diff --git a/.gitignore b/.gitignore index 180462a32f..7fe2778755 100644 --- a/.gitignore +++ b/.gitignore @@ -62,3 +62,5 @@ jmeter/src/main/resources/*-JMeter.csv **/dist **/tmp **/out-tsc +**/nbproject/ +**/nb-configuration.xml \ No newline at end of file diff --git a/JGit/pom.xml b/JGit/pom.xml index d1ebd364da..176d55d321 100644 --- a/JGit/pom.xml +++ b/JGit/pom.xml @@ -3,10 +3,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - JGitSnippets + JGit 1.0-SNAPSHOT jar http://maven.apache.org + JGit com.baeldung diff --git a/README.md b/README.md index d018783465..8e0a5eb9ee 100644 --- a/README.md +++ b/README.md @@ -2,41 +2,27 @@ The "REST with Spring" Classes ============================== -After 5 months of work, here's the Master Class of REST With Spring:
-**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)** +Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material):
+**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)** And here's the Master Class of Learn Spring Security:
-**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)** +**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)** -Spring Tutorials +Java and Spring Tutorials ================ -This project is **a collection of small and focused tutorials** each covering a single and well defined area of development. -Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`). +This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem. +A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Securiyt. In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`. + Building the project ==================== To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false` -Working with the code in Eclipse -================================ -Any IDE can be used to work with the projects, but if you're using Eclipse, consider the following. - -- import the included **formatter** in Eclipse: -`https://github.com/eugenp/tutorials/tree/master/eclipse` - - -CI - Jenkins -================================ -This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)** - -### Relevant Articles: -================================ - -- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure) -- [Apache Maven Tutorial](http://www.baeldung.com/maven) -- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library) +Building a single module +==================== +To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory diff --git a/Twitter4J/pom.xml b/Twitter4J/pom.xml index 80236a2cd4..982c1adc23 100644 --- a/Twitter4J/pom.xml +++ b/Twitter4J/pom.xml @@ -1,13 +1,9 @@ 4.0.0 - - com.mabsisa Twitter4J jar - 1.0-SNAPSHOT Twitter4J - http://maven.apache.org com.baeldung @@ -23,27 +19,6 @@ - - ${project.artifactId} - - - src/main/resources - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/ApplicationTest.java - - - - - - 4.0.6 diff --git a/activejdbc/pom.xml b/activejdbc/pom.xml index 0c8047f10b..542e674ff3 100644 --- a/activejdbc/pom.xml +++ b/activejdbc/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung activejdbc 1.0-SNAPSHOT jar @@ -79,55 +78,11 @@ - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - brief - true - false - - **/*Spec*.java - **/*Test*.java - - - **/helpers/* - **/*$* - - - - - - snapshots1 - JavaLite Snapshots1 - http://repo.javalite.io/ - - true - always - warn - - - - - - - snapshots2 - JavaLite Snapshots2 - http://repo.javalite.io/ - - true - always - warn - - - - - 1.4.13 + 2.0 development.test,development 5.1.34 diff --git a/activejdbc/src/main/java/com/baeldung/model/Employee.java b/activejdbc/src/main/java/com/baeldung/model/Employee.java index b7fa8aaf1f..e6e9be2aac 100644 --- a/activejdbc/src/main/java/com/baeldung/model/Employee.java +++ b/activejdbc/src/main/java/com/baeldung/model/Employee.java @@ -16,4 +16,8 @@ public class Employee extends Model { set("created_by",createdBy); } + public String getLastName() { + return getString("last_name"); + } + } diff --git a/activejdbc/src/main/java/com/baeldung/model/Role.java b/activejdbc/src/main/java/com/baeldung/model/Role.java index 3f425dbe6b..bbd5a7d169 100644 --- a/activejdbc/src/main/java/com/baeldung/model/Role.java +++ b/activejdbc/src/main/java/com/baeldung/model/Role.java @@ -15,4 +15,8 @@ public class Role extends Model { set("role_name",role); set("created_by",createdBy); } + + public String getRoleName() { + return getString("role_name"); + } } diff --git a/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppTest.java b/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java similarity index 97% rename from activejdbc/src/test/java/com/baeldung/ActiveJDBCAppTest.java rename to activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java index 316dc34712..22eb87f930 100644 --- a/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppTest.java +++ b/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java @@ -7,7 +7,7 @@ import org.junit.Test; import java.util.List; -public class ActiveJDBCAppTest extends DBSpec +public class ActiveJDBCAppManualTest extends DBSpec { @Test public void ifEmployeeCreated_thenIsValid() { diff --git a/algorithms/README.md b/algorithms/README.md index 47ddd7028a..9d347869bd 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -24,3 +24,10 @@ - [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) - [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element) - [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation) +- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap) +- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points) +- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines) +- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters) +- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred) +- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort) +- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage) diff --git a/algorithms/pom.xml b/algorithms/pom.xml index eda87d6c75..db4a1c2eff 100644 --- a/algorithms/pom.xml +++ b/algorithms/pom.xml @@ -17,6 +17,11 @@ commons-math3 ${commons-math3.version} + + commons-codec + commons-codec + ${commons-codec.version} + org.projectlombok lombok @@ -85,6 +90,7 @@ 3.7.0 1.0.1 3.9.0 + 1.11 \ No newline at end of file diff --git a/algorithms/roundUpToHundred/.gitignore b/algorithms/roundUpToHundred/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/algorithms/roundUpToHundred/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java new file mode 100644 index 0000000000..f5024c227d --- /dev/null +++ b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java @@ -0,0 +1,20 @@ +package com.java.src; + +import java.util.Scanner; + +public class RoundUpToHundred { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + double input = scanner.nextDouble(); + scanner.close(); + + RoundUpToHundred.round(input); + } + + static long round(double input) { + long i = (long) Math.ceil(input); + return ((i + 99) / 100) * 100; + }; + +} diff --git a/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java new file mode 100644 index 0000000000..f35a9a249f --- /dev/null +++ b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java @@ -0,0 +1,14 @@ +package com.java.src; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class RoundUpToHundredTest { + @Test + public void givenInput_whenRound_thenRoundUpToTheNearestHundred() { + assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99)); + assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2)); + assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400)); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java b/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java new file mode 100644 index 0000000000..d3e251d3fd --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java @@ -0,0 +1,110 @@ +package com.baeldung.algorithms.conversion; + +import java.math.BigInteger; + +import javax.xml.bind.DatatypeConverter; + +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.binary.Hex; + +import com.google.common.io.BaseEncoding; + +public class HexStringConverter { + + /** + * Create a byte Array from String of hexadecimal digits using Character conversion + * @param hexString - Hexadecimal digits as String + * @return Desired byte Array + */ + public byte[] decodeHexString(String hexString) { + if (hexString.length() % 2 == 1) { + throw new IllegalArgumentException("Invalid hexadecimal String supplied."); + } + byte[] bytes = new byte[hexString.length() / 2]; + + for (int i = 0; i < hexString.length(); i += 2) { + bytes[i / 2] = hexToByte(hexString.substring(i, i + 2)); + } + return bytes; + } + + /** + * Create a String of hexadecimal digits from a byte Array using Character conversion + * @param byteArray - The byte Array + * @return Desired String of hexadecimal digits in lower case + */ + public String encodeHexString(byte[] byteArray) { + StringBuffer hexStringBuffer = new StringBuffer(); + for (int i = 0; i < byteArray.length; i++) { + hexStringBuffer.append(byteToHex(byteArray[i])); + } + return hexStringBuffer.toString(); + } + + public String byteToHex(byte num) { + char[] hexDigits = new char[2]; + hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16); + hexDigits[1] = Character.forDigit((num & 0xF), 16); + return new String(hexDigits); + } + + public byte hexToByte(String hexString) { + int firstDigit = toDigit(hexString.charAt(0)); + int secondDigit = toDigit(hexString.charAt(1)); + return (byte) ((firstDigit << 4) + secondDigit); + } + + private int toDigit(char hexChar) { + int digit = Character.digit(hexChar, 16); + if(digit == -1) { + throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar); + } + return digit; + } + + public String encodeUsingBigIntegerToString(byte[] bytes) { + BigInteger bigInteger = new BigInteger(1, bytes); + return bigInteger.toString(16); + } + + public String encodeUsingBigIntegerStringFormat(byte[] bytes) { + BigInteger bigInteger = new BigInteger(1, bytes); + return String.format("%0" + (bytes.length << 1) + "x", bigInteger); + } + + public byte[] decodeUsingBigInteger(String hexString) { + byte[] byteArray = new BigInteger(hexString, 16).toByteArray(); + if (byteArray[0] == 0) { + byte[] output = new byte[byteArray.length - 1]; + System.arraycopy(byteArray, 1, output, 0, output.length); + return output; + } + return byteArray; + } + + public String encodeUsingDataTypeConverter(byte[] bytes) { + return DatatypeConverter.printHexBinary(bytes); + } + + public byte[] decodeUsingDataTypeConverter(String hexString) { + return DatatypeConverter.parseHexBinary(hexString); + } + + public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException { + return Hex.encodeHexString(bytes); + } + + public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException { + return Hex.decodeHex(hexString); + } + + public String encodeUsingGuava(byte[] bytes) { + return BaseEncoding.base16() + .encode(bytes); + } + + public byte[] decodeUsingGuava(String hexString) { + return BaseEncoding.base16() + .decode(hexString.toUpperCase()); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java b/algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java new file mode 100644 index 0000000000..0c8eb86a38 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.distancebetweenpoints; + +import java.awt.geom.Point2D; + +public class DistanceBetweenPointsService { + + public double calculateDistanceBetweenPoints( + double x1, + double y1, + double x2, + double y2) { + + return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1)); + } + + public double calculateDistanceBetweenPointsWithHypot( + double x1, + double y1, + double x2, + double y2) { + + double ac = Math.abs(y2 - y1); + double cb = Math.abs(x2 - x1); + + return Math.hypot(ac, cb); + } + + public double calculateDistanceBetweenPointsWithPoint2D( + double x1, + double y1, + double x2, + double y2) { + + return Point2D.distance(x1, y1, x2, y2); + + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java b/algorithms/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java new file mode 100644 index 0000000000..02dd485cf1 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java @@ -0,0 +1,41 @@ +package com.baeldung.algorithms.insertionsort; + +public class InsertionSort { + + public static void insertionSortImperative(int[] input) { + for (int i = 1; i < input.length; i++) { + int key = input[i]; + int j = i - 1; + while (j >= 0 && input[j] > key) { + input[j + 1] = input[j]; + j = j - 1; + } + input[j + 1] = key; + } + } + + public static void insertionSortRecursive(int[] input) { + insertionSortRecursive(input, input.length); + } + + private static void insertionSortRecursive(int[] input, int i) { + // base case + if (i <= 1) { + return; + } + + // sort the first i - 1 elements of the array + insertionSortRecursive(input, i - 1); + + // then find the correct position of the element at position i + int key = input[i - 1]; + int j = i - 2; + // shifting the elements from their position by 1 + while (j >= 0 && input[j] > key) { + input[j + 1] = input[j]; + j = j - 1; + } + // inserting the key at the appropriate position + input[j + 1] = key; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java b/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java index 822abdae02..7054979ada 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java @@ -98,7 +98,7 @@ public class FindKthLargest { private int randomPartition(Integer arr[], int left, int right) { int n = right - left + 1; - int pivot = (int) (Math.random()) % n; + int pivot = (int) (Math.random() * n); swap(arr, left + pivot, right); return partition(arr, left, right); } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java b/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java new file mode 100644 index 0000000000..35d6c8b424 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java @@ -0,0 +1,21 @@ +package com.baeldung.algorithms.linesintersection; + +import java.awt.Point; +import java.util.Optional; + +public class LinesIntersectionService { + + public Optional calculateIntersectionPoint(double m1, double b1, double m2, double b2) { + + if (m1 == m2) { + return Optional.empty(); + } + + double x = (b2 - b1) / (m1 - m2); + double y = m1 * x + b1; + + Point point = new Point(); + point.setLocation(x, y); + return Optional.of(point); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java index d855f775a8..5d4b265500 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java @@ -87,7 +87,7 @@ public class State { void randomPlay() { List availablePositions = this.board.getEmptyPositions(); int totalPossibilities = availablePositions.size(); - int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1)); + int selectRandom = (int) (Math.random() * totalPossibilities); this.board.performMove(this.playerNo, availablePositions.get(selectRandom)); } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java index 20f9e992b5..0ad6510e50 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java @@ -65,7 +65,7 @@ public class Node { public Node getRandomChildNode() { int noOfPossibleMoves = this.childArray.size(); - int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1)); + int selectRandom = (int) (Math.random() * noOfPossibleMoves); return this.childArray.get(selectRandom); } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java b/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java new file mode 100644 index 0000000000..0deb48b6a0 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java @@ -0,0 +1,50 @@ +package com.baeldung.algorithms.mergesort; + +public class MergeSort { + + public static void main(String[] args) { + int[] a = { 5, 1, 6, 2, 3, 4 }; + mergeSort(a, a.length); + for (int i = 0; i < a.length; i++) + System.out.println(a[i]); + } + + public static void mergeSort(int[] a, int n) { + if (n < 2) + return; + int mid = n / 2; + int[] l = new int[mid]; + int[] r = new int[n - mid]; + + for (int i = 0; i < mid; i++) { + l[i] = a[i]; + } + for (int i = mid; i < n; i++) { + r[i - mid] = a[i]; + } + mergeSort(l, mid); + mergeSort(r, n - mid); + + merge(a, l, r, mid, n - mid); + } + + public static void merge(int[] a, int[] l, int[] r, int left, int right) { + + int i = 0, j = 0, k = 0; + + while (i < left && j < right) { + + if (l[i] < r[j]) + a[k++] = l[i++]; + else + a[k++] = r[j++]; + + } + + while (i < left) + a[k++] = l[i++]; + + while (j < right) + a[k++] = r[j++]; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java b/algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java new file mode 100644 index 0000000000..e113cc3242 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java @@ -0,0 +1,39 @@ +package com.baeldung.algorithms.quicksort; + +public class QuickSort { + + public static void quickSort(int arr[], int begin, int end) + { + if (begin < end) { + int partitionIndex = partition(arr, begin, end); + + // Recursively sort elements of the 2 sub-arrays + quickSort(arr, begin, partitionIndex-1); + quickSort(arr, partitionIndex+1, end); + } + } + + private static int partition(int arr[], int begin, int end) + { + int pivot = arr[end]; + int i = (begin-1); + + for (int j=begin; j other.topRight.getY()) { + return false; + } + // one rectangle is to the left of the other + if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) { + return false; + } + return true; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java b/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java new file mode 100644 index 0000000000..2dd1fdcb75 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java @@ -0,0 +1,35 @@ +package com.baeldung.algorithms.string; + +public class EnglishAlphabetLetters { + + public static boolean checkStringForAllTheLetters(String input) { + boolean[] visited = new boolean[26]; + + int index = 0; + + for (int id = 0; id < input.length(); id++) { + if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') { + index = input.charAt(id) - 'a'; + } else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') { + index = input.charAt(id) - 'A'; + } + visited[index] = true; + } + + for (int id = 0; id < 26; id++) { + if (!visited[id]) { + return false; + } + } + return true; + } + + public static boolean checkStringForAllLetterUsingStream(String input) { + long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count(); + return c == 26; + } + + public static void main(String[] args) { + checkStringForAllLetterUsingStream("intit"); + } +} \ No newline at end of file diff --git a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java similarity index 94% rename from algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java index b0218ae23e..2ac7adc3aa 100644 --- a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java similarity index 92% rename from algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java index fa8ecdee77..e819da4b36 100644 --- a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java similarity index 98% rename from algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java index 68386278fc..bbc4d4f398 100644 --- a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java similarity index 98% rename from algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java index e4746b521c..e817d195b3 100644 --- a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import com.baeldung.algorithms.hillclimbing.HillClimbing; import com.baeldung.algorithms.hillclimbing.State; diff --git a/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java similarity index 99% rename from algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java index 01f9ca2f76..2cda0ccb36 100644 --- a/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup; import com.baeldung.algorithms.middleelementlookup.Node; diff --git a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java similarity index 98% rename from algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java index 99e962773f..fddccfcd9f 100644 --- a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import com.baeldung.algorithms.automata.*; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java similarity index 90% rename from algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java index 6ee129ece9..2ce7d75e43 100644 --- a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java similarity index 94% rename from algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java index c98a8a53f3..dfe015aad2 100755 --- a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; diff --git a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java similarity index 95% rename from algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java index 74db4236b9..826682d373 100644 --- a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java @@ -1,4 +1,4 @@ -package algorithms.binarysearch; +package com.baeldung.algorithms.binarysearch; import java.util.Arrays; import java.util.List; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java new file mode 100644 index 0000000000..be61802705 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java @@ -0,0 +1,127 @@ +package com.baeldung.algorithms.conversion; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import org.apache.commons.codec.DecoderException; +import org.hamcrest.text.IsEqualIgnoringCase; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.algorithms.conversion.HexStringConverter; + +public class ByteArrayConverterUnitTest { + + private HexStringConverter hexStringConverter; + + @Before + public void setup() { + hexStringConverter = new HexStringConverter(); + } + + @Test + public void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + if(hexString.charAt(0) == '0') { + hexString = hexString.substring(1); + } + String output = hexStringConverter.encodeUsingBigIntegerToString(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldDecodeHexStringToByteArrayUsingBigInteger() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + byte[] output = hexStringConverter.decodeUsingBigInteger(hexString); + assertArrayEquals(bytes, output); + } + + @Test + public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + String output = hexStringConverter.encodeHexString(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + byte[] output = hexStringConverter.decodeHexString(hexString); + assertArrayEquals(bytes, output); + } + + @Test(expected=IllegalArgumentException.class) + public void shouldDecodeHexToByteWithInvalidHexCharacter() { + hexStringConverter.hexToByte("fg"); + } + + @Test + public void shouldEncodeByteArrayToHexStringDataTypeConverter() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + String output = hexStringConverter.encodeUsingDataTypeConverter(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString); + assertArrayEquals(bytes, output); + } + + @Test + public void shouldEncodeByteArrayToHexStringUsingGuava() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + String output = hexStringConverter.encodeUsingGuava(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldDecodeHexStringToByteArrayUsingGuava() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + byte[] output = hexStringConverter.decodeUsingGuava(hexString); + assertArrayEquals(bytes, output); + } + + @Test + public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + String output = hexStringConverter.encodeUsingApacheCommons(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString); + assertArrayEquals(bytes, output); + } + + private String getSampleHexString() { + return "0af50c0e2d10"; + } + + private byte[] getSampleBytes() { + return new byte[] { 10, -11, 12, 14, 45, 16 }; + } + +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java new file mode 100644 index 0000000000..785afdbb2b --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.algorithms.distancebetweenpoints; + +import org.junit.Test; + +import com.baeldung.algorithms.distancebetweenpoints.DistanceBetweenPointsService; + +import static org.junit.Assert.assertEquals; + +public class DistanceBetweenPointsServiceUnitTest { + + private DistanceBetweenPointsService service = new DistanceBetweenPointsService(); + + @Test + public void givenTwoPoints_whenCalculateDistanceByFormula_thenCorrect() { + + double x1 = 3; + double y1 = 4; + double x2 = 7; + double y2 = 1; + + double distance = service.calculateDistanceBetweenPoints(x1, y1, x2, y2); + + assertEquals(distance, 5, 0.001); + + } + + @Test + public void givenTwoPoints_whenCalculateDistanceWithHypot_thenCorrect() { + + double x1 = 3; + double y1 = 4; + double x2 = 7; + double y2 = 1; + + double distance = service.calculateDistanceBetweenPointsWithHypot(x1, y1, x2, y2); + + assertEquals(distance, 5, 0.001); + + } + + @Test + public void givenTwoPoints_whenCalculateDistanceWithPoint2D_thenCorrect() { + + double x1 = 3; + double y1 = 4; + double x2 = 7; + double y2 = 1; + + double distance = service.calculateDistanceBetweenPointsWithPoint2D(x1, y1, x2, y2); + + assertEquals(distance, 5, 0.001); + + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java new file mode 100644 index 0000000000..b3d7e8c534 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.algorithms.insertionsort; + +import com.baeldung.algorithms.insertionsort.InsertionSort; +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; + +public class InsertionSortUnitTest { + + @Test + public void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() { + int[] input = {6, 2, 3, 4, 5, 1}; + InsertionSort.insertionSortImperative(input); + int[] expected = {1, 2, 3, 4, 5, 6}; + assertArrayEquals("the two arrays are not equal", expected, input); + } + + @Test + public void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() { + int[] input = {6, 4, 5, 2, 3, 1}; + InsertionSort.insertionSortRecursive(input); + int[] expected = {1, 2, 3, 4, 5, 6}; + assertArrayEquals("the two arrays are not equal", expected, input); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java new file mode 100644 index 0000000000..22371107f3 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.algorithms.linesintersection; + +import java.awt.Point; +import java.util.Optional; + +import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertEquals; + +public class LinesIntersectionServiceUnitTest { + private LinesIntersectionService service = new LinesIntersectionService(); + + @Test + public void givenNotParallelLines_whenCalculatePoint_thenPresent() { + + double m1 = 0; + double b1 = 0; + double m2 = 1; + double b2 = -1; + + Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2); + + assertTrue(point.isPresent()); + assertEquals(point.get().getX(), 1, 0.001); + assertEquals(point.get().getY(), 0, 0.001); + } + + @Test + public void givenParallelLines_whenCalculatePoint_thenEmpty() { + double m1 = 1; + double b1 = 0; + double m2 = 1; + double b2 = -1; + + Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2); + + assertFalse(point.isPresent()); + } +} diff --git a/algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java similarity index 98% rename from algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java index edbf21390d..59afed65de 100644 --- a/algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java @@ -1,4 +1,4 @@ -package algorithms.mcts; +package com.baeldung.algorithms.mcts; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java new file mode 100644 index 0000000000..5cd14b7bd0 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.algorithms.mergesort; + +import org.junit.Assert; + +import org.junit.Test; + +public class MergeSortUnitTest { + + @Test + public void positiveTest() { + int[] actual = { 5, 1, 6, 2, 3, 4 }; + int[] expected = { 1, 2, 3, 4, 5, 6 }; + MergeSort.mergeSort(actual, actual.length); + Assert.assertArrayEquals(expected, actual); + } + +} diff --git a/algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java similarity index 95% rename from algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java index c07975bca0..59f0fcf053 100644 --- a/algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java @@ -1,4 +1,4 @@ -package algorithms.minimax; +package com.baeldung.algorithms.minimax; import org.junit.Before; import org.junit.Test; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java new file mode 100644 index 0000000000..c9af5b4bf8 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.algorithms.quicksort; + +import com.baeldung.algorithms.quicksort.QuickSort; +import org.junit.Assert; +import org.junit.Test; + +public class QuickSortUnitTest { + + @Test + public void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() { + int[] actual = { 9, 5, 1, 0, 6, 2, 3, 4, 7, 8 }; + int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + QuickSort.quickSort(actual, 0, actual.length-1); + Assert.assertArrayEquals(expected, actual); + } + +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java new file mode 100644 index 0000000000..cd8c7c1241 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.algorithms.quicksort; + +import org.junit.Assert; +import org.junit.Test; + +public class ThreeWayQuickSortUnitTest { + + @Test + public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { + int[] actual = { 3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3 }; + int[] expected = { 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7 }; + ThreeWayQuickSort.threeWayQuickSort(actual, 0, actual.length-1); + Assert.assertArrayEquals(expected, actual); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java new file mode 100644 index 0000000000..6707b34477 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.algorithms.rectanglesoverlap; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import org.junit.Test; + +import com.baeldung.algorithms.rectanglesoverlap.Point; +import com.baeldung.algorithms.rectanglesoverlap.Rectangle; + +public class RectangleUnitTest { + + @Test + public void givenTwoOverlappingRectangles_whenisOverlappingCalled_shouldReturnTrue() { + Rectangle rectangle1 = new Rectangle(new Point(2, 1), new Point(4, 3)); + Rectangle rectangle2 = new Rectangle(new Point(1, 1), new Point(6, 4)); + assertTrue(rectangle1.isOverlapping(rectangle2)); + + rectangle1 = new Rectangle(new Point(-5, -2), new Point(2, 3)); + rectangle2 = new Rectangle(new Point(-2, -1), new Point(5, 2)); + assertTrue(rectangle1.isOverlapping(rectangle2)); + + rectangle1 = new Rectangle(new Point(-5, 1), new Point(2, 4)); + rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5)); + assertTrue(rectangle1.isOverlapping(rectangle2)); + } + + @Test + public void givenTwoNonOverlappingRectangles_whenisOverlappingCalled_shouldReturnFalse() { + Rectangle rectangle1 = new Rectangle(new Point(-5, 1), new Point(-3, 4)); + Rectangle rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5)); + assertFalse(rectangle1.isOverlapping(rectangle2)); + + rectangle1 = new Rectangle(new Point(-5, 1), new Point(3, 4)); + rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, -1)); + assertFalse(rectangle1.isOverlapping(rectangle2)); + + rectangle1 = new Rectangle(new Point(-2, 1), new Point(0, 3)); + rectangle2 = new Rectangle(new Point(3, 1), new Point(5, 4)); + assertFalse(rectangle1.isOverlapping(rectangle2)); + } + +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java new file mode 100644 index 0000000000..54863cddc8 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.string; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class EnglishAlphabetLettersUnitTest { + + @Test + void givenString_whenContainsAllCharacter_thenTrue() { + String input = "Farmer jack realized that big yellow quilts were expensive"; + Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input)); + } + + @Test + void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() { + String input = "Farmer jack realized that big yellow quilts were expensive"; + Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input)); + } + +} diff --git a/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java b/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java similarity index 81% rename from animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java rename to animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java index 8ecb1bc629..dcfd22ff87 100644 --- a/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java +++ b/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java @@ -7,7 +7,7 @@ import junit.framework.TestSuite; /** * Unit test for simple App. */ -public class AppTest +public class AppUnitTest extends TestCase { /** @@ -15,7 +15,7 @@ public class AppTest * * @param testName name of the test case */ - public AppTest( String testName ) + public AppUnitTest( String testName ) { super( testName ); } @@ -25,7 +25,7 @@ public class AppTest */ public static Test suite() { - return new TestSuite( AppTest.class ); + return new TestSuite( AppUnitTest.class ); } /** diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml index 39da518269..ddf5844271 100644 --- a/apache-avro/pom.xml +++ b/apache-avro/pom.xml @@ -4,8 +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 com.baeldung - apache-avro-tutorial + apache-avro 0.0.1-SNAPSHOT + Apache Avro UTF-8 diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java index d2219a45f2..7d30c3d1ee 100644 --- a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java +++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java @@ -5,29 +5,37 @@ import org.apache.avro.io.DatumReader; import org.apache.avro.io.Decoder; import org.apache.avro.io.DecoderFactory; import org.apache.avro.specific.SpecificDatumReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; public class AvroDeSerealizer { -public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data){ - DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class); - Decoder decoder = null; - try { - decoder = DecoderFactory.get().jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data)); - return reader.read(null, decoder); - } catch (IOException e) { - return null; - } -} + private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class); -public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data){ - DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class); - Decoder decoder = DecoderFactory.get().binaryDecoder(data, null); - try { - return employeeReader.read(null, decoder); - } catch (IOException e) { + public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) { + DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class); + Decoder decoder = null; + try { + decoder = DecoderFactory.get() + .jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data)); + return reader.read(null, decoder); + } catch (IOException e) { + logger.error("Deserialization error" + e.getMessage()); + } + return null; + } + + public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) { + DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class); + Decoder decoder = DecoderFactory.get() + .binaryDecoder(data, null); + try { + return employeeReader.read(null, decoder); + } catch (IOException e) { + logger.error("Deserialization error" + e.getMessage()); + } return null; } } -} diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java index f56c89e201..767b688dea 100644 --- a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java +++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java @@ -3,42 +3,48 @@ package com.baeldung.avro.util.serealization; import com.baeldung.avro.util.model.AvroHttpRequest; import org.apache.avro.io.*; import org.apache.avro.specific.SpecificDatumWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; public class AvroSerealizer { -public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request){ - DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class); - byte[] data = new byte[0]; - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - Encoder jsonEncoder = null; - try { - jsonEncoder = EncoderFactory.get().jsonEncoder(AvroHttpRequest.getClassSchema(), stream); - writer.write(request, jsonEncoder); - jsonEncoder.flush(); - data = stream.toByteArray(); - } catch (IOException e) { - data =null; - } - return data; -} + private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class); -public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request){ - DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class); - byte[] data = new byte[0]; - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - Encoder jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null); - try { - writer.write(request, jsonEncoder); - jsonEncoder.flush(); - data = stream.toByteArray(); - } catch (IOException e) { - data = null; + public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) { + DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class); + byte[] data = new byte[0]; + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Encoder jsonEncoder = null; + try { + jsonEncoder = EncoderFactory.get() + .jsonEncoder(AvroHttpRequest.getClassSchema(), stream); + writer.write(request, jsonEncoder); + jsonEncoder.flush(); + data = stream.toByteArray(); + } catch (IOException e) { + logger.error("Serialization error " + e.getMessage()); + } + return data; } - return data; -} + public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) { + DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class); + byte[] data = new byte[0]; + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Encoder jsonEncoder = EncoderFactory.get() + .binaryEncoder(stream, null); + try { + writer.write(request, jsonEncoder); + jsonEncoder.flush(); + data = stream.toByteArray(); + } catch (IOException e) { + logger.error("Serialization error " + e.getMessage()); + } + + return data; + } } diff --git a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java deleted file mode 100644 index 937a4ae650..0000000000 --- a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.avro.util.serealization; - -import com.baeldung.avro.util.model.Active; -import com.baeldung.avro.util.model.AvroHttpRequest; -import com.baeldung.avro.util.model.ClientIdentifier; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import static org.junit.Assert.*; - -public class AvroSerealizerDeSerealizerTest { - - AvroSerealizer serealizer; - AvroDeSerealizer deSerealizer; - AvroHttpRequest request; - - @Before - public void setUp() throws Exception { - serealizer = new AvroSerealizer(); - deSerealizer = new AvroDeSerealizer(); - - ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder(). - setHostName("localhost").setIpAddress("255.255.255.0").build(); - - List employees = new ArrayList(); - employees.add("James"); - employees.add("Alice"); - employees.add("David"); - employees.add("Han"); - - request = AvroHttpRequest.newBuilder().setRequestTime(01l) - .setActive(Active.YES).setClientIdentifier(clientIdentifier) - .setEmployeeNames(employees).build(); - } - - @After - public void tearDown() throws Exception { - } - -@Test -public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){ - byte[] data = serealizer.serealizeAvroHttpRequestJSON(request); - assertTrue(Objects.nonNull(data)); - assertTrue(data.length > 0); -} - -@Test -public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){ - byte[] data = serealizer.serealizeAvroHttpRequestBinary(request); - assertTrue(Objects.nonNull(data)); - assertTrue(data.length > 0); -} - -@Test -public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){ - byte[] data = serealizer.serealizeAvroHttpRequestJSON(request); - AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data); - assertEquals(actualRequest,request); - assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime())); -} - -@Test -public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){ - byte[] data = serealizer.serealizeAvroHttpRequestBinary(request); - AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data); - assertEquals(actualRequest,request); - assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime())); -} -} - diff --git a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java new file mode 100644 index 0000000000..992ea806c3 --- /dev/null +++ b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.avro.util.serealization; + +import com.baeldung.avro.util.model.Active; +import com.baeldung.avro.util.model.AvroHttpRequest; +import com.baeldung.avro.util.model.ClientIdentifier; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import static org.junit.Assert.*; + +public class AvroSerealizerDeSerealizerUnitTest { + + AvroSerealizer serealizer; + AvroDeSerealizer deSerealizer; + AvroHttpRequest request; + + @Before + public void setUp() throws Exception { + serealizer = new AvroSerealizer(); + deSerealizer = new AvroDeSerealizer(); + + ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder() + .setHostName("localhost") + .setIpAddress("255.255.255.0") + .build(); + + List employees = new ArrayList(); + employees.add("James"); + employees.add("Alice"); + employees.add("David"); + employees.add("Han"); + + request = AvroHttpRequest.newBuilder() + .setRequestTime(01l) + .setActive(Active.YES) + .setClientIdentifier(clientIdentifier) + .setEmployeeNames(employees) + .build(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() { + byte[] data = serealizer.serealizeAvroHttpRequestJSON(request); + assertTrue(Objects.nonNull(data)); + assertTrue(data.length > 0); + } + + @Test + public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() { + byte[] data = serealizer.serealizeAvroHttpRequestBinary(request); + assertTrue(Objects.nonNull(data)); + assertTrue(data.length > 0); + } + + @Test + public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() { + byte[] data = serealizer.serealizeAvroHttpRequestJSON(request); + AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data); + assertEquals(actualRequest, request); + assertTrue(actualRequest.getRequestTime() + .equals(request.getRequestTime())); + } + + @Test + public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() { + byte[] data = serealizer.serealizeAvroHttpRequestBinary(request); + AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data); + assertEquals(actualRequest, request); + assertTrue(actualRequest.getRequestTime() + .equals(request.getRequestTime())); + } + +} + diff --git a/apache-cxf/README.md b/apache-cxf/README.md index 1e66ce5da8..d03999dce3 100644 --- a/apache-cxf/README.md +++ b/apache-cxf/README.md @@ -3,3 +3,4 @@ - [Apache CXF Support for RESTful Web Services](http://www.baeldung.com/apache-cxf-rest-api) - [A Guide to Apache CXF with Spring](http://www.baeldung.com/apache-cxf-with-spring) - [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf) +- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse) diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml index 53d9d4054c..8918fd4450 100644 --- a/apache-cxf/pom.xml +++ b/apache-cxf/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung apache-cxf @@ -17,6 +17,7 @@ cxf-spring cxf-jaxrs-implementation cxf-aegis + sse-jaxrs diff --git a/apache-cxf/sse-jaxrs/pom.xml b/apache-cxf/sse-jaxrs/pom.xml new file mode 100644 index 0000000000..d4b6c19d03 --- /dev/null +++ b/apache-cxf/sse-jaxrs/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + + sse-jaxrs + pom + + + com.baeldung + apache-cxf + 0.0.1-SNAPSHOT + + + + sse-jaxrs-server + sse-jaxrs-client + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml new file mode 100644 index 0000000000..0f5406fbc7 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + + com.baeldung + sse-jaxrs + 0.0.1-SNAPSHOT + + + sse-jaxrs-client + + + 3.2.0 + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + singleEvent + + java + + + com.baeldung.sse.jaxrs.client.SseClientApp + + + + broadcast + + java + + + com.baeldung.sse.jaxrs.client.SseClientBroadcastApp + + + + + + + + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + + + org.apache.cxf + cxf-rt-rs-sse + ${cxf-version} + + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java new file mode 100644 index 0000000000..5d42b3a243 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java @@ -0,0 +1,48 @@ +package com.baeldung.sse.jaxrs.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.sse.InboundSseEvent; +import javax.ws.rs.sse.SseEventSource; +import java.util.function.Consumer; + +public class SseClientApp { + + private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices"; + + public static void main(String... args) throws Exception { + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(url); + try (SseEventSource eventSource = SseEventSource.target(target).build()) { + + eventSource.register(onEvent, onError, onComplete); + eventSource.open(); + + //Consuming events for one hour + Thread.sleep(60 * 60 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + client.close(); + System.out.println("End"); + } + + // A new event is received + private static Consumer onEvent = (inboundSseEvent) -> { + String data = inboundSseEvent.readData(); + System.out.println(data); + }; + + //Error + private static Consumer onError = (throwable) -> { + throwable.printStackTrace(); + }; + + //Connection close and there is nothing to receive + private static Runnable onComplete = () -> { + System.out.println("Done!"); + }; + +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java new file mode 100644 index 0000000000..9afc187a6d --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java @@ -0,0 +1,52 @@ +package com.baeldung.sse.jaxrs.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.sse.InboundSseEvent; +import javax.ws.rs.sse.SseEventSource; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +public class SseClientBroadcastApp { + + private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe"; + + + public static void main(String... args) throws Exception { + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(subscribeUrl); + try (final SseEventSource eventSource = SseEventSource.target(target) + .reconnectingEvery(5, TimeUnit.SECONDS) + .build()) { + eventSource.register(onEvent, onError, onComplete); + eventSource.open(); + System.out.println("Wainting for incoming event ..."); + + //Consuming events for one hour + Thread.sleep(60 * 60 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + client.close(); + System.out.println("End"); + } + + // A new event is received + private static Consumer onEvent = (inboundSseEvent) -> { + String data = inboundSseEvent.readData(); + System.out.println(data); + }; + + //Error + private static Consumer onError = (throwable) -> { + throwable.printStackTrace(); + }; + + //Connection close and there is nothing to receive + private static Runnable onComplete = () -> { + System.out.println("Done!"); + }; + +} diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/resources/logback.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml similarity index 100% rename from enterprise-patterns/intercepting-filter-pattern/src/main/resources/logback.xml rename to apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml new file mode 100644 index 0000000000..2e82dc3829 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + + + com.baeldung + sse-jaxrs + 0.0.1-SNAPSHOT + + + sse-jaxrs-server + war + + + 2.4.2 + false + 18.0.0.2 + + + + ${project.artifactId} + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${liberty-maven-plugin.version} + + + io.openliberty + openliberty-webProfile8 + ${openliberty-version} + zip + + project + true + src/main/liberty/config/server.xml + + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + + + + + javax.ws.rs + javax.ws.rs-api + 2.1 + provided + + + javax.enterprise + cdi-api + 2.0 + provided + + + javax.json.bind + javax.json.bind-api + 1.0 + provided + + + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java new file mode 100644 index 0000000000..058d19f045 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java @@ -0,0 +1,8 @@ +package com.baeldung.sse.jaxrs; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("sse") +public class AppConfig extends Application { +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java new file mode 100644 index 0000000000..1f60168a1b --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java @@ -0,0 +1,119 @@ +package com.baeldung.sse.jaxrs; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.sse.OutboundSseEvent; +import javax.ws.rs.sse.Sse; +import javax.ws.rs.sse.SseBroadcaster; +import javax.ws.rs.sse.SseEventSink; + +@ApplicationScoped +@Path("stock") +public class SseResource { + + @Inject + private StockService stockService; + + private Sse sse; + private SseBroadcaster sseBroadcaster; + private OutboundSseEvent.Builder eventBuilder; + + @Context + public void setSse(Sse sse) { + this.sse = sse; + this.eventBuilder = sse.newEventBuilder(); + this.sseBroadcaster = sse.newBroadcaster(); + } + + @GET + @Path("prices") + @Produces("text/event-stream") + public void getStockPrices(@Context SseEventSink sseEventSink, + @HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastReceivedId) { + + int lastEventId = 1; + if (lastReceivedId != -1) { + lastEventId = ++lastReceivedId; + } + boolean running = true; + while (running) { + Stock stock = stockService.getNextTransaction(lastEventId); + if (stock != null) { + OutboundSseEvent sseEvent = this.eventBuilder + .name("stock") + .id(String.valueOf(lastEventId)) + .mediaType(MediaType.APPLICATION_JSON_TYPE) + .data(Stock.class, stock) + .reconnectDelay(3000) + .comment("price change") + .build(); + sseEventSink.send(sseEvent); + lastEventId++; + } + //Simulate connection close + if (lastEventId % 5 == 0) { + sseEventSink.close(); + break; + } + + try { + //Wait 5 seconds + Thread.sleep(5 * 1000); + } catch (InterruptedException ex) { + // ... + } + //Simulatae a while boucle break + running = lastEventId <= 2000; + } + sseEventSink.close(); + } + + @GET + @Path("subscribe") + @Produces(MediaType.SERVER_SENT_EVENTS) + public void listen(@Context SseEventSink sseEventSink) { + sseEventSink.send(sse.newEvent("Welcome !")); + this.sseBroadcaster.register(sseEventSink); + sseEventSink.send(sse.newEvent("You are registred !")); + } + + @GET + @Path("publish") + public void broadcast() { + Runnable r = new Runnable() { + @Override + public void run() { + int lastEventId = 0; + boolean running = true; + while (running) { + lastEventId++; + Stock stock = stockService.getNextTransaction(lastEventId); + if (stock != null) { + OutboundSseEvent sseEvent = eventBuilder + .name("stock") + .id(String.valueOf(lastEventId)) + .mediaType(MediaType.APPLICATION_JSON_TYPE) + .data(Stock.class, stock) + .reconnectDelay(3000) + .comment("price change") + .build(); + sseBroadcaster.broadcast(sseEvent); + } + try { + //Wait 5 seconds + Thread.currentThread().sleep(5 * 1000); + } catch (InterruptedException ex) { + // ... + } + //Simulatae a while boucle break + running = lastEventId <= 2000; + } + } + }; + new Thread(r).start(); + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java new file mode 100644 index 0000000000..a186b32771 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java @@ -0,0 +1,50 @@ +package com.baeldung.sse.jaxrs; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +public class Stock { + private Integer id; + private String name; + private BigDecimal price; + LocalDateTime dateTime; + + public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) { + this.id = id; + this.name = name; + this.price = price; + this.dateTime = dateTime; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public LocalDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(LocalDateTime dateTime) { + this.dateTime = dateTime; + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java new file mode 100644 index 0000000000..15818ead5d --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java @@ -0,0 +1,78 @@ +package com.baeldung.sse.jaxrs; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.Initialized; +import javax.enterprise.event.Event; +import javax.enterprise.event.Observes; +import javax.inject.Inject; +import javax.inject.Named; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicInteger; + +@ApplicationScoped +@Named +public class StockService { + + private static final BigDecimal UP = BigDecimal.valueOf(1.05f); + private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f); + + List stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO"); + List stocksDB = new ArrayList<>(); + private AtomicInteger counter = new AtomicInteger(0); + + public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { + //Open price + System.out.println("@Start Init ..."); + stockNames.forEach(stockName -> { + stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now())); + }); + + Runnable runnable = new Runnable() { + @Override + public void run() { + //Simulate Change price and put every x seconds + while (true) { + int indx = new Random().nextInt(stockNames.size()); + String stockName = stockNames.get(indx); + BigDecimal price = getLastPrice(stockName); + BigDecimal newprice = changePrice(price); + Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now()); + stocksDB.add(stock); + + int r = new Random().nextInt(30); + try { + Thread.currentThread().sleep(r*1000); + } catch (InterruptedException ex) { + // ... + } + } + } + }; + new Thread(runnable).start(); + System.out.println("@End Init ..."); + } + + public Stock getNextTransaction(Integer lastEventId) { + return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null); + } + + BigDecimal generateOpenPrice() { + float min = 70; + float max = 120; + return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING); + } + + BigDecimal changePrice(BigDecimal price) { + return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING); + } + + private BigDecimal getLastPrice(String stockName) { + return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice(); + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..9bf66d7795 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml @@ -0,0 +1,7 @@ + + + jaxrs-2.1 + cdi-2.0 + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..4f0b3cdeeb --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/resources/logback.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml similarity index 100% rename from jpa-storedprocedure/src/main/resources/logback.xml rename to apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..b4b8121fdd --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,11 @@ + + + Hello Servlet + + + index.html + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html new file mode 100644 index 0000000000..9015a7a32c --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html @@ -0,0 +1 @@ +index diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html new file mode 100644 index 0000000000..5a46e2a5d3 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html @@ -0,0 +1,38 @@ + + + + Server-Sent Event Broadcasting + + +

Stock prices :

+
+
    +
+
+ + + \ No newline at end of file diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html new file mode 100644 index 0000000000..8fddae4717 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html @@ -0,0 +1,38 @@ + + + + Server-Sent Event + + +

Stock prices :

+
+
    +
+
+ + + \ No newline at end of file diff --git a/apache-fop/src/main/resources/logback.xml b/apache-fop/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/apache-fop/src/main/resources/logback.xml +++ b/apache-fop/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/apache-geode/pom.xml b/apache-geode/pom.xml new file mode 100644 index 0000000000..a3f6604ac4 --- /dev/null +++ b/apache-geode/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + com.baeldung + apache-geode + 1.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.6.0 + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + org.apache.geode + geode-core + ${geode.core} + + + junit + junit + RELEASE + + + + \ No newline at end of file diff --git a/apache-geode/src/main/java/com/baeldung/geode/Customer.java b/apache-geode/src/main/java/com/baeldung/geode/Customer.java new file mode 100644 index 0000000000..82ee5ecaeb --- /dev/null +++ b/apache-geode/src/main/java/com/baeldung/geode/Customer.java @@ -0,0 +1,78 @@ +package com.baeldung.geode; + +import java.io.Serializable; +import java.util.Objects; + +public class Customer implements Serializable { + + private static final long serialVersionUID = -7482516011038799900L; + + private CustomerKey key; + private String firstName; + private String lastName; + private Integer age; + + public Customer() { + } + + public Customer(String firstName, String lastName, int age) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + public Customer(CustomerKey key, String firstName, String lastName, int age) { + this(firstName, lastName, age); + this.key = key; + } + + // setters and getters + + public static long getSerialVersionUID() { + return serialVersionUID; + } + + 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 Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + @Override + public String toString() { + return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Customer customer = (Customer) o; + return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName, age); + } +} diff --git a/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java b/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java new file mode 100644 index 0000000000..bfa64870c0 --- /dev/null +++ b/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java @@ -0,0 +1,57 @@ +package com.baeldung.geode; + +import java.io.Serializable; + +public class CustomerKey implements Serializable { + + private static final long serialVersionUID = -3529253035303792458L; + private long id; + private String country; + + public CustomerKey(long id) { + this.id = id; + this.country = "USA"; + } + + public CustomerKey(long id, String country) { + this.id = id; + this.country = country; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + CustomerKey that = (CustomerKey) o; + + if (id != that.id) + return false; + return country != null ? country.equals(that.country) : that.country == null; + } + + @Override + public int hashCode() { + int result = (int) (id ^ (id >>> 32)); + result = 31 * result + (country != null ? country.hashCode() : 0); + return result; + } +} diff --git a/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java b/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java new file mode 100644 index 0000000000..5ff8e53da8 --- /dev/null +++ b/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java @@ -0,0 +1,34 @@ +package com.baeldung.geode.functions; + +import com.baeldung.geode.Customer; +import com.baeldung.geode.CustomerKey; +import org.apache.geode.cache.Region; +import org.apache.geode.cache.execute.Function; +import org.apache.geode.cache.execute.FunctionContext; +import org.apache.geode.cache.execute.RegionFunctionContext; + +import java.util.Map; + +public class UpperCaseNames implements Function { + private static final long serialVersionUID = -8946294032165677602L; + + @Override + public void execute(FunctionContext context) { + RegionFunctionContext regionContext = (RegionFunctionContext) context; + Region region = regionContext.getDataSet(); + + for (Map.Entry entry : region.entrySet()) { + Customer customer = entry.getValue(); + customer.setFirstName(customer.getFirstName() + .toUpperCase()); + } + + context.getResultSender() + .lastResult(true); + } + + @Override + public String getId() { + return getClass().getName(); + } +} diff --git a/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java new file mode 100644 index 0000000000..b96d2c9b6a --- /dev/null +++ b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java @@ -0,0 +1,110 @@ +package com.baeldung.geode; + +import com.baeldung.geode.functions.UpperCaseNames; +import org.apache.geode.cache.Region; +import org.apache.geode.cache.client.ClientCache; +import org.apache.geode.cache.client.ClientCacheFactory; +import org.apache.geode.cache.client.ClientRegionShortcut; +import org.apache.geode.cache.execute.Execution; +import org.apache.geode.cache.execute.FunctionService; +import org.apache.geode.cache.query.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + +public class GeodeSamplesIntegrationTest { + + ClientCache cache = null; + Region region = null; + Region queryRegion = null; + Region customerRegion = null; + + @Before + public void connect() { + this.cache = new ClientCacheFactory().addPoolLocator("localhost", 10334) + .create(); + this.region = this.cache. createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY) + .create("baeldung"); + this.customerRegion = this.cache. createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY) + .create("baeldung-customers"); + } + + @After + public void cleanup() { + this.cache.close(); + } + + @Test + public void whenSendMessageToRegion_thenMessageSavedSuccessfully() { + + this.region.put("1", "Hello"); + this.region.put("2", "Baeldung"); + + assertEquals("Hello", region.get("1")); + assertEquals("Baeldung", region.get("2")); + + } + + @Test + public void whenPutMultipleValuesAtOnce_thenValuesSavedSuccessfully() { + + Supplier> keys = () -> Stream.of("A", "B", "C", "D", "E"); + Map values = keys.get() + .collect(Collectors.toMap(Function.identity(), String::toLowerCase)); + + this.region.putAll(values); + + keys.get() + .forEach(k -> assertEquals(k.toLowerCase(), this.region.get(k))); + + } + + @Test + public void whenPutCustomKey_thenValuesSavedSuccessfully() { + CustomerKey key = new CustomerKey(123); + Customer customer = new Customer(key, "William", "Russell", 35); + + Map customerInfo = new HashMap<>(); + customerInfo.put(key, customer); + + this.customerRegion.putAll(customerInfo); + + Customer storedCustomer = this.customerRegion.get(key); + assertEquals("William", storedCustomer.getFirstName()); + assertEquals("Russell", storedCustomer.getLastName()); + + } + + @Test + public void whenFindACustomerUsingOQL_thenCorrectCustomerObject() throws NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException { + + Map data = new HashMap<>(); + data.put(new CustomerKey(1), new Customer("Gheorge", "Manuc", 36)); + data.put(new CustomerKey(2), new Customer("Allan", "McDowell", 43)); + this.customerRegion.putAll(data); + + QueryService queryService = this.cache.getQueryService(); + String query = "select * from /baeldung-customers c where c.firstName = 'Allan'"; + SelectResults queryResults = (SelectResults) queryService.newQuery(query) + .execute(); + assertEquals(1, queryResults.size()); + + } + + @Test + public void whenExecuteUppercaseNames_thenCustomerNamesAreUppercased() { + Execution execution = FunctionService.onRegion(this.customerRegion); + execution.execute(UpperCaseNames.class.getName()); + Customer customer = this.customerRegion.get(new CustomerKey(1)); + assertEquals("GHEORGE", customer.getFirstName()); + } +} diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml index 3a72804ab1..98d9563284 100644 --- a/apache-shiro/pom.xml +++ b/apache-shiro/pom.xml @@ -3,7 +3,6 @@ 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 - com.baeldung apache-shiro 1.0-SNAPSHOT @@ -36,13 +35,11 @@ org.slf4j jcl-over-slf4j - ${slf4j-version} runtime org.slf4j slf4j-log4j12 - ${slf4j-version} runtime @@ -53,26 +50,9 @@ - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - - - 1.4.0 - 3.7.0 - 1.8 1.2.17 - 1.7.25
\ No newline at end of file diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml index 6947cc71bc..b22364cb19 100644 --- a/apache-thrift/pom.xml +++ b/apache-thrift/pom.xml @@ -39,6 +39,7 @@ org.codehaus.mojo build-helper-maven-plugin + ${build-helper-maven-plugin.version} generate-sources @@ -60,6 +61,7 @@ 0.10.0 0.1.11 1.7.12 + 3.0.0
diff --git a/apache-velocity/src/main/resources/logback.xml b/apache-velocity/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/apache-velocity/src/main/resources/logback.xml +++ b/apache-velocity/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/asciidoctor/README.md b/asciidoctor/README.md index aafd0bca17..2124907e87 100644 --- a/asciidoctor/README.md +++ b/asciidoctor/README.md @@ -1,5 +1,4 @@ ### Relevant articles -- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor) - [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book) - [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor) diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml index 15de5ac913..42ee544eb0 100644 --- a/asciidoctor/pom.xml +++ b/asciidoctor/pom.xml @@ -61,9 +61,10 @@ - 1.5.5 - 1.5.4 - 1.5.0-alpha.11 + 1.5.6 + 1.5.6 + + 1.5.0-alpha.15 1.5.0-alpha.15 diff --git a/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java b/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java similarity index 89% rename from asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java rename to asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java index 3e312eb059..c4129e6441 100644 --- a/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java +++ b/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.asciidoctor; import org.junit.Assert; import org.junit.Test; -public class AsciidoctorDemoTest { +public class AsciidoctorDemoIntegrationTest { @Test public void givenString_whenConverting_thenResultingHTMLCode() { diff --git a/asm/pom.xml b/asm/pom.xml index 7bbaa2a8f1..5aad2a0e37 100644 --- a/asm/pom.xml +++ b/asm/pom.xml @@ -42,14 +42,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - -javaagent:"C:\asm-1.0.jar" - - diff --git a/aws-lambda/pom.xml b/aws-lambda/pom.xml index 3a2be70da6..c47c3cd86f 100644 --- a/aws-lambda/pom.xml +++ b/aws-lambda/pom.xml @@ -95,7 +95,6 @@ 2.8.2 1.11.241 3.0.0 - 2.10 \ No newline at end of file diff --git a/aws/.gitignore b/aws/.gitignore index b83d22266a..bf11a4cc38 100644 --- a/aws/.gitignore +++ b/aws/.gitignore @@ -1 +1,2 @@ /target/ +.idea/ \ No newline at end of file diff --git a/aws/README.md b/aws/README.md index d23937a419..2c61928095 100644 --- a/aws/README.md +++ b/aws/README.md @@ -9,4 +9,4 @@ - [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests) - [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3) - [Managing Amazon SQS Queues in Java](http://www.baeldung.com/aws-queues-java) - +- [Guide to AWS Aurora RDS with Java](https://www.baeldung.com/aws-aurora-rds-java) diff --git a/aws/pom.xml b/aws/pom.xml index 176ecaa40d..ab63f6afa1 100644 --- a/aws/pom.xml +++ b/aws/pom.xml @@ -100,26 +100,6 @@ - - - org.apache.maven.plugins - maven-dependency-plugin - ${maven-dependency-plugin.version} - - - copy-dependencies - test-compile - - copy-dependencies - - - test - so,dll,dylib - ${project.basedir}/native-libs - - - - @@ -137,14 +117,13 @@ 1.1.0 2.8.0 1.11.290 - 2.8.9 + 2.21.0 3.8.0 1.11.86 https://s3-us-west-2.amazonaws.com/dynamodb-local/release 1.10.L001 0.9.4.0006L 3.0.0 - 2.10 \ No newline at end of file diff --git a/aws/src/main/java/com/baeldung/rds/AWSRDSService.java b/aws/src/main/java/com/baeldung/rds/AWSRDSService.java new file mode 100644 index 0000000000..d4da92f30f --- /dev/null +++ b/aws/src/main/java/com/baeldung/rds/AWSRDSService.java @@ -0,0 +1,184 @@ +package com.baeldung.rds; + +import com.amazonaws.auth.AWSCredentialsProvider; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.rds.AmazonRDS; +import com.amazonaws.services.rds.AmazonRDSClientBuilder; +import com.amazonaws.services.rds.model.*; + +import java.io.IOException; +import java.io.InputStream; +import java.sql.*; +import java.util.List; +import java.util.Properties; +import java.util.UUID; +import java.util.logging.Logger; + +public class AWSRDSService { + + + final static Logger logger = Logger.getLogger(AWSRDSService.class.getName()); + private AWSCredentialsProvider credentials; + private AmazonRDS amazonRDS; + private String db_username; + private String db_password; + private String db_database; + private String db_hostname; + + /* + * User access key and secret key must be set before execute any operation. + * Follow the link on how to get the user access and secret key + * https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/ + * **/ + public AWSRDSService() throws IOException { + //Init RDS client with credentials and region. + credentials = new + AWSStaticCredentialsProvider(new + BasicAWSCredentials("", + "")); + amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials) + .withRegion(Regions.AP_SOUTHEAST_2).build(); + Properties prop = new Properties(); + InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties"); + prop.load(input); + db_username = prop.getProperty("db_username"); + db_password = prop.getProperty("db_password"); + db_database = prop.getProperty("db_database"); + } + + public AWSRDSService(AmazonRDS amazonRDS){ + this.amazonRDS = amazonRDS; + } + + /** + * create the RDS instance. + * After instance creation, update the db_hostname with endpoint in db.properties. + * */ + + public String launchInstance() { + + String identifier = ""; + CreateDBInstanceRequest request = new CreateDBInstanceRequest(); + // RDS instance name + request.setDBInstanceIdentifier("Sydney"); + request.setEngine("postgres"); + request.setMultiAZ(false); + request.setMasterUsername(db_username); + request.setMasterUserPassword(db_password); + request.setDBName(db_database); + request.setStorageType("gp2"); + request.setAllocatedStorage(10); + + DBInstance instance = amazonRDS.createDBInstance(request); + + // Information about the new RDS instance + identifier = instance.getDBInstanceIdentifier(); + String status = instance.getDBInstanceStatus(); + Endpoint endpoint = instance.getEndpoint(); + String endpoint_url = "Endpoint URL not available yet."; + if (endpoint != null) { + endpoint_url = endpoint.toString(); + } + logger.info(identifier + "\t" + status); + logger.info(endpoint_url); + + return identifier; + + } + + // Describe DB instances + public void listInstances() { + DescribeDBInstancesResult result = amazonRDS.describeDBInstances(); + List instances = result.getDBInstances(); + for (DBInstance instance : instances) { + // Information about each RDS instance + String identifier = instance.getDBInstanceIdentifier(); + String engine = instance.getEngine(); + String status = instance.getDBInstanceStatus(); + Endpoint endpoint = instance.getEndpoint(); + String endpoint_url = "Endpoint URL not available yet."; + if (endpoint != null) { + endpoint_url = endpoint.toString(); + } + logger.info(identifier + "\t" + engine + "\t" + status); + logger.info("\t" + endpoint_url); + } + + } + + //Delete RDS instance + public void terminateInstance(String identifier) { + + DeleteDBInstanceRequest request = new DeleteDBInstanceRequest(); + request.setDBInstanceIdentifier(identifier); + request.setSkipFinalSnapshot(true); + + // Delete the RDS instance + DBInstance instance = amazonRDS.deleteDBInstance(request); + + // Information about the RDS instance being deleted + String status = instance.getDBInstanceStatus(); + Endpoint endpoint = instance.getEndpoint(); + String endpoint_url = "Endpoint URL not available yet."; + if (endpoint != null) { + endpoint_url = endpoint.toString(); + } + + logger.info(identifier + "\t" + status); + logger.info(endpoint_url); + + } + + + public void runJdbcTests() throws SQLException, IOException { + + // Getting database properties from db.properties + Properties prop = new Properties(); + InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties"); + prop.load(input); + db_hostname = prop.getProperty("db_hostname"); + String jdbc_url = "jdbc:postgresql://" + db_hostname + ":5432/" + db_database; + + // Create a connection using the JDBC driver + try (Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password)) { + + // Create the test table if not exists + Statement statement = conn.createStatement(); + String sql = "CREATE TABLE IF NOT EXISTS jdbc_test (id SERIAL PRIMARY KEY, content VARCHAR(80))"; + statement.executeUpdate(sql); + + // Do some INSERT + PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO jdbc_test (content) VALUES (?)"); + String content = "" + UUID.randomUUID(); + preparedStatement.setString(1, content); + preparedStatement.executeUpdate(); + logger.info("INSERT: " + content); + + // Do some SELECT + sql = "SELECT * FROM jdbc_test"; + ResultSet resultSet = statement.executeQuery(sql); + while (resultSet.next()) { + String count = resultSet.getString("content"); + logger.info("Total Records: " + count); + } + } + + + } + + public static void main(String[] args) throws IOException, SQLException { + AWSRDSService awsrdsService = new AWSRDSService(); + + String instanceName = awsrdsService.launchInstance(); + + //Add some wait for instance creation. + + awsrdsService.listInstances(); + + awsrdsService.runJdbcTests(); + + awsrdsService.terminateInstance(instanceName); + } +} diff --git a/aws/src/main/resources/db.properties b/aws/src/main/resources/db.properties new file mode 100644 index 0000000000..e934611a2b --- /dev/null +++ b/aws/src/main/resources/db.properties @@ -0,0 +1,4 @@ +db_hostname= +db_username=username +db_password=password +db_database=mydb \ No newline at end of file diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 22d1522fbe..2291da9084 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -2,12 +2,10 @@ 4.0.0 - com.baeldung cas-secured-app - 0.0.1-SNAPSHOT jar cas-secured-app - Demo project for Spring Boot + Demo project for CAS parent-boot-1 @@ -60,10 +58,4 @@ - - UTF-8 - UTF-8 - 1.8 - - diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml index a15b4b58d5..9b61aaec3d 100644 --- a/cas/cas-server/pom.xml +++ b/cas/cas-server/pom.xml @@ -2,11 +2,17 @@ 4.0.0 - com.baeldung cas-server war 1.0 + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 + + org.apereo.cas @@ -39,7 +45,6 @@ org.springframework.boot spring-boot-maven-plugin - ${springboot.version} ${mainClassName} true @@ -74,42 +79,10 @@ - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - cas - - - sonatype-releases - http://oss.sonatype.org/content/repositories/releases/ - - false - - - true - - - - sonatype-snapshots - https://oss.sonatype.org/content/repositories/snapshots/ - - true - - - false - - - - shibboleth-releases - https://build.shibboleth.net/nexus/content/repositories/releases - - - @@ -214,8 +187,7 @@ - 5.3.0-SNAPSHOT - 1.5.13.RELEASE + 5.3.3 -tomcat @@ -223,14 +195,12 @@ false ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF - 1.8 - 1.8 - UTF-8 0.0.4 2.6 3.3 + 0.3.0 1.1.0 - \ No newline at end of file + diff --git a/cdi-portable-extension/flyway-cdi/pom.xml b/cdi-portable-extension/flyway-cdi/pom.xml new file mode 100644 index 0000000000..9fb781aaab --- /dev/null +++ b/cdi-portable-extension/flyway-cdi/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + + flyway-cdi + + + com.baeldung + cdi-portable-extension + 1.0-SNAPSHOT + + + + + javax.enterprise + cdi-api + 2.0.SP1 + + + org.flywaydb + flyway-core + 5.1.4 + + + org.apache.tomcat + tomcat-jdbc + 8.5.33 + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + diff --git a/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java new file mode 100644 index 0000000000..a5019b82c1 --- /dev/null +++ b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java @@ -0,0 +1,74 @@ +package com.baeldung.cdi.extension; + +import org.apache.tomcat.jdbc.pool.DataSource; +import org.flywaydb.core.Flyway; + +import javax.annotation.sql.DataSourceDefinition; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.Any; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.literal.InjectLiteral; +import javax.enterprise.inject.spi.*; +import javax.enterprise.util.AnnotationLiteral; + + +/** + * Flyway is now under CDI container like: + * + * @ApplicationScoped + * @FlywayType public class Flyway{ + * @Inject setDataSource(DataSource dataSource){ + * //... + * } + * } + */ + +public class FlywayExtension implements Extension { + + DataSourceDefinition dataSourceDefinition = null; + + public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) { + bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName()); + } + + public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType patEvent) { + AnnotatedType at = patEvent.getAnnotatedType(); + dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class); + } + + public void processAnnotatedType(@Observes ProcessAnnotatedType patEvent) { + patEvent.configureAnnotatedType() + //Add Scope + .add(ApplicationScoped.Literal.INSTANCE) + //Add Qualifier + .add(new AnnotationLiteral() { + }) + //Decorate setDataSource(DataSource dataSource){} with @Inject + .filterMethods(annotatedMethod -> { + return annotatedMethod.getParameters().size() == 1 && + annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class); + }) + .findFirst().get().add(InjectLiteral.INSTANCE); + } + + void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) { + abdEvent.addBean() + .types(javax.sql.DataSource.class, DataSource.class) + .qualifiers(new AnnotationLiteral() {}, new AnnotationLiteral() {}) + .scope(ApplicationScoped.class) + .name(DataSource.class.getName()) + .beanClass(DataSource.class) + .createWith(creationalContext -> { + DataSource instance = new DataSource(); + instance.setUrl(dataSourceDefinition.url()); + instance.setDriverClassName(dataSourceDefinition.className()); + return instance; + }); + } + + void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) { + Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral() {}).get(); + flyway.migrate(); + } +} diff --git a/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayType.java b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayType.java new file mode 100644 index 0000000000..7c3a5affa6 --- /dev/null +++ b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayType.java @@ -0,0 +1,14 @@ +package com.baeldung.cdi.extension; + +import javax.inject.Qualifier; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target({FIELD, METHOD, PARAMETER, TYPE}) +@Qualifier +public @interface FlywayType { +} \ No newline at end of file diff --git a/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/beans.xml b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..44959bfa99 --- /dev/null +++ b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension new file mode 100644 index 0000000000..a82dc47714 --- /dev/null +++ b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension @@ -0,0 +1,2 @@ +com.baeldung.cdi.extension.FlywayExtension + diff --git a/cdi-portable-extension/main-app/pom.xml b/cdi-portable-extension/main-app/pom.xml new file mode 100644 index 0000000000..fab9b8bf07 --- /dev/null +++ b/cdi-portable-extension/main-app/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + main-app + jar + + + com.baeldung + cdi-portable-extension + 1.0-SNAPSHOT + + + + + + javax.enterprise + cdi-api + 2.0.SP1 + + + org.jboss.weld.se + weld-se-core + 3.0.5.Final + runtime + + + + com.baeldung + flyway-cdi + 1.0-SNAPSHOT + runtime + + + + com.h2database + h2 + 1.4.197 + runtime + + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + + \ No newline at end of file diff --git a/cdi-portable-extension/main-app/src/main/java/com/baeldung/cdi/extension/MainApp.java b/cdi-portable-extension/main-app/src/main/java/com/baeldung/cdi/extension/MainApp.java new file mode 100644 index 0000000000..1f6c5b43ba --- /dev/null +++ b/cdi-portable-extension/main-app/src/main/java/com/baeldung/cdi/extension/MainApp.java @@ -0,0 +1,16 @@ +package com.baeldung.cdi.extension; + +import javax.annotation.sql.DataSourceDefinition; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.se.SeContainer; +import javax.enterprise.inject.se.SeContainerInitializer; + +@ApplicationScoped +@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb") +public class MainApp { + public static void main(String[] args) { + SeContainerInitializer initializer = SeContainerInitializer.newInstance(); + try (SeContainer container = initializer.initialize()) { + } + } +} \ No newline at end of file diff --git a/cdi-portable-extension/main-app/src/main/resources/META-INF/beans.xml b/cdi-portable-extension/main-app/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..44959bfa99 --- /dev/null +++ b/cdi-portable-extension/main-app/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/cdi-portable-extension/main-app/src/main/resources/db/migration/V1__Create_person_table.sql b/cdi-portable-extension/main-app/src/main/resources/db/migration/V1__Create_person_table.sql new file mode 100644 index 0000000000..6bddc7689e --- /dev/null +++ b/cdi-portable-extension/main-app/src/main/resources/db/migration/V1__Create_person_table.sql @@ -0,0 +1,4 @@ +create table PERSON ( + ID int not null, + NAME varchar(100) not null +); diff --git a/cdi-portable-extension/main-app/src/main/resources/db/migration/V2__Add_people.sql b/cdi-portable-extension/main-app/src/main/resources/db/migration/V2__Add_people.sql new file mode 100644 index 0000000000..d8f1d62667 --- /dev/null +++ b/cdi-portable-extension/main-app/src/main/resources/db/migration/V2__Add_people.sql @@ -0,0 +1,3 @@ +insert into PERSON (ID, NAME) values (1, 'Axel'); +insert into PERSON (ID, NAME) values (2, 'Mr. Foo'); +insert into PERSON (ID, NAME) values (3, 'Ms. Bar'); diff --git a/cdi-portable-extension/pom.xml b/cdi-portable-extension/pom.xml new file mode 100644 index 0000000000..66913de84d --- /dev/null +++ b/cdi-portable-extension/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + com.baeldung + cdi-portable-extension + 1.0-SNAPSHOT + pom + + + 1.8 + 1.8 + + + + main-app + flyway-cdi + + + + + javax.enterprise + cdi-api + 2.0.SP1 + + + + \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java index 8b5fa409c9..930e913109 100644 --- a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java @@ -1,70 +1,91 @@ package com.baeldung.test.dependencyinjection; -import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor; -import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor; -import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor; -import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor; -import com.baeldung.dependencyinjection.loggers.TimeLogger; -import java.text.SimpleDateFormat; -import java.util.Calendar; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; + +import java.text.ParseException; +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; + import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.junit.BeforeClass; import org.junit.Test; +import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor; +import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor; +import com.baeldung.dependencyinjection.loggers.TimeLogger; + public class ImageProcessorUnitTest { - + private static ImageFileProcessor imageFileProcessor; - private static SimpleDateFormat dateFormat; - private static Calendar calendar; - - + @BeforeClass public static void setImageProcessorInstance() { Weld weld = new Weld(); WeldContainer container = weld.initialize(); - imageFileProcessor = container.select(ImageFileProcessor.class).get(); + imageFileProcessor = container.select(ImageFileProcessor.class) + .get(); container.shutdown(); } - - @BeforeClass - public static void setSimpleDateFormatInstance() { - dateFormat = new SimpleDateFormat("HH:mm"); - } - - @BeforeClass - public static void setCalendarInstance() { - calendar = Calendar.getInstance(); - } - + @Test public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() { assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class); assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class); } - + @Test - public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String openFileLog = imageFileProcessor.openFile("file1.png"); + assertThat(openFileLog).contains("Opening PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(openFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); } - + @Test - public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String editFileLog = imageFileProcessor.editFile("file1.png"); + assertThat(editFileLog).contains("Editing PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(editFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); } - + @Test - public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String writeFileLog = imageFileProcessor.writeFile("file1.png"); + assertThat(writeFileLog).contains("Writing PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(writeFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); } - + @Test - public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String saveFileLog = imageFileProcessor.saveFile("file1.png"); + assertThat(saveFileLog).contains("Saving PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(saveFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); + } + + private LocalTime getLoggedTime(String log) throws ParseException { + String logTimeString = log.split("at: ")[1]; + + int hour = Integer.valueOf(logTimeString.split(":")[0]); + int minutes = Integer.valueOf(logTimeString.split(":")[1]); + + LocalTime loggedTime = LocalTime.of(hour, minutes); + return loggedTime; } } \ No newline at end of file diff --git a/checker-plugin/pom.xml b/checker-plugin/pom.xml index 7538340f69..45f0939e77 100644 --- a/checker-plugin/pom.xml +++ b/checker-plugin/pom.xml @@ -41,27 +41,6 @@ - - - org.apache.maven.plugins - maven-dependency-plugin - - - - - properties - - - - - maven-compiler-plugin ${maven-compiler-plugin.version} diff --git a/core-java-8/README.md b/core-java-8/README.md index 6f31a8b886..64d423aafe 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -9,54 +9,26 @@ - [Java 8 New Features](http://www.baeldung.com/java-8-new-features) - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) -- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) - [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector) - [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern) -- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams) -- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) - [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions) -- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany) - [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing) -- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element) -- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) -- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) - [Guide To Java 8 Optional](http://www.baeldung.com/java-optional) - [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java) -- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8) -- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster) -- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) - [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode) - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) -- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) -- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception) -- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) -- [Copy a File with Java](http://www.baeldung.com/java-copy-file) - [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods) -- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream) -- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream) -- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices) - [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency) -- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) -- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) -- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection) -- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner) - [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator) - [Java 8 Math New Methods](http://www.baeldung.com/java-8-math) - [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations) - [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) -- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) -- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) - [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) -- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) - [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) - [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) -- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) - [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference) -- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) -- [Calculate Age in Java](http://www.baeldung.com/java-get-age) -- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) -- [Increment Date in Java](http://www.baeldung.com/java-increment-date) -- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date) - [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time) +- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone) +- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance) +- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects) diff --git a/core-java-8/findItemsBasedOnValues/.gitignore b/core-java-8/findItemsBasedOnValues/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/core-java-8/findItemsBasedOnValues/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java new file mode 100644 index 0000000000..a0dcdddd85 --- /dev/null +++ b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java @@ -0,0 +1,93 @@ +package findItems; + +import static org.junit.Assert.assertEquals; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class FindItemsBasedOnValues { + + List EmplList = new ArrayList(); + List deptList = new ArrayList(); + + public static void main(String[] args) throws ParseException { + FindItemsBasedOnValues findItems = new FindItemsBasedOnValues(); + findItems.givenDepartmentList_thenEmployeeListIsFilteredCorrectly(); + } + + @Test + public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() { + Integer expectedId = 1002; + + populate(EmplList, deptList); + + List filteredList = EmplList.stream() + .filter(empl -> deptList.stream() + .anyMatch(dept -> dept.getDepartment() + .equals("sales") && empl.getEmployeeId() + .equals(dept.getEmployeeId()))) + .collect(Collectors.toList()); + + assertEquals(expectedId, filteredList.get(0) + .getEmployeeId()); + } + + private void populate(List EmplList, List deptList) { + Employee employee1 = new Employee(1001, "empl1"); + Employee employee2 = new Employee(1002, "empl2"); + Employee employee3 = new Employee(1003, "empl3"); + + Collections.addAll(EmplList, employee1, employee2, employee3); + + Department department1 = new Department(1002, "sales"); + Department department2 = new Department(1003, "marketing"); + Department department3 = new Department(1004, "sales"); + + Collections.addAll(deptList, department1, department2, department3); + } +} + +class Employee { + Integer employeeId; + String employeeName; + + public Employee(Integer employeeId, String employeeName) { + super(); + this.employeeId = employeeId; + this.employeeName = employeeName; + } + + public Integer getEmployeeId() { + return employeeId; + } + + public String getEmployeeName() { + return employeeName; + } + +} + +class Department { + Integer employeeId; + String department; + + public Department(Integer employeeId, String department) { + super(); + this.employeeId = employeeId; + this.department = department; + } + + public Integer getEmployeeId() { + return employeeId; + } + + public String getDepartment() { + return department; + } + +} \ No newline at end of file diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 7e3b8cb280..18bdaa15f4 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -89,11 +89,6 @@ vavr ${vavr.version} - - one.util - streamex - ${streamex.version} - joda-time joda-time @@ -121,23 +116,6 @@ - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - - org.apache.maven.plugins maven-compiler-plugin @@ -151,6 +129,7 @@ org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} @@ -176,7 +155,6 @@ 1.16.12 0.9.0 1.13 - 0.6.5 2.10 3.6.1 @@ -184,6 +162,6 @@ 1.7.0 1.19 1.19 + 2.0.4.RELEASE - - \ No newline at end of file + diff --git a/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java b/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java new file mode 100644 index 0000000000..46018faf80 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.optional; + +public class PersonRepository { + + public String findNameById(String id) { + return id == null ? null : "Name"; + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java b/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java new file mode 100644 index 0000000000..2513ec0d03 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java @@ -0,0 +1,23 @@ +package com.baeldung.primitive; + +public class BenchmarkRunner { + + public static void main(String[] args) throws Exception { + new IntPrimitiveLookup().run(); + new IntegerWrapperLookup().run(); + new FloatPrimitiveLookup().run(); + new FloatWrapperLookup().run(); + new DoublePrimitiveLookup().run(); + new DoubleWrapperLookup().run(); + new ShortPrimitiveLookup().run(); + new ShortWrapperLookup().run(); + new BooleanPrimitiveLookup().run(); + new BooleanWrapperLookup().run(); + new CharPrimitiveLookup().run(); + new CharacterWrapperLookup().run(); + new BytePrimitiveLookup().run(); + new ByteWrapperLookup().run(); + new LongPrimitiveLookup().run(); + new LongWrapperLookup().run(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java new file mode 100644 index 0000000000..2ad698eba4 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class BooleanPrimitiveLookup extends Lookup { + + private boolean[] elements; + private final boolean pivot = false; + + @Setup + @Override + public void prepare() { + elements = new boolean[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = true; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return BooleanPrimitiveLookup.class.getSimpleName(); + } + + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java new file mode 100644 index 0000000000..8d996739a8 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class BooleanWrapperLookup extends Lookup { + private Boolean[] elements; + private final boolean pivot = false; + + @Override + @Setup + public void prepare() { + elements = new Boolean[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = true; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Boolean pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return BooleanWrapperLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java new file mode 100644 index 0000000000..73eda5cf5b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java @@ -0,0 +1,46 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class BytePrimitiveLookup extends Lookup { + + private byte[] elements; + private final byte pivot = 2; + + @Setup + @Override + public void prepare() { + byte common = 1; + elements = new byte[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return BytePrimitiveLookup.class.getSimpleName(); + } + + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java new file mode 100644 index 0000000000..23e02315a6 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java @@ -0,0 +1,46 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class ByteWrapperLookup extends Lookup { + private Byte[] elements; + private final byte pivot = 2; + + @Override + @Setup + public void prepare() { + byte common = 1; + elements = new Byte[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Byte pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return ByteWrapperLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java new file mode 100644 index 0000000000..a6d4be6206 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java @@ -0,0 +1,46 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class CharPrimitiveLookup extends Lookup { + + private char[] elements; + private final char pivot = 'b'; + + @Setup + @Override + public void prepare() { + char common = 'a'; + elements = new char[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return CharPrimitiveLookup.class.getSimpleName(); + } + + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java new file mode 100644 index 0000000000..9509b4a156 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java @@ -0,0 +1,46 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class CharacterWrapperLookup extends Lookup { + private Character[] elements; + private final char pivot = 'b'; + + @Override + @Setup + public void prepare() { + char common = 'a'; + elements = new Character[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Character pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return CharacterWrapperLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java new file mode 100644 index 0000000000..f95515a02d --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java @@ -0,0 +1,42 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class DoublePrimitiveLookup extends Lookup { + private double[] elements; + private final double pivot = 2; + + @Setup + @Override + public void prepare() { + double common = 1; + elements = new double[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return DoublePrimitiveLookup.class.getSimpleName(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java new file mode 100644 index 0000000000..671c2ccc29 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class DoubleWrapperLookup extends Lookup { + private Double[] elements; + private final double pivot = 2d; + + @Override + @Setup + public void prepare() { + double common = 1; + elements = new Double[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Double pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return DoubleWrapperLookup.class.getSimpleName(); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java new file mode 100644 index 0000000000..26b58f0053 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java @@ -0,0 +1,42 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class FloatPrimitiveLookup extends Lookup { + private float[] elements; + private final float pivot = 2; + + @Setup + @Override + public void prepare() { + int common = 1; + elements = new float[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return FloatPrimitiveLookup.class.getSimpleName(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java new file mode 100644 index 0000000000..8e75eae3e3 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java @@ -0,0 +1,43 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class FloatWrapperLookup extends Lookup { + private Float[] elements; + private final float pivot = 2; + + @Override + @Setup + public void prepare() { + float common = 1; + elements = new Float[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Float pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return FloatWrapperLookup.class.getSimpleName(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java new file mode 100644 index 0000000000..551163dba2 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class IntPrimitiveLookup extends Lookup { + + private int[] elements; + private final int pivot = 2; + + @Setup + @Override + public void prepare() { + int common = 1; + elements = new int[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return IntPrimitiveLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java new file mode 100644 index 0000000000..f39fb80a0b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class IntegerWrapperLookup extends Lookup { + private Integer[] elements; + private final int pivot = 2; + + @Override + @Setup + public void prepare() { + int common = 1; + elements = new Integer[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Integer pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return IntegerWrapperLookup.class.getSimpleName(); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java new file mode 100644 index 0000000000..2f414577da --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java @@ -0,0 +1,42 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class LongPrimitiveLookup extends Lookup { + private long[] elements; + private final long pivot = 2; + + @Setup + @Override + public void prepare() { + long common = 1; + elements = new long[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return LongPrimitiveLookup.class.getSimpleName(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java new file mode 100644 index 0000000000..692a9fd15c --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class LongWrapperLookup extends Lookup{ + private Long[] elements; + private final long pivot = 2; + + @Override + @Setup + public void prepare() { + long common = 1; + elements = new Long[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Long pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return LongWrapperLookup.class.getSimpleName(); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java b/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java new file mode 100644 index 0000000000..3dc7b7655e --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java @@ -0,0 +1,56 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.results.RunResult; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.Collection; + +/** + * An abstract class that is to be extended by the classes that + * perform lookup in the arrays either of Java primitive types or their wrappers. + */ +public abstract class Lookup { + /** + * the array size + */ + final protected int s = 50000000; + + /** + * Initialize the array: fill in the array with the same + * elements except for the last one. + */ + abstract public void prepare(); + + /** + * Free the array's reference. + */ + abstract public void clean(); + + /** + * Find the position of the element that is different from the others. + * By construction, it is the last array element. + * + * @return array's last element index + */ + abstract public int findPosition(); + + /** + * Get the name of the class that extends this one. It is needed in order + * to set up the benchmark. + * + * @return + */ + abstract public String getSimpleClassName(); + + Collection run() throws RunnerException { + Options opt = new OptionsBuilder() + .include(getSimpleClassName()) + .forks(1) + .build(); + return new Runner(opt).run(); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java new file mode 100644 index 0000000000..2d2ffbd67b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java @@ -0,0 +1,45 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class ShortPrimitiveLookup extends Lookup { + + private short[] elements; + private final short pivot = 2; + + @Setup + @Override + public void prepare() { + short common = 1; + elements = new short[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @TearDown + @Override + public void clean() { + elements = null; + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + while (pivot != elements[index]) { + index++; + } + return index; + } + + @Override + public String getSimpleClassName() { + return ShortPrimitiveLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java new file mode 100644 index 0000000000..1c1cd4a345 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java @@ -0,0 +1,46 @@ +package com.baeldung.primitive; + +import org.openjdk.jmh.annotations.*; + +@State(Scope.Thread) +public class ShortWrapperLookup extends Lookup { + private Short[] elements; + private final short pivot = 2; + + @Override + @Setup + public void prepare() { + short common = 1; + elements = new Short[s]; + for (int i = 0; i < s - 1; i++) { + elements[i] = common; + } + elements[s - 1] = pivot; + } + + @Override + @TearDown + public void clean() { + elements = null; + } + + @Override + @Benchmark + @BenchmarkMode(Mode.AverageTime) + public int findPosition() { + int index = 0; + Short pivotWrapper = pivot; + while (!pivotWrapper.equals(elements[index])) { + index++; + } + return index; + + } + + @Override + public String getSimpleClassName() { + return ShortWrapperLookup.class.getSimpleName(); + } + + +} diff --git a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java b/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java deleted file mode 100644 index 4d95bc82e1..0000000000 --- a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.internationalization; - -import org.junit.Assert; -import org.junit.Test; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.Locale; -import java.util.TimeZone; - -public class DateTimeFormatterUnitTest { - - @Test - public void givenDefaultUsLocaleAndDateTimeAndPattern_whenFormatWithDifferentLocales_thenGettingLocalizedDateTimes() { - Locale.setDefault(Locale.US); - LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500); - String pattern = "dd-MMMM-yyyy HH:mm:ss.SSS"; - - DateTimeFormatter defaultTimeFormatter = DateTimeFormatter.ofPattern(pattern); - DateTimeFormatter plTimeFormatter = DateTimeFormatter.ofPattern(pattern, new Locale("pl", "PL")); - DateTimeFormatter deTimeFormatter = DateTimeFormatter.ofPattern(pattern).withLocale(Locale.GERMANY); - - Assert.assertEquals("01-January-2018 10:15:50.000", defaultTimeFormatter.format(localDateTime)); - Assert.assertEquals("01-stycznia-2018 10:15:50.000", plTimeFormatter.format(localDateTime)); - Assert.assertEquals("01-Januar-2018 10:15:50.000", deTimeFormatter.format(localDateTime)); - } - - @Test - public void givenDateTimeAndTimeZone_whenFormatWithDifferentLocales_thenGettingLocalizedZonedDateTimes() { - Locale.setDefault(Locale.US); - LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500); - ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId(); - - DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL); - DateTimeFormatter frLocalizedFormatter = - DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE); - String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone)); - String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone)); - - Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime); - Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index f371c0d7da..71ec5b147f 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -1,16 +1,18 @@ package com.baeldung.java8; -import com.baeldung.java8.entity.Human; -import com.google.common.collect.Lists; -import com.google.common.primitives.Ints; -import org.junit.Assert; -import org.junit.Test; +import static org.hamcrest.Matchers.equalTo; import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.stream.Collectors; -import static org.hamcrest.Matchers.equalTo; +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.java8.entity.Human; +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; public class Java8SortUnitTest { @@ -111,5 +113,22 @@ public class Java8SortUnitTest { humans.sort(Comparator.comparing(Human::getName)); Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12))); } + + @Test + public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { + final List letters = Lists.newArrayList("B", "A", "C"); + + final List sortedLetters = letters.stream().sorted().collect(Collectors.toList()); + Assert.assertThat(sortedLetters.get(0), equalTo("A")); + } + @Test + public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { + + final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); + final Comparator nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName()); + + final List sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList()); + Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12))); + } } diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java index 4df3482633..df6c72d346 100644 --- a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java @@ -5,25 +5,22 @@ */ package com.baeldung.nullsafecollectionstreams; +import static org.junit.Assert.assertEquals; + import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.stream.Stream; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; + import org.junit.Test; -import static org.junit.Assert.*; /** * * @author Kwaje Anthony */ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { - - private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = - new NullSafeCollectionStreamsUsingJava8OptionalContainer(); + + private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer(); @Test public void whenCollectionIsNull_thenExpectAnEmptyStream() { @@ -49,5 +46,5 @@ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { assertEquals(iter1.next(), iter2.next()); assert !iter1.hasNext() && !iter2.hasNext(); } - + } diff --git a/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java b/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java new file mode 100644 index 0000000000..4efa625ccd --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.optional; + +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class PersonRepositoryUnitTest { + + PersonRepository personRepository = new PersonRepository(); + + @Test + public void whenIdIsNull_thenExceptionIsThrown() { + assertThrows(IllegalArgumentException.class, + () -> + Optional + .ofNullable(personRepository.findNameById(null)) + .orElseThrow(IllegalArgumentException::new)); + } + + @Test + public void whenIdIsNonNull_thenNoExceptionIsThrown() { + assertAll( + () -> + Optional + .ofNullable(personRepository.findNameById("id")) + .orElseThrow(RuntimeException::new)); + } + + @Test + public void whenIdNonNull_thenReturnsNameUpperCase() { + String name = Optional + .ofNullable(personRepository.findNameById("id")) + .map(String::toUpperCase) + .orElseThrow(RuntimeException::new); + + assertEquals("NAME", name); + } + +} \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java b/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java new file mode 100644 index 0000000000..b5d26eb6a8 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.stream.conditional; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + +import org.junit.Assert; +import org.junit.Test; + +public class StreamForEachIfElseUnitTest { + + @Test + public final void givenIntegerStream_whenCheckingIntegerParityWithIfElse_thenEnsureCorrectParity() { + List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + + ints.stream() + .forEach(i -> { + if (i.intValue() % 2 == 0) { + Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0); + } else { + Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0); + } + }); + + } + + @Test + public final void givenIntegerStream_whenCheckingIntegerParityWithStreamFilter_thenEnsureCorrectParity() { + List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + + Stream evenIntegers = ints.stream() + .filter(i -> i.intValue() % 2 == 0); + Stream oddIntegers = ints.stream() + .filter(i -> i.intValue() % 2 != 0); + + evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0)); + oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0)); + + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java index 1689a5054d..ec20b7794b 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java @@ -1,7 +1,6 @@ package com.baeldung.util; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import java.time.Clock; import java.time.Instant; @@ -10,8 +9,6 @@ import java.time.LocalTime; import java.time.ZoneId; import java.time.temporal.ChronoField; -import org.joda.time.DateTime; -import org.joda.time.DateTimeUtils; import org.junit.Test; public class CurrentDateTimeUnitTest { diff --git a/core-java-9/README.md b/core-java-9/README.md index a76dcefc69..38816471aa 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -15,10 +15,7 @@ - [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) - [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional) - [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams) -- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) - [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new) -- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) -- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime) - [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles) - [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client) - [Method Handles in Java](http://www.baeldung.com/java-method-handles) @@ -26,3 +23,7 @@ - [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity) - [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional) - [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api) +- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) +- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) +- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) diff --git a/core-java-9/logging.sh b/core-java-9/logging.sh new file mode 100755 index 0000000000..c9b502f300 --- /dev/null +++ b/core-java-9/logging.sh @@ -0,0 +1,15 @@ +# compile logging module +# javac --module-path mods -d mods/com.baeldung.logging src/modules/com.baeldung.logging/module-info.java src/modules/com.baeldung.logging/com/baeldung/logging/*.java + +# compile logging slf4j module +javac --module-path mods -d mods/com.baeldung.logging.slf4j src/modules/com.baeldung.logging.slf4j/module-info.java src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/*.java + + +# compile logging main app module +javac --module-path mods -d mods/com.baeldung.logging.app src/modules/com.baeldung.logging.app/module-info.java src/modules/com.baeldung.logging.app/com/baeldung/logging/app/*.java + +# run logging main app +# java --module-path mods -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp + +# run looging main app using logback +java --module-path mods -Dlogback.configurationFile=mods/logback.xml -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp diff --git a/core-java-9/mods/logback.xml b/core-java-9/mods/logback.xml new file mode 100644 index 0000000000..c22c7a7130 --- /dev/null +++ b/core-java-9/mods/logback.xml @@ -0,0 +1,16 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} -- %msg%n + + + + + + + + + \ No newline at end of file diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java new file mode 100644 index 0000000000..46c2e688ce --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java @@ -0,0 +1,15 @@ +package com.baeldung.java9.process; + +import java.util.Scanner; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ChildProcess { + + public static void main(String[] args) { + @SuppressWarnings("resource") + Scanner input = new Scanner(System.in); + Logger log = Logger.getLogger(ChildProcess.class.getName()); + log.log(Level.INFO, input.nextLine()); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java new file mode 100644 index 0000000000..443847916a --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java @@ -0,0 +1,16 @@ +package com.baeldung.java9.process; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public class OutputStreamExample { + + public static void main(String[] args) { + Logger log = Logger.getLogger(OutputStreamExample.class.getName()); + log.log(Level.INFO, Integer.toString(sum(1,2))); + } + + public static int sum(int a, int b) { + return a + b; + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java new file mode 100644 index 0000000000..8b6ae0b441 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java @@ -0,0 +1,7 @@ +package com.baeldung.java9.process; + +public class ProcessCompilationError { + //This method has been written to generate error to display + //how process errorStream() can consume error + public static void(); +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java new file mode 100644 index 0000000000..74101ba3da --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java @@ -0,0 +1,110 @@ +package com.baeldung.java9.process; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ProcessUnderstanding { + + public static int compileAndRunJavaProgram() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + return value; + } + + public static String getErrorStreamExample() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java"); + BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); + String errorString = error.readLine(); + return errorString; + } + + public static void creatingNewProcess() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + } + + public static int filterProcessWithStreamsInSpecificRangeReturnCount() { + return (int) ProcessHandle.allProcesses() + .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000)) + .count(); + } + + public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + } + + public static void destroyingProcessCreatedByDifferentProcess() { + // find out the process id of current running task by checking + // task manager in windows and enter the integer value + Optional optionalProcessHandle = ProcessHandle.of(5232); + ProcessHandle processHandle = optionalProcessHandle.get(); + processHandle.destroy(); + } + + public static int waitForExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + return process.waitFor(); + } + + public static int exitValueExample() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + process.destroy(); + return process.exitValue(); + } + + public static void destroyExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + } + + public static void destroyForciblyExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + if (process.isAlive()) { + process.destroyForcibly(); + } + } + + public static void outputStreamDemo() throws IOException, InterruptedException { + Logger log = Logger.getLogger(ProcessUnderstanding.class.getName()); + Process pr = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java"); + final Process process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess"); + try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) { + w.write("send to child\n"); + } + new Thread(() -> { + try { + int c; + while ((c = process.getInputStream() + .read()) != -1) + System.out.write((byte) c); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + // send to child + log.log(Level.INFO, "rc=" + process.waitFor()); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java b/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java new file mode 100644 index 0000000000..f5ec5d29dc --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java @@ -0,0 +1,24 @@ +package com.baeldung.java9.rangedates; + +import java.util.Collection; +import java.util.Date; + +public class DatesCollectionIteration { + + public void iteratingRangeOfDatesJava7(Collection dates) { + + for (Date date : dates) { + processDate(date); + } + } + + public void iteratingRangeOfDatesJava8(Collection dates) { + dates.stream() + .forEach(this::processDate); + } + + private void processDate(Date date) { + System.out.println(date); + } + +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java b/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java new file mode 100644 index 0000000000..4972036c91 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java @@ -0,0 +1,43 @@ +package com.baeldung.java9.rangedates; + +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; + +public class RangeDatesIteration { + + public void iterateBetweenDatesJava9(LocalDate startDate, LocalDate endDate) { + + startDate.datesUntil(endDate) + .forEach(this::processDate); + } + + public void iterateBetweenDatesJava8(LocalDate start, LocalDate end) { + for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) { + processDate(date); + } + } + + public void iterateBetweenDatesJava7(Date start, Date end) { + Date current = start; + + while (current.before(end)) { + processDate(current); + + Calendar calendar = Calendar.getInstance(); + calendar.setTime(current); + + calendar.add(Calendar.DATE, 1); + + current = calendar.getTime(); + } + } + + private void processDate(LocalDate date) { + System.out.println(date); + } + + private void processDate(Date date) { + System.out.println(date); + } +} diff --git a/core-java-9/src/main/resources/logback.xml b/core-java-9/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/core-java-9/src/main/resources/logback.xml +++ b/core-java-9/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java-9/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java b/core-java-9/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java new file mode 100644 index 0000000000..01f53d59e9 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java @@ -0,0 +1,13 @@ +package com.baeldung.logging.app; + +import static java.lang.System.Logger.*; + +public class MainApp { + + private static System.Logger LOGGER = System.getLogger("MainApp"); + + public static void main(String[] args) { + LOGGER.log(Level.ERROR, "error test"); + LOGGER.log(Level.INFO, "info test"); + } +} diff --git a/core-java-9/src/modules/com.baeldung.logging.app/module-info.java b/core-java-9/src/modules/com.baeldung.logging.app/module-info.java new file mode 100644 index 0000000000..037c72b755 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging.app/module-info.java @@ -0,0 +1,2 @@ +module com.baeldung.logging.app { +} \ No newline at end of file diff --git a/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java new file mode 100644 index 0000000000..df41e071fd --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java @@ -0,0 +1,99 @@ +package com.baeldung.logging.slf4j; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ResourceBundle; + +public class Slf4jLogger implements System.Logger { + + private final String name; + private final Logger logger; + + public Slf4jLogger(String name) { + this.name = name; + logger = LoggerFactory.getLogger(name); + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isLoggable(Level level) { + switch (level) { + case OFF: + return false; + case TRACE: + return logger.isTraceEnabled(); + case DEBUG: + return logger.isDebugEnabled(); + case INFO: + return logger.isInfoEnabled(); + case WARNING: + return logger.isWarnEnabled(); + case ERROR: + return logger.isErrorEnabled(); + case ALL: + default: + return true; + } + } + + @Override + public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) { + if (!isLoggable(level)) { + return; + } + + switch (level) { + case TRACE: + logger.trace(msg, thrown); + break; + case DEBUG: + logger.debug(msg, thrown); + break; + case INFO: + logger.info(msg, thrown); + break; + case WARNING: + logger.warn(msg, thrown); + break; + case ERROR: + logger.error(msg, thrown); + break; + case ALL: + default: + logger.info(msg, thrown); + } + } + + @Override + public void log(Level level, ResourceBundle bundle, String format, Object... params) { + if (!isLoggable(level)) { + return; + } + + switch (level) { + case TRACE: + logger.trace(format, params); + break; + case DEBUG: + logger.debug(format, params); + break; + case INFO: + logger.info(format, params); + break; + case WARNING: + logger.warn(format, params); + break; + case ERROR: + logger.error(format, params); + break; + case ALL: + default: + logger.info(format, params); + } + } +} diff --git a/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java new file mode 100644 index 0000000000..97f7cccb92 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java @@ -0,0 +1,8 @@ +package com.baeldung.logging.slf4j; + +public class Slf4jLoggerFinder extends System.LoggerFinder { + @Override + public System.Logger getLogger(String name, Module module) { + return new Slf4jLogger(name); + } +} diff --git a/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java b/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java new file mode 100644 index 0000000000..311ca22f5b --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java @@ -0,0 +1,6 @@ +module com.baeldung.logging.slf4j { + requires org.slf4j; + provides java.lang.System.LoggerFinder + with com.baeldung.logging.slf4j.Slf4jLoggerFinder; + exports com.baeldung.logging.slf4j; +} \ No newline at end of file diff --git a/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java new file mode 100644 index 0000000000..a495e6979d --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java @@ -0,0 +1,27 @@ +package com.baeldung.logging; + +import java.text.MessageFormat; +import java.util.ResourceBundle; + +public class ConsoleLogger implements System.Logger { + + @Override + public String getName() { + return "ConsoleLogger"; + } + + @Override + public boolean isLoggable(Level level) { + return true; + } + + @Override + public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) { + System.out.printf("ConsoleLogger [%s]: %s - %s%n", level, msg, thrown); + } + + @Override + public void log(Level level, ResourceBundle bundle, String format, Object... params) { + System.out.printf("ConsoleLogger [%s]: %s%n", level, MessageFormat.format(format, params)); + } +} diff --git a/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java new file mode 100644 index 0000000000..b38955f199 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java @@ -0,0 +1,9 @@ +package com.baeldung.logging; + +public class CustomLoggerFinder extends System.LoggerFinder { + + @Override + public System.Logger getLogger(String name, Module module) { + return new ConsoleLogger(); + } +} diff --git a/core-java-9/src/modules/com.baeldung.logging/module-info.java b/core-java-9/src/modules/com.baeldung.logging/module-info.java new file mode 100644 index 0000000000..4ca0af0225 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.logging/module-info.java @@ -0,0 +1,5 @@ +module com.baeldung.logging { + provides java.lang.System.LoggerFinder + with com.baeldung.logging.CustomLoggerFinder; + exports com.baeldung.logging; +} \ No newline at end of file diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java new file mode 100644 index 0000000000..2c5525b9ed --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java @@ -0,0 +1,121 @@ +package com.baeldung.java9.process; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.String; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.lang.Integer; + +import org.junit.jupiter.api.Test; + +class ProcessUnderstandingTest { + + @Test + public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + assertEquals(3, value); + } + + @Test + public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + assertEquals(3, value); + } + + @Test + public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java"); + BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); + String errorString = error.readLine(); + assertNotNull(errorString); + } + + //@Test - windows specific + public void givenSubProcess_whenStarted_thenStartSuccessIsAlive() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + assertTrue(builder.start().isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + assertFalse(process.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + if (process.isAlive()) { + process.destroyForcibly(); + } + assertFalse(process.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenDestroyed_thenCheckIfAlive() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + assertFalse(process.isAlive()); + } + + @Test + public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() { + Optional optionalProcessHandle = ProcessHandle.of(5232); + ProcessHandle processHandle = optionalProcessHandle.get(); + processHandle.destroy(); + assertFalse(processHandle.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertThat(process.waitFor() >= 0); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertFalse(process.waitFor(1, TimeUnit.SECONDS)); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertThat(process.exitValue() >= 0); + } + + @Test + public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() { + assertThat(((int) ProcessHandle.allProcesses() + .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000)) + .count()) > 0); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java new file mode 100644 index 0000000000..522b00065e --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.java9.rangedates; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class DatesCollectionIterationUnitTest { + + private Collection localDates = LocalDate.now() + .datesUntil(LocalDate.now() + .plus(10L, ChronoUnit.DAYS)) + .collect(Collectors.toList()); + + private Collection dates = localDates.stream() + .map(localDate -> Date.from(localDate.atStartOfDay(ZoneId.systemDefault()) + .toInstant())) + .collect(Collectors.toList()); + + @Test + public void givenIteratingListOfDatesJava7_WhenStartTodayAndEnding10DaysAhead() { + DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration(); + Calendar today = Calendar.getInstance(); + Calendar next10Ahead = (Calendar) today.clone(); + next10Ahead.add(Calendar.DATE, 10); + + iterateInColleciton.iteratingRangeOfDatesJava7(createRangeDates(today.getTime(), next10Ahead.getTime())); + } + + @Test + public void givenIteratingListOfDatesJava8_WhenStartTodayAndEnd10DaysAhead() { + DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration(); + + iterateInColleciton.iteratingRangeOfDatesJava8(dates); + } + + private List createRangeDates(Date start, Date end) { + + List dates = new ArrayList<>(); + Date current = start; + + while (current.before(end)) { + dates.add(current); + + Calendar calendar = Calendar.getInstance(); + calendar.setTime(current); + calendar.add(Calendar.DATE, 1); + + current = calendar.getTime(); + } + + return dates; + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java new file mode 100644 index 0000000000..4f5cd17d98 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.java9.rangedates; + +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +public class RangeDatesIterationUnitTest { + + @Test + public void givenIterateBetweenDatesJava9_WhenStartDateAsTodayAndEndDateAs10DaysAhead() { + LocalDate start = LocalDate.now(); + LocalDate end = start.plus(10L, ChronoUnit.DAYS); + + RangeDatesIteration iteration = new RangeDatesIteration(); + + iteration.iterateBetweenDatesJava9(start, end); + } + + @Test + public void givenIterateBetweenDatesJava8_WhenStartDateAsTodayAndEndDateAs10DaysAhead() { + LocalDate start = LocalDate.now(); + LocalDate end = start.plus(10L, ChronoUnit.DAYS); + + RangeDatesIteration iteration = new RangeDatesIteration(); + + iteration.iterateBetweenDatesJava8(start, end); + } + + @Test + public void givenIterateBetweenDatesJava7_WhenStartDateAsTodayAndEndDateAs10DaysAhead() { + Calendar today = Calendar.getInstance(); + Calendar calendar = Calendar.getInstance(); + calendar.clear(); + calendar.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE)); + Date start = calendar.getTime(); + + calendar.add(Calendar.DATE, 10); + Date end = calendar.getTime(); + + RangeDatesIteration iteration = new RangeDatesIteration(); + + iteration.iterateBetweenDatesJava7(start, end); + } + +} diff --git a/core-java-collections/README.md b/core-java-collections/README.md index 8f5dd137ed..aef640634e 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -36,3 +36,22 @@ - [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list) - [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map) - [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset) +- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element) +- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) +- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection) +- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) +- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) +- [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) +- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) +- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list) +- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe) +- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) +- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall) +- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance) +- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value) +- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity) +- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort) +- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max) +- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index 1290419a6a..b4a6e26d13 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -1,67 +1,88 @@ - - 4.0.0 - com.baeldung - core-java-collections - 0.1.0-SNAPSHOT - jar - core-java-collections - - - 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} - - - com.jayway.awaitility - awaitility - ${avaitility.version} - test - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - org.eclipse.collections - eclipse-collections - ${eclipse.collections.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - - 1.2.0 - 3.5 - 4.1 - 4.01 - 1.7.0 - 3.6.1 - 9.2.0 - - + + 4.0.0 + core-java-collections + 0.1.0-SNAPSHOT + jar + core-java-collections + + + 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} + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.eclipse.collections + eclipse-collections + ${eclipse.collections.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.openjdk.jmh + jmh-core + ${openjdk.jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk.jmh.version} + + + org.apache.commons + commons-exec + 1.3 + + + + one.util + streamex + 0.6.5 + + + + + 1.19 + 1.2.0 + 3.5 + 4.1 + 4.01 + 1.7.0 + 3.6.1 + 7.1.0 + + diff --git a/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningArrays.java b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningArrays.java new file mode 100644 index 0000000000..2ad48033c0 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningArrays.java @@ -0,0 +1,39 @@ +package com.baeldung.combiningcollections; + +import java.util.Arrays; +import java.util.stream.Stream; + +import org.apache.commons.lang3.ArrayUtils; + +import com.google.common.collect.ObjectArrays; + +public class CombiningArrays { + + public static Object[] usingNativeJava(Object[] first, Object[] second) { + Object[] combined = new Object[first.length + second.length]; + System.arraycopy(first, 0, combined, 0, first.length); + System.arraycopy(second, 0, combined, first.length, second.length); + return combined; + } + + public static Object[] usingJava8ObjectStream(Object[] first, Object[] second) { + Object[] combined = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(); + return combined; + } + + public static Object[] usingJava8FlatMaps(Object[] first, Object[] second) { + Object[] combined = Stream.of(first, second).flatMap(Stream::of).toArray(String[]::new); + return combined; + } + + public static Object[] usingApacheCommons(Object[] first, Object[] second) { + Object[] combined = ArrayUtils.addAll(first, second); + return combined; + } + + public static Object[] usingGuava(Object[] first, Object[] second) { + Object [] combined = ObjectArrays.concat(first, second, Object.class); + return combined; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningLists.java b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningLists.java new file mode 100644 index 0000000000..3fdf672758 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningLists.java @@ -0,0 +1,46 @@ +package com.baeldung.combiningcollections; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.collections4.ListUtils; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +public class CombiningLists { + + public static List usingNativeJava(List first, List second) { + List combined = new ArrayList<>(); + combined.addAll(first); + combined.addAll(second); + return combined; + } + + public static List usingJava8ObjectStream(List first, List second) { + List combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toList()); + return combined; + } + + public static List usingJava8FlatMaps(List first, List second) { + List combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toList()); + return combined; + } + + public static List usingApacheCommons(List first, List second) { + List combined = ListUtils.union(first, second); + return combined; + } + + public static List usingGuava(List first, List second) { + Iterable combinedIterables = Iterables.unmodifiableIterable( + Iterables.concat(first, second)); + + List combined = Lists.newArrayList(combinedIterables); + return combined; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningMaps.java b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningMaps.java new file mode 100644 index 0000000000..d8bbd01ed3 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningMaps.java @@ -0,0 +1,47 @@ +package com.baeldung.combiningcollections; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.exec.util.MapUtils; + +import com.google.common.collect.ImmutableMap; + +public class CombiningMaps { + + public static Map usingPlainJava(Map first, Map second) { + Map combined = new HashMap<>(); + combined.putAll(first); + combined.putAll(second); + return combined; + } + + public static Map usingJava8ForEach(Map first, Map second) { + second.forEach((key, value) -> first.merge(key, value, String::concat)); + return first; + } + + public static Map usingJava8FlatMaps(Map first, Map second) { + Map combined = Stream.of(first, second).map(Map::entrySet).flatMap(Collection::stream) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, String::concat)); + return combined; + + } + + public static Map usingApacheCommons(Map first, Map second) { + Map combined = MapUtils.merge(first, second); + return combined; + } + + public static Map usingGuava(Map first, Map second) { + Map combined = ImmutableMap.builder() + .putAll(first) + .putAll(second) + .build(); + return combined; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningSets.java b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningSets.java new file mode 100644 index 0000000000..5f531c1d43 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningSets.java @@ -0,0 +1,42 @@ +package com.baeldung.combiningcollections; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.collections4.SetUtils; + +import com.google.common.collect.Sets; + +public class CombiningSets { + + public static Set usingNativeJava(Set first, Set second) { + Set combined = new HashSet<>(); + combined.addAll(first); + combined.addAll(second); + return combined; + } + + public static Set usingJava8ObjectStream(Set first, Set second) { + Set combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toSet()); + return combined; + } + + public static Set usingJava8FlatMaps(Set first, Set second) { + Set combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toSet()); + return combined; + } + + public static Set usingApacheCommons(Set first, Set second) { + Set combined = SetUtils.union(first, second); + return combined; + } + + public static Set usingGuava(Set first, Set second) { + Set combined = Sets.union(first, second); + return combined; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java b/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java new file mode 100644 index 0000000000..5c9464182e --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java @@ -0,0 +1,52 @@ +package com.baeldung.convertcollectiontoarraylist; + +/** + * This POJO is the element type of our collection. It has a deepCopy() method. + * + * @author chris + */ +public class Foo { + + private int id; + private String name; + private Foo parent; + + public Foo() { + } + + public Foo(int id, String name, Foo parent) { + this.id = id; + this.name = name; + this.parent = parent; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Foo getParent() { + return parent; + } + + public void setParent(Foo parent) { + this.parent = parent; + } + + public Foo deepCopy() { + return new Foo( + this.id, this.name, this.parent != null ? this.parent.deepCopy() : null); + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java b/core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java new file mode 100644 index 0000000000..7b93ed8737 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java @@ -0,0 +1,45 @@ +package com.baeldung.enumset; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; + +public class EnumSets { + + public enum Color { + RED, YELLOW, GREEN, BLUE, BLACK, WHITE + } + + public static void main(String[] args) { + EnumSet allColors = EnumSet.allOf(Color.class); + System.out.println(allColors); + + EnumSet noColors = EnumSet.noneOf(Color.class); + System.out.println(noColors); + + EnumSet blackAndWhite = EnumSet.of(Color.BLACK, Color.WHITE); + System.out.println(blackAndWhite); + + EnumSet noBlackOrWhite = EnumSet.complementOf(blackAndWhite); + System.out.println(noBlackOrWhite); + + EnumSet range = EnumSet.range(Color.YELLOW, Color.BLUE); + System.out.println(range); + + EnumSet blackAndWhiteCopy = EnumSet.copyOf(EnumSet.of(Color.BLACK, Color.WHITE)); + System.out.println(blackAndWhiteCopy); + + List colorsList = new ArrayList<>(); + colorsList.add(Color.RED); + EnumSet listCopy = EnumSet.copyOf(colorsList); + System.out.println(listCopy); + + EnumSet set = EnumSet.noneOf(Color.class); + set.add(Color.RED); + set.add(Color.YELLOW); + set.contains(Color.RED); + set.forEach(System.out::println); + set.remove(Color.RED); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/Customer.java b/core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/findanelement/Customer.java rename to core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java b/core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java rename to core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java diff --git a/core-java-8/src/main/java/com/baeldung/hashtable/Word.java b/core-java-collections/src/main/java/com/baeldung/hashtable/Word.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/hashtable/Word.java rename to core-java-collections/src/main/java/com/baeldung/hashtable/Word.java diff --git a/core-java-8/src/main/java/com/baeldung/iterators/Iterators.java b/core-java-collections/src/main/java/com/baeldung/iterators/Iterators.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/iterators/Iterators.java rename to core-java-collections/src/main/java/com/baeldung/iterators/Iterators.java diff --git a/core-java-8/src/main/java/com/baeldung/list/CopyListService.java b/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java similarity index 98% rename from core-java-8/src/main/java/com/baeldung/list/CopyListService.java rename to core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java index 55d5bb9379..5c92d856aa 100644 --- a/core-java-8/src/main/java/com/baeldung/list/CopyListService.java +++ b/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java @@ -1,4 +1,4 @@ -package com.baeldung.list; +package com.baeldung.java.list; import java.util.ArrayList; import java.util.Collections; diff --git a/core-java-collections/src/main/java/com/baeldung/java/map/MapUtil.java b/core-java-collections/src/main/java/com/baeldung/java/map/MapUtil.java new file mode 100644 index 0000000000..688c7592f3 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/map/MapUtil.java @@ -0,0 +1,44 @@ +/** + * + */ +package com.baeldung.java.map; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; +import java.util.stream.Stream; + +/** + * @author swpraman + * + */ +public class MapUtil { + + public static Stream keys(Map map, V value) { + return map.entrySet() + .stream() + .filter(entry -> value.equals(entry.getValue())) + .map(Map.Entry::getKey); + } + + public static Set getKeys(Map map, V value) { + Set keys = new HashSet<>(); + for (Entry entry : map.entrySet()) { + if (entry.getValue().equals(value)) { + keys.add(entry.getKey()); + } + } + return keys; + } + + public static K getKey(Map map, V value) { + for (Entry entry : map.entrySet()) { + if (entry.getValue().equals(value)) { + return entry.getKey(); + } + } + return null; + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java b/core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Car.java rename to core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Person.java b/core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Person.java rename to core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java diff --git a/core-java-collections/src/main/java/com/baeldung/map/java_8/MergeMaps.java b/core-java-collections/src/main/java/com/baeldung/map/java_8/MergeMaps.java new file mode 100644 index 0000000000..052cfb8bad --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/map/java_8/MergeMaps.java @@ -0,0 +1,105 @@ +package com.baeldung.map.java_8; + +import com.baeldung.sort.Employee; +import one.util.streamex.EntryStream; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class MergeMaps { + + private static Map map1 = new HashMap<>(); + private static Map map2 = new HashMap<>(); + + public static void main(String[] args) { + + initialize(); + + mergeFunction(); + + streamConcat(); + + streamOf(); + + streamEx(); + + streamMerge(); + } + + private static void streamMerge() { + + Map map3 = map2.entrySet() + .stream() + .collect( + Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (v1, v2) -> new Employee(v1.getId(), v2.getName()), + () -> new HashMap<>(map1) + ) + ); + + System.out.println(map3); + } + + private static void streamEx() { + Map map3 = EntryStream.of(map1) + .append(EntryStream.of(map2)) + .toMap((e1, e2) -> e1); + + System.out.println(map3); + + } + + private static void streamOf() { + Map map3 = Stream.of(map1, map2) + .flatMap(map -> map.entrySet().stream()) + .collect( + Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (v1, v2) -> new Employee(v1.getId(), v2.getName()) + ) + ); + + map3.entrySet().forEach(System.out::println); + } + + private static void streamConcat() { + Map result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (value1, value2) -> new Employee(value2.getId(), value1.getName()) + )); + + result.entrySet().forEach(System.out::println); + } + + private static void mergeFunction() { + Map map3 = new HashMap<>(map1); + + map2.forEach( + (key, value) -> map3.merge(key, value, (v1, v2) -> + new Employee(v1.getId(), v2.getName())) + ); + + map3.entrySet().forEach(System.out::println); + } + + + private static void initialize() { + Employee employee1 = new Employee(1L, "Henry"); + map1.put(employee1.getName(), employee1); + Employee employee2 = new Employee(22L, "Annie"); + map1.put(employee2.getName(), employee2); + Employee employee3 = new Employee(8L, "John"); + map1.put(employee3.getName(), employee3); + + Employee employee4 = new Employee(2L, "George"); + map2.put(employee4.getName(), employee4); + Employee employee5 = new Employee(3L, "Henry"); + map2.put(employee5.getName(), employee5); + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/map/util/MapMax.java b/core-java-collections/src/main/java/com/baeldung/map/util/MapMax.java new file mode 100644 index 0000000000..93a98ba6fd --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/map/util/MapMax.java @@ -0,0 +1,96 @@ +package com.baeldung.map.util; + +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + +public class MapMax { + + public > V maxUsingIteration(Map map) { + + Map.Entry maxEntry = null; + + for (Map.Entry entry : map.entrySet()) { + + if (maxEntry == null || entry.getValue() + .compareTo(maxEntry.getValue()) > 0) { + maxEntry = entry; + } + } + + return maxEntry.getValue(); + } + + public > V maxUsingCollectionsMax(Map map) { + + Entry maxEntry = Collections.max(map.entrySet(), new Comparator>() { + public int compare(Entry e1, Entry e2) { + return e1.getValue() + .compareTo(e2.getValue()); + } + }); + + return maxEntry.getValue(); + } + + public > V maxUsingCollectionsMaxAndLambda(Map map) { + + Entry maxEntry = Collections.max(map.entrySet(), (Entry e1, Entry e2) -> e1.getValue() + .compareTo(e2.getValue())); + + return maxEntry.getValue(); + } + + public > V maxUsingCollectionsMaxAndMethodReference(Map map) { + + Entry maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue)); + + return maxEntry.getValue(); + } + + public > V maxUsingStreamAndLambda(Map map) { + + Optional> maxEntry = map.entrySet() + .stream() + .max((Entry e1, Entry e2) -> e1.getValue() + .compareTo(e2.getValue())); + + return maxEntry.get() + .getValue(); + } + + public > V maxUsingStreamAndMethodReference(Map map) { + + Optional> maxEntry = map.entrySet() + .stream() + .max(Comparator.comparing(Map.Entry::getValue)); + + return maxEntry.get() + .getValue(); + } + + public static void main(String[] args) { + + Map map = new HashMap(); + + map.put(1, 3); + map.put(2, 4); + map.put(3, 5); + map.put(4, 6); + map.put(5, 7); + + MapMax mapMax = new MapMax(); + + System.out.println(mapMax.maxUsingIteration(map)); + System.out.println(mapMax.maxUsingCollectionsMax(map)); + System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map)); + System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map)); + System.out.println(mapMax.maxUsingStreamAndLambda(map)); + System.out.println(mapMax.maxUsingStreamAndMethodReference(map)); + + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java new file mode 100644 index 0000000000..dddd85007d --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java @@ -0,0 +1,77 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 10) +public class ArrayListBenchmark { + + @State(Scope.Thread) + public static class MyState { + + List employeeList = new ArrayList<>(); + //LinkedList employeeList = new LinkedList<>(); + + long iterations = 100000; + + Employee employee = new Employee(100L, "Harry"); + + int employeeIndex = -1; + + @Setup(Level.Trial) + public void setUp() { + for (long i = 0; i < iterations; i++) { + employeeList.add(new Employee(i, "John")); + } + + employeeList.add(employee); + employeeIndex = employeeList.indexOf(employee); + } + } + + @Benchmark + public void testAddAt(ArrayListBenchmark.MyState state) { + state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John")); + } + + @Benchmark + public boolean testContains(ArrayListBenchmark.MyState state) { + return state.employeeList.contains(state.employee); + } + + @Benchmark + public int testIndexOf(ArrayListBenchmark.MyState state) { + return state.employeeList.indexOf(state.employee); + } + + @Benchmark + public Employee testGet(ArrayListBenchmark.MyState state) { + return state.employeeList.get(state.employeeIndex); + } + + @Benchmark + public boolean testRemove(ArrayListBenchmark.MyState state) { + return state.employeeList.remove(state.employee); + } + +// @Benchmark +// public void testAdd(ArrayListBenchmark.MyState state) { +// state.employeeList.add(new Employee(state.iterations + 1, "John")); +// } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(ArrayListBenchmark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java new file mode 100644 index 0000000000..921e1608ea --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java @@ -0,0 +1,59 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 5) +public class CollectionsBenchmark { + + @State(Scope.Thread) + public static class MyState { + private Set employeeSet = new HashSet<>(); + private List employeeList = new ArrayList<>(); + + private long iterations = 10000; + + private Employee employee = new Employee(100L, "Harry"); + + @Setup(Level.Trial) + public void setUp() { + + for (long i = 0; i < iterations; i++) { + employeeSet.add(new Employee(i, "John")); + employeeList.add(new Employee(i, "John")); + } + + employeeList.add(employee); + employeeSet.add(employee); + } + } + + @Benchmark + public boolean testArrayList(MyState state) { + return state.employeeList.contains(state.employee); + } + + @Benchmark + public boolean testHashSet(MyState state) { + return state.employeeSet.contains(state.employee); + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(CollectionsBenchmark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CopyOnWriteBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CopyOnWriteBenchmark.java new file mode 100644 index 0000000000..30c50291dd --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/CopyOnWriteBenchmark.java @@ -0,0 +1,78 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 10) +public class CopyOnWriteBenchmark { + + @State(Scope.Thread) + public static class MyState { + + CopyOnWriteArrayList employeeList = new CopyOnWriteArrayList<>(); + + long iterations = 100000; + + Employee employee = new Employee(100L, "Harry"); + + int employeeIndex = -1; + + @Setup(Level.Trial) + public void setUp() { + for (long i = 0; i < iterations; i++) { + employeeList.add(new Employee(i, "John")); + } + + employeeList.add(employee); + + employeeIndex = employeeList.indexOf(employee); + } + } + + @Benchmark + public void testAdd(CopyOnWriteBenchmark.MyState state) { + state.employeeList.add(new Employee(state.iterations + 1, "John")); + } + + @Benchmark + public void testAddAt(CopyOnWriteBenchmark.MyState state) { + state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John")); + } + + @Benchmark + public boolean testContains(CopyOnWriteBenchmark.MyState state) { + return state.employeeList.contains(state.employee); + } + + @Benchmark + public int testIndexOf(CopyOnWriteBenchmark.MyState state) { + return state.employeeList.indexOf(state.employee); + } + + @Benchmark + public Employee testGet(CopyOnWriteBenchmark.MyState state) { + return state.employeeList.get(state.employeeIndex); + } + + @Benchmark + public boolean testRemove(CopyOnWriteBenchmark.MyState state) { + return state.employeeList.remove(state.employee); + } + + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(CopyOnWriteBenchmark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java new file mode 100644 index 0000000000..1ed4410371 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java @@ -0,0 +1,55 @@ +package com.baeldung.performance; + +public class Employee { + + private Long id; + private String name; + + public Employee(Long id, String name) { + this.name = name; + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Employee employee = (Employee) o; + + if (!id.equals(employee.id)) return false; + return name.equals(employee.name); + + } + + @Override + public int hashCode() { + int result = id.hashCode(); + result = 31 * result + name.hashCode(); + return result; + } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/HashMapBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/HashMapBenchmark.java new file mode 100644 index 0000000000..085daaceb7 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/HashMapBenchmark.java @@ -0,0 +1,73 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 10) +public class HashMapBenchmark { + + @State(Scope.Thread) + public static class MyState { + + Map employeeMap = new HashMap<>(); + //LinkedHashMap employeeMap = new LinkedHashMap<>(); + //IdentityHashMap employeeMap = new IdentityHashMap<>(); + //WeakHashMap employeeMap = new WeakHashMap<>(); + //ConcurrentHashMap employeeMap = new ConcurrentHashMap<>(); + //ConcurrentSkipListMap employeeMap = new ConcurrentSkipListMap <>(); + + // TreeMap + + long iterations = 100000; + + Employee employee = new Employee(100L, "Harry"); + + int employeeIndex = -1; + + @Setup(Level.Trial) + public void setUp() { + for (long i = 0; i < iterations; i++) { + employeeMap.put(i, new Employee(i, "John")); + } + + //employeeMap.put(iterations, employee); + } + } + + @Benchmark + public Employee testGet(HashMapBenchmark.MyState state) { + return state.employeeMap.get(state.iterations); + } + + @Benchmark + public Employee testRemove(HashMapBenchmark.MyState state) { + return state.employeeMap.remove(state.iterations); + } + + @Benchmark + public Employee testPut(HashMapBenchmark.MyState state) { + return state.employeeMap.put(state.employee.getId(), state.employee); + } + + @Benchmark + public Boolean testContainsKey(HashMapBenchmark.MyState state) { + return state.employeeMap.containsKey(state.employee.getId()); + } + + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(HashMapBenchmark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/SetBenchMark.java b/core-java-collections/src/main/java/com/baeldung/performance/SetBenchMark.java new file mode 100644 index 0000000000..f70bab4fcf --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/SetBenchMark.java @@ -0,0 +1,66 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 10) +public class SetBenchMark { + + @State(Scope.Thread) + public static class MyState { + + //Set employeeSet = new HashSet<>(); + LinkedHashSet employeeSet = new LinkedHashSet<>(); + //ConcurrentSkipListSet employeeSet = new ConcurrentSkipListSet <>(); + + // TreeSet  + + long iterations = 1000; + Employee employee = new Employee(100L, "Harry"); + + @Setup(Level.Trial) + public void setUp() { + for (long i = 0; i < iterations; i++) { + employeeSet.add(new Employee(i, "John")); + } + + //employeeSet.add(employee); + } + } + + @Benchmark + public boolean testAdd(SetBenchMark.MyState state) { + return state.employeeSet.add(state.employee); + } + + @Benchmark + public Boolean testContains(SetBenchMark.MyState state) { + return state.employeeSet.contains(state.employee); + } + + @Benchmark + public boolean testRemove(SetBenchMark.MyState state) { + return state.employeeSet.remove(state.employee); + } + + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(SetBenchMark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/sort/Employee.java b/core-java-collections/src/main/java/com/baeldung/sort/Employee.java new file mode 100644 index 0000000000..b5e56f6141 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/sort/Employee.java @@ -0,0 +1,60 @@ +package com.baeldung.sort; + +public class Employee implements Comparable { + + private Long id; + private String name; + + public Employee(Long id, String name) { + this.name = name; + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Employee employee = (Employee) o; + + if (!id.equals(employee.id)) return false; + return name.equals(employee.name); + + } + + @Override + public int hashCode() { + int result = id.hashCode(); + result = 31 * result + name.hashCode(); + return result; + } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } + + @Override + public int compareTo(Employee employee) { + return (int)(this.id - employee.getId()); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java new file mode 100644 index 0000000000..b8a2b32060 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -0,0 +1,104 @@ +package com.baeldung.sort; + +import com.google.common.base.Functions; +import com.google.common.collect.ImmutableSortedMap; +import com.google.common.collect.Lists; +import com.google.common.collect.Ordering; + +import java.util.*; +import java.util.stream.Collectors; + +public class SortHashMap { + + private static Map map = new HashMap<>(); + + public static void main(String[] args) { + + initialize(); + + treeMapSortByKey(); + + arrayListSortByValue(); + arrayListSortByKey(); + + sortStream(); + + sortGuava(); + + addDuplicates(); + + treeSetByKey(); + treeSetByValue(); + + } + + private static void sortGuava() { + final Ordering naturalOrdering = + Ordering.natural().onResultOf(Functions.forMap(map, null)); + + System.out.println(ImmutableSortedMap.copyOf(map, naturalOrdering)); + } + + private static void sortStream() { + map.entrySet().stream() + .sorted(Map.Entry.comparingByKey().reversed()) + .forEach(System.out::println); + + Map result = map.entrySet().stream() + .sorted(Map.Entry.comparingByValue()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, + (oldValue, newValue) -> oldValue, LinkedHashMap::new)); + + result.entrySet().forEach(System.out::println); + } + + private static void treeSetByValue() { + SortedSet values = new TreeSet<>(map.values()); + System.out.println(values); + } + + private static void treeSetByKey() { + SortedSet keysSet = new TreeSet<>(map.keySet()); + System.out.println(keysSet); + } + + private static void treeMapSortByKey() { + TreeMap sorted = new TreeMap<>(map); + sorted.putAll(map); + + sorted.entrySet().forEach(System.out::println); + + } + + private static void arrayListSortByValue() { + List employeeById = new ArrayList<>(map.values()); + + Collections.sort(employeeById); + + System.out.println(employeeById); + } + + private static void arrayListSortByKey() { + List employeeByKey = new ArrayList<>(map.keySet()); + Collections.sort(employeeByKey); + System.out.println(employeeByKey); + } + + private static void initialize() { + Employee employee1 = new Employee(1L, "Mher"); + map.put(employee1.getName(), employee1); + Employee employee2 = new Employee(22L, "Annie"); + map.put(employee2.getName(), employee2); + Employee employee3 = new Employee(8L, "John"); + map.put(employee3.getName(), employee3); + Employee employee4 = new Employee(2L, "George"); + map.put(employee4.getName(), employee4); + } + + private static void addDuplicates() { + Employee employee5 = new Employee(1L, "Mher"); + map.put(employee5.getName(), employee5); + Employee employee6 = new Employee(22L, "Annie"); + map.put(employee6.getName(), employee6); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/synchronizedcollections/application/Application.java b/core-java-collections/src/main/java/com/baeldung/synchronizedcollections/application/Application.java new file mode 100644 index 0000000000..1840c125d0 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/synchronizedcollections/application/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.synchronizedcollections.application; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.logging.Logger; + +public class Application { + + private static final Logger LOGGER = Logger.getLogger(Application.class.getName()); + + public static void main(String[] args) throws InterruptedException { + List syncCollection = Collections.synchronizedList(Arrays.asList(1, 2, 3, 4, 5, 6)); + synchronized (syncCollection) { + syncCollection.forEach((e) -> {LOGGER.info(e.toString());}); + } + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/collection/ClearVsRemoveAllUnitTest.java b/core-java-collections/src/test/java/com/baeldung/collection/ClearVsRemoveAllUnitTest.java new file mode 100644 index 0000000000..8b0a7ef0db --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/collection/ClearVsRemoveAllUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.collection; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Unit tests demonstrating differences between ArrayList#clear() and ArrayList#removeAll() + */ +class ClearVsRemoveAllUnitTest { + + /* + * Tests + */ + @Test + void givenArrayListWithElements_whenClear_thenListBecomesEmpty() { + Collection collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); + + collection.clear(); + + assertTrue(collection.isEmpty()); + } + + @Test + void givenTwoArrayListsWithCommonElements_whenRemoveAll_thenFirstListMissElementsFromSecondList() { + Collection firstCollection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); + Collection secondCollection = new ArrayList<>(Arrays.asList(3, 4, 5, 6, 7)); + + firstCollection.removeAll(secondCollection); + + assertEquals(Arrays.asList(1, 2), firstCollection); + assertEquals(Arrays.asList(3, 4, 5, 6, 7), secondCollection); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java b/core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java new file mode 100644 index 0000000000..86a262107d --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java @@ -0,0 +1,26 @@ +package com.baeldung.collection; + +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; +import org.junit.Assert; +import org.junit.Test; + +public class CollectionsEmpty { + + @Test + public void givenArrayList_whenAddingElement_addsNewElement() { + ArrayList mutableList = new ArrayList<>(); + mutableList.add("test"); + + Assert.assertEquals(mutableList.size(), 1); + Assert.assertEquals(mutableList.get(0), "test"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() { + List immutableList = Collections.emptyList(); + immutableList.add("test"); + } + +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningArraysUnitTest.java b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningArraysUnitTest.java new file mode 100644 index 0000000000..3b80d773ad --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningArraysUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.combiningcollections; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class CombiningArraysUnitTest { + private static final String first[] = { + "One", + "Two", + "Three" + }; + + private static final String second[] = { + "Four", + "Five", + "Six" + }; + + private static final String expected[] = { + "One", + "Two", + "Three", + "Four", + "Five", + "Six" + }; + + @Test + public void givenTwoArrays_whenUsingNativeJava_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingNativeJava(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingObjectStreams_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingJava8ObjectStream(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingFlatMaps_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingJava8FlatMaps(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingApacheCommons_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingApacheCommons(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingGuava_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingGuava(first, second)); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningListsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningListsUnitTest.java new file mode 100644 index 0000000000..c5851d7daf --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningListsUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.combiningcollections; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class CombiningListsUnitTest { + private static final List first = Arrays.asList(new Object[]{ + "One", + "Two", + "Three" + }); + + private static final List second = Arrays.asList(new Object[]{ + "Four", + "Five", + "Six" + }); + + private static final List expected = Arrays.asList(new Object[]{ + "One", + "Two", + "Three", + "Four", + "Five", + "Six" + }); + + @Test + public void givenTwoLists_whenUsingNativeJava_thenArraysCombined() { + assertThat(CombiningLists.usingNativeJava(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingObjectStreams_thenArraysCombined() { + assertThat(CombiningLists.usingJava8ObjectStream(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingFlatMaps_thenArraysCombined() { + assertThat(CombiningLists.usingJava8FlatMaps(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingApacheCommons_thenArraysCombined() { + assertThat(CombiningLists.usingApacheCommons(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingGuava_thenArraysCombined() { + assertThat(CombiningLists.usingGuava(first, second), is(expected)); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningMapsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningMapsUnitTest.java new file mode 100644 index 0000000000..3fa9cc7dc4 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningMapsUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.combiningcollections; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +public class CombiningMapsUnitTest { + private static final Map first = new HashMap<>(); + private static final Map second = new HashMap<>(); + private static Map expected = new HashMap<>(); + + static { + first.put("one", "first String"); + first.put("two", "second String"); + + second.put("three", "third String"); + second.put("four", "fourth String"); + + expected.put("one", "first String"); + expected.put("two", "second String"); + expected.put("three", "third String"); + expected.put("four", "fourth String"); + } + + @Test + public void givenTwoMaps_whenUsingNativeJava_thenMapsCombined() { + assertThat(CombiningMaps.usingPlainJava(first, second), is(expected)); + } + + + @Test + public void givenTwoMaps_whenUsingForEach_thenMapsCombined() { + assertThat(CombiningMaps.usingJava8ForEach(first, second), is(expected)); + } + + @Test + public void givenTwoMaps_whenUsingFlatMaps_thenMapsCombined() { + assertThat(CombiningMaps.usingJava8FlatMaps(first, second), is(expected)); + } + + @Test + public void givenTwoMaps_whenUsingApacheCommons_thenMapsCombined() { + assertThat(CombiningMaps.usingApacheCommons(first, second), is(expected)); + } + + @Test + public void givenTwoMaps_whenUsingGuava_thenMapsCombined() { + assertThat(CombiningMaps.usingGuava(first, second), is(expected)); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningSetsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningSetsUnitTest.java new file mode 100644 index 0000000000..330827bdc2 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/combiningcollections/CombiningSetsUnitTest.java @@ -0,0 +1,45 @@ + +package com.baeldung.combiningcollections; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; + +public class CombiningSetsUnitTest { + private static final Set first = new HashSet(Arrays.asList(new Object[] { "One", "Two", "Three" })); + + private static final Set second = new HashSet(Arrays.asList(new Object[] { "Four", "Five", "Six" })); + + private static final Set expected = new HashSet(Arrays + .asList(new Object[] { "One", "Two", "Three", "Four", "Five", "Six" })); + + @Test + public void givenTwoSets_whenUsingNativeJava_thenArraysCombined() { + assertThat(CombiningSets.usingNativeJava(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingObjectStreams_thenArraysCombined() { + assertThat(CombiningSets.usingJava8ObjectStream(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingFlatMaps_thenArraysCombined() { + assertThat(CombiningSets.usingJava8FlatMaps(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingApacheCommons_thenArraysCombined() { + assertThat(CombiningSets.usingApacheCommons(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingGuava_thenArraysCombined() { + assertThat(CombiningSets.usingGuava(first, second), is(expected)); + } +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java new file mode 100644 index 0000000000..5be4121bc7 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java @@ -0,0 +1,148 @@ +package com.baeldung.convertcollectiontoarraylist; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import static java.util.stream.Collectors.toCollection; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author chris + */ +public class FooUnitTest { + private static Collection srcCollection = new HashSet<>(); + + public FooUnitTest() { + } + + @BeforeClass + public static void setUpClass() { + int i = 0; + Foo john = new Foo(i++, "John", null); + Foo mary = new Foo(i++, "Mary", null); + Foo sam = new Foo(i++, "Sam", john); + Foo alice = new Foo(i++, "Alice", john); + Foo buffy = new Foo(i++, "Buffy", sam); + srcCollection.add(john); + srcCollection.add(mary); + srcCollection.add(sam); + srcCollection.add(alice); + srcCollection.add(buffy); + + // make sure the collection isn't sorted accidentally + assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection)); + } + + /** + * Section 3. Using the ArrayList Constructor + */ + @Test + public void whenUsingConstructor_thenVerifyShallowCopy() { + ArrayList newList = new ArrayList<>(srcCollection); + verifyShallowCopy(srcCollection, newList); + } + + /** + * Section 4. Using the Streams API + */ + @Test + public void whenUsingStream_thenVerifyShallowCopy() { + ArrayList newList = srcCollection.stream().collect(toCollection(ArrayList::new)); + + verifyShallowCopy(srcCollection, newList); + } + + /** + * Section 5. Deep Copy + */ + @Test + public void whenUsingDeepCopy_thenVerifyDeepCopy() { + ArrayList newList = srcCollection.stream() + .map(foo -> foo.deepCopy()) + .collect(toCollection(ArrayList::new)); + + verifyDeepCopy(srcCollection, newList); + } + + /** + * Section 6. Controlling the List Order + */ + @Test + public void whenUsingSortedStream_thenVerifySortOrder() { + ArrayList newList = srcCollection.stream() + .sorted(Comparator.comparing(Foo::getName)) + .collect(toCollection(ArrayList::new)); + + assertTrue("ArrayList is not sorted by name", isSorted(newList)); + } + + /** + * Verify that the contents of the two collections are the same + * @param a + * @param b + */ + private void verifyShallowCopy(Collection a, Collection b) { + assertEquals("Collections have different lengths", a.size(), b.size()); + Iterator iterA = a.iterator(); + Iterator iterB = b.iterator(); + while (iterA.hasNext()) { + // use '==' to test instance identity + assertTrue("Foo instances differ!", iterA.next() == iterB.next()); + } + } + + /** + * Verify that the contents of the two collections are the same + * @param a + * @param b + */ + private void verifyDeepCopy(Collection a, Collection b) { + assertEquals("Collections have different lengths", a.size(), b.size()); + Iterator iterA = a.iterator(); + Iterator iterB = b.iterator(); + while (iterA.hasNext()) { + Foo nextA = iterA.next(); + Foo nextB = iterB.next(); + // should not be same instance + assertFalse("Foo instances are the same!", nextA == nextB); + // but should have same content + assertFalse("Foo instances have different content!", fooDiff(nextA, nextB)); + } + } + + /** + * Return true if the contents of a and b differ. Test parent recursively + * @param a + * @param b + * @return False if the two items are the same + */ + private boolean fooDiff(Foo a, Foo b) { + if (a != null && b != null) { + return a.getId() != b.getId() + || !a.getName().equals(b.getName()) + || fooDiff(a.getParent(), b.getParent()); + } + return !(a == null && b == null); + } + + /** + * @param c collection of Foo + * @return true if the collection is sorted by name + */ + private static boolean isSorted(Collection c) { + String prevName = null; + for (Foo foo : c) { + if (prevName == null || foo.getName().compareTo(prevName) > 0) { + prevName = foo.getName(); + } else { + return false; + } + } + return true; + } +} diff --git a/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java b/core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java similarity index 95% rename from core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java index 348747111f..bc1611038c 100644 --- a/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java @@ -1,13 +1,17 @@ -package com.baeldung.list; +package com.baeldung.java.list; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; public class CopyListServiceUnitTest { diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/KeyCheckUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/KeyCheckUnitTest.java new file mode 100644 index 0000000000..2c97a97690 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/map/KeyCheckUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.java.map; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Collections; +import java.util.Map; + +import org.junit.Test; + +public class KeyCheckUnitTest { + + @Test + public void whenKeyIsPresent_thenContainsKeyReturnsTrue() { + Map map = Collections.singletonMap("key", "value"); + + assertTrue(map.containsKey("key")); + assertFalse(map.containsKey("missing")); + } + + @Test + public void whenKeyHasNullValue_thenGetStillWorks() { + Map map = Collections.singletonMap("nothing", null); + + assertTrue(map.containsKey("nothing")); + assertNull(map.get("nothing")); + } +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/MapUtilUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/MapUtilUnitTest.java new file mode 100644 index 0000000000..e31385e972 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/map/MapUtilUnitTest.java @@ -0,0 +1,104 @@ +/** + * + */ +package com.baeldung.java.map; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.collections4.BidiMap; +import org.apache.commons.collections4.bidimap.DualHashBidiMap; +import org.junit.Test; + +import com.google.common.collect.HashBiMap; + +/** + * @author swpraman + * + */ +public class MapUtilUnitTest { + + + @Test + public void whenUsingImperativeWayForSingleKey_shouldReturnSingleKey() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("New Delhi", "India"); + assertEquals("New Delhi", MapUtil.getKey(capitalCountryMap, "India")); + } + + @Test + public void whenUsingImperativeWayForAllKeys_shouldReturnAllKeys() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + capitalCountryMap.put("Bloemfontein", "South Africa"); + + assertEquals(new HashSet(Arrays.asList( + new String[] {"Cape Town", "Pretoria", "Bloemfontein"})), + MapUtil.getKeys(capitalCountryMap, "South Africa")); + } + + @Test + public void whenUsingFunctionalWayForSingleKey_shouldReturnSingleKey() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + assertEquals("Berlin", MapUtil.keys(capitalCountryMap, "Germany").findFirst().get()); + } + + @Test + public void whenUsingFunctionalWayForAllKeys_shouldReturnAllKeys() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + capitalCountryMap.put("Bloemfontein", "South Africa"); + assertEquals(new HashSet(Arrays.asList( + new String[] {"Cape Town", "Pretoria", "Bloemfontein"})), + MapUtil.keys(capitalCountryMap, "South Africa").collect(Collectors.toSet())); + } + + @Test + public void whenUsingBidiMap_shouldReturnKey() { + BidiMap capitalCountryMap = new DualHashBidiMap(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + assertEquals("Berlin", capitalCountryMap.getKey("Germany")); + } + + @Test + public void whenUsingBidiMapAddDuplicateValue_shouldRemoveOldEntry() { + BidiMap capitalCountryMap = new DualHashBidiMap(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + assertEquals("Pretoria", capitalCountryMap.getKey("South Africa")); + } + + @Test + public void whenUsingBiMap_shouldReturnKey() { + HashBiMap capitalCountryMap = HashBiMap.create(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingBiMapAddDuplicateValue_shouldThrowException() { + HashBiMap capitalCountryMap = HashBiMap.create(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java index 09f0bb248c..f2b1bd9d88 100644 --- a/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java @@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedList; import java.util.List; @@ -48,4 +49,14 @@ public class RemoveFirstElementUnitTest { assertThat(linkedList, not(contains("cat"))); } + @Test + public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() { + String[] stringArray = {"foo", "bar", "baz"}; + + String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length); + + assertThat(modifiedArray.length, is(2)); + assertThat(modifiedArray[0], is("bar")); + } + } diff --git a/core-java-collections/src/test/java/com/baeldung/map/util/MapMaxUnitTest.java b/core-java-collections/src/test/java/com/baeldung/map/util/MapMaxUnitTest.java new file mode 100644 index 0000000000..883265cc8b --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/map/util/MapMaxUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.map.util; + + + +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; + +public class MapMaxUnitTest { + + Map map = null; + MapMax mapMax = null; + + + @Before + public void setupTestData() { + map = new HashMap(); + map.put(23, 12); + map.put(46, 24); + map.put(27, 38); + mapMax = new MapMax(); + } + + @Test + public void givenMap_whenIterated_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingIteration(map)); + } + + @Test + public void givenMap_whenUsingCollectionsMax_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingCollectionsMax(map)); + } + + @Test + public void givenMap_whenUsingCollectionsMaxAndLambda_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndLambda(map)); + } + + @Test + public void givenMap_whenUsingCollectionsMaxAndMethodReference_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndMethodReference(map)); + } + + @Test + public void givenMap_whenUsingStreamAndLambda_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingStreamAndLambda(map)); + } + + @Test + public void givenMap_whenUsingStreamAndMethodReference_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingStreamAndMethodReference (map)); + } + + +} diff --git a/core-java-8/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedCollectionUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedCollectionUnitTest.java new file mode 100644 index 0000000000..84feeb6eaa --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedCollectionUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class SynchronizedCollectionUnitTest { + + @Test + public void givenSynchronizedCollection_whenTwoThreadsAddElements_thenCorrectCollectionSize() throws InterruptedException { + Collection syncCollection = Collections.synchronizedCollection(new ArrayList<>()); + + Runnable listOperations = () -> { + syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)); + }; + Thread thread1 = new Thread(listOperations); + Thread thread2 = new Thread(listOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncCollection.size()).isEqualTo(12); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedListUnitTest.java new file mode 100644 index 0000000000..68fc3becd4 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedListUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class SynchronizedListUnitTest { + + @Test + public void givenSynchronizedList_whenTwoThreadsAddElements_thenCorrectListSize() throws InterruptedException { + List syncList = Collections.synchronizedList(new ArrayList<>()); + + Runnable listOperations = () -> { + syncList.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)); + }; + Thread thread1 = new Thread(listOperations); + Thread thread2 = new Thread(listOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncList.size()).isEqualTo(12); + } + + @Test + public void givenStringList_whenTwoThreadsIterateOnSynchronizedList_thenCorrectResult() throws InterruptedException { + List syncCollection = Collections.synchronizedList(Arrays.asList("a", "b", "c")); + List uppercasedCollection = new ArrayList<>(); + + Runnable listOperations = () -> { + synchronized (syncCollection) { + syncCollection.forEach((e) -> { + uppercasedCollection.add(e.toUpperCase()); + }); + } + }; + + Thread thread1 = new Thread(listOperations); + Thread thread2 = new Thread(listOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(uppercasedCollection.get(0)).isEqualTo("A"); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedMapUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedMapUnitTest.java new file mode 100644 index 0000000000..abfb866e9c --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedMapUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class SynchronizedMapUnitTest { + + @Test + public void givenSynchronizedMap_whenTwoThreadsAddElements_thenCorrectMapSize() throws InterruptedException { + Map syncMap = Collections.synchronizedMap(new HashMap<>()); + + Runnable mapOperations = () -> { + syncMap.put(1, "one"); + syncMap.put(2, "two"); + syncMap.put(3, "three"); + + }; + Thread thread1 = new Thread(mapOperations); + Thread thread2 = new Thread(mapOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncMap.size()).isEqualTo(3); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSetUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSetUnitTest.java new file mode 100644 index 0000000000..58a33b207d --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSetUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class SynchronizedSetUnitTest { + + @Test + public void givenSynchronizedSet_whenTwoThreadsAddElements_thenCorrectSetSize() throws InterruptedException { + Set syncSet = Collections.synchronizedSet(new HashSet<>()); + + Runnable setOperations = () -> {syncSet.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));}; + Thread thread1 = new Thread(setOperations); + Thread thread2 = new Thread(setOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncSet.size()).isEqualTo(6); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedMapUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedMapUnitTest.java new file mode 100644 index 0000000000..4b0ed6d8c8 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedMapUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.Collections; +import java.util.Map; +import java.util.TreeMap; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class SynchronizedSortedMapUnitTest { + + @Test + public void givenSynchronizedSorteMap_whenTwoThreadsAddElements_thenCorrectSortedMapSize() throws InterruptedException { + Map syncSortedMap = Collections.synchronizedSortedMap(new TreeMap<>()); + + Runnable sortedMapOperations = () -> { + syncSortedMap.put(1, "One"); + syncSortedMap.put(2, "Two"); + syncSortedMap.put(3, "Three"); + }; + Thread thread1 = new Thread(sortedMapOperations); + Thread thread2 = new Thread(sortedMapOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncSortedMap.size()).isEqualTo(3); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedSetUnitTest.java b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedSetUnitTest.java new file mode 100644 index 0000000000..0e26c6eb1c --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/synchronizedcollections/test/SynchronizedSortedSetUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.synchronizedcollections.test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.SortedSet; +import java.util.TreeSet; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class SynchronizedSortedSetUnitTest { + + @Test + public void givenSynchronizedSortedSet_whenTwoThreadsAddElements_thenCorrectSortedSetSize() throws InterruptedException { + SortedSet syncSortedSet = Collections.synchronizedSortedSet(new TreeSet<>()); + + Runnable sortedSetOperations = () -> {syncSortedSet.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));}; + sortedSetOperations.run(); + sortedSetOperations.run(); + Thread thread1 = new Thread(sortedSetOperations); + Thread thread2 = new Thread(sortedSetOperations); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + + assertThat(syncSortedSet.size()).isEqualTo(6); + } +} diff --git a/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java new file mode 100644 index 0000000000..09ecebe47b --- /dev/null +++ b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java @@ -0,0 +1,26 @@ +package org.baeldung.java.collections; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +class CollectionsEmpty { + + @Test + public void givenArrayList_whenAddingElement_addsNewElement() { + ArrayList mutableList = new ArrayList<>(); + mutableList.add("test"); + + Assert.assertEquals(mutableList.size(), 1); + Assert.assertEquals(mutableList.get(0), "test"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() { + List immutableList = Collections.emptyList(); + immutableList.add("test"); + } + +} diff --git a/core-java-concurrency-collections/.gitignore b/core-java-concurrency-collections/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-concurrency-collections/.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/core-java-concurrency-collections/README.md b/core-java-concurrency-collections/README.md new file mode 100644 index 0000000000..b982a91861 --- /dev/null +++ b/core-java-concurrency-collections/README.md @@ -0,0 +1,15 @@ +========= + +## Core Java Concurrency Collections Examples + +### Relevant Articles: +- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue) +- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map) +- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue) +- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception) +- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool) +- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue) +- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue) +- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue) +- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map) +- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist) diff --git a/core-java-concurrency-collections/pom.xml b/core-java-concurrency-collections/pom.xml new file mode 100644 index 0000000000..9473de8c51 --- /dev/null +++ b/core-java-concurrency-collections/pom.xml @@ -0,0 +1,74 @@ + + 4.0.0 + com.baeldung + core-java-concurrency-collections + 0.1.0-SNAPSHOT + jar + core-java-concurrency-collections + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + 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.assertj + assertj-core + ${assertj.version} + test + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + + + core-java-concurrency-collections + + + src/main/resources + true + + + + + + + 21.0 + 3.5 + 3.6.1 + 4.1 + 4.01 + + 3.6.1 + 1.7.0 + + + diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java similarity index 79% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java index 052136bfe4..842d4e630e 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java +++ b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java @@ -10,15 +10,18 @@ public class BlockingQueueUsage { int N_CONSUMERS = Runtime.getRuntime().availableProcessors(); int poisonPill = Integer.MAX_VALUE; int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS; - + int mod = N_CONSUMERS % N_PRODUCERS; BlockingQueue queue = new LinkedBlockingQueue<>(BOUND); - for (int i = 0; i < N_PRODUCERS; i++) { + for (int i = 1; i < N_PRODUCERS; i++) { new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer)).start(); } for (int j = 0; j < N_CONSUMERS; j++) { new Thread(new NumbersConsumer(queue, poisonPill)).start(); } + + new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer+mod)).start(); + } } \ No newline at end of file diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/Event.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/Event.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/Event.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/Event.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Consumer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Consumer.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Producer.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java rename to core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Producer.java diff --git a/core-java-concurrency-collections/src/main/resources/logback.xml b/core-java-concurrency-collections/src/main/resources/logback.xml new file mode 100644 index 0000000000..ec0dc2469a --- /dev/null +++ b/core-java-concurrency-collections/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java b/core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java rename to core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java diff --git a/out/production/main122/.gitignore b/core-java-concurrency-collections/src/test/resources/.gitignore similarity index 100% rename from out/production/main122/.gitignore rename to core-java-concurrency-collections/src/test/resources/.gitignore diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md index a16d885b0c..eeb9a83748 100644 --- a/core-java-concurrency/README.md +++ b/core-java-concurrency/README.md @@ -7,22 +7,12 @@ - [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) - [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) - [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future) -- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue) - [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch) -- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map) -- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue) -- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception) -- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool) - [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks) - [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal) -- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue) -- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue) -- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue) -- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map) - [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep) - [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator) - [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers) -- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist) - [Guide to the Java Phaser](http://www.baeldung.com/java-phaser) - [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized) - [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables) @@ -39,3 +29,4 @@ - [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer) - [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle) - [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) +- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield) diff --git a/core-java-concurrency/pom.xml b/core-java-concurrency/pom.xml index eb81983a2a..bd22253c2c 100644 --- a/core-java-concurrency/pom.xml +++ b/core-java-concurrency/pom.xml @@ -57,26 +57,6 @@ true - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - - - diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/yield/ThreadYield.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/yield/ThreadYield.java new file mode 100644 index 0000000000..b31a04015f --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/yield/ThreadYield.java @@ -0,0 +1,17 @@ +package com.baeldung.concurrent.yield; + +public class ThreadYield { + public static void main(String[] args) { + Runnable r = () -> { + int counter = 0; + while (counter < 2) { + System.out.println(Thread.currentThread() + .getName()); + counter++; + Thread.yield(); + } + }; + new Thread(r).start(); + new Thread(r).start(); + } +} diff --git a/core-java-concurrency/src/main/resources/logback.xml b/core-java-concurrency/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/core-java-concurrency/src/main/resources/logback.xml +++ b/core-java-concurrency/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java-io/README.md b/core-java-io/README.md index 5e5ddf42b4..58e331b6fc 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -30,3 +30,5 @@ - [Download a File From an URL in Java](http://www.baeldung.com/java-download-file) - [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink) - [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) +- [ Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist) diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml index 35bc43921c..cf3e950cb8 100644 --- a/core-java-io/pom.xml +++ b/core-java-io/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung core-java-io 0.1.0-SNAPSHOT jar @@ -166,35 +165,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - - true - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - spring-boot - org.baeldung.executable.ExecutableMavenJar - - - - org.codehaus.mojo exec-maven-plugin @@ -228,32 +198,6 @@ integration - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - - - org.codehaus.mojo exec-maven-plugin @@ -309,8 +253,6 @@ 1.7.0 - 1.8 - 1.8 3.0.0-M1 2.4.0 2.1.0.1 diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java new file mode 100644 index 0000000000..45ff486a79 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java @@ -0,0 +1,24 @@ +package com.baeldung.fileparser; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +public class BufferedReaderExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (BufferedReader br = new BufferedReader(new FileReader(filename))) { + + while (br.ready()) { + result.add(br.readLine()); + } + return result; + } + + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java new file mode 100644 index 0000000000..f9dd2a9ec5 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java @@ -0,0 +1,31 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +public class FileReaderExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (FileReader f = new FileReader(filename)) { + StringBuffer sb = new StringBuffer(); + while (f.ready()) { + char c = (char) f.read(); + if (c == '\n') { + result.add(sb.toString()); + sb = new StringBuffer(); + } else { + sb.append(c); + } + } + if (sb.length() > 0) { + result.add(sb.toString()); + } + } + + return result; + } +} diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java new file mode 100644 index 0000000000..8e74f7d386 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java @@ -0,0 +1,18 @@ +package com.baeldung.fileparser; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +public class FilesReadLinesExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + List result = Files.readAllLines(Paths.get(filename)); + + return (ArrayList) result; + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java new file mode 100644 index 0000000000..25d17af4ea --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java @@ -0,0 +1,24 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Scanner; + +public class ScannerIntExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (Scanner s = new Scanner(new FileReader(filename))) { + + while (s.hasNext()) { + result.add(s.nextInt()); + } + return result; + } + + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java new file mode 100644 index 0000000000..ec213c9490 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java @@ -0,0 +1,24 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Scanner; + +public class ScannerStringExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (Scanner s = new Scanner(new FileReader(filename))) { + + while (s.hasNext()) { + result.add(s.nextLine()); + } + return result; + } + + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/stream/OutputStreamExamples.java b/core-java-io/src/main/java/com/baeldung/stream/OutputStreamExamples.java new file mode 100644 index 0000000000..c7168c5b26 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/stream/OutputStreamExamples.java @@ -0,0 +1,48 @@ +package com.baeldung.stream; + +import java.io.BufferedOutputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; + +public class OutputStreamExamples { + + public void fileOutputStreamByteSequence(String file, String data) throws IOException { + byte[] bytes = data.getBytes(); + try (OutputStream out = new FileOutputStream(file)) { + out.write(bytes); + } + } + + public void fileOutputStreamByteSubSequence(String file, String data) throws IOException { + byte[] bytes = data.getBytes(); + try (OutputStream out = new FileOutputStream(file)) { + out.write(bytes, 6, 5); + } + } + + public void fileOutputStreamByteSingle(String file, String data) throws IOException { + byte[] bytes = data.getBytes(); + try (OutputStream out = new FileOutputStream(file)) { + out.write(bytes[6]); + } + } + + public void bufferedOutputStream(String file, String... data) throws IOException { + try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { + for (String s : data) { + out.write(s.getBytes()); + out.write(" ".getBytes()); + } + } + } + + public void outputStreamWriter(String file, String data) throws IOException { + try (OutputStream out = new FileOutputStream(file); Writer writer = new OutputStreamWriter(out, "UTF-8")) { + writer.write(data); + } + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/zip/ZipDirectory.java b/core-java-io/src/main/java/com/baeldung/zip/ZipDirectory.java index 7da71a093d..42147b07db 100644 --- a/core-java-io/src/main/java/com/baeldung/zip/ZipDirectory.java +++ b/core-java-io/src/main/java/com/baeldung/zip/ZipDirectory.java @@ -24,6 +24,13 @@ public class ZipDirectory { return; } if (fileToZip.isDirectory()) { + if (fileName.endsWith("/")) { + zipOut.putNextEntry(new ZipEntry(fileName)); + zipOut.closeEntry(); + } else { + zipOut.putNextEntry(new ZipEntry(fileName + "/")); + zipOut.closeEntry(); + } final File[] children = fileToZip.listFiles(); for (final File childFile : children) { zipFile(childFile, fileName + "/" + childFile.getName(), zipOut); diff --git a/core-java-io/src/main/resources/logback.xml b/core-java-io/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/core-java-io/src/main/resources/logback.xml +++ b/core-java-io/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java-io/src/main/resources/zipTest/test1.txt b/core-java-io/src/main/resources/zipTest/test1.txt new file mode 100644 index 0000000000..e88ded96ab --- /dev/null +++ b/core-java-io/src/main/resources/zipTest/test1.txt @@ -0,0 +1 @@ +Test1 \ No newline at end of file diff --git a/core-java-io/src/main/resources/zipTest/test2.txt b/core-java-io/src/main/resources/zipTest/test2.txt new file mode 100644 index 0000000000..da8f209890 --- /dev/null +++ b/core-java-io/src/main/resources/zipTest/test2.txt @@ -0,0 +1 @@ +Test2 \ No newline at end of file diff --git a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java index 7968967679..e781489808 100644 --- a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java +++ b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java @@ -1,6 +1,7 @@ package com.baeldung.file; import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.Test; @@ -17,6 +18,7 @@ import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; @@ -49,7 +51,7 @@ public class FileOperationsManualTest { @Test public void givenFileName_whenUsingJarFile_thenFileData() throws IOException { - String expectedData = "BSD License"; + String expectedData = "MIT License"; Class clazz = Matchers.class; InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt"); @@ -78,7 +80,7 @@ public class FileOperationsManualTest { ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("fileTest.txt").getFile()); - String data = FileUtils.readFileToString(file); + String data = FileUtils.readFileToString(file, "UTF-8"); assertEquals(expectedData, data.trim()); } @@ -101,12 +103,11 @@ public class FileOperationsManualTest { Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); - StringBuilder data = new StringBuilder(); Stream lines = Files.lines(path); - lines.forEach(line -> data.append(line).append("\n")); + String data = lines.collect(Collectors.joining("\n")); lines.close(); - assertEquals(expectedData, data.toString().trim()); + assertEquals(expectedData, data.trim()); } private String readFromInputStream(InputStream inputStream) throws IOException { @@ -120,4 +121,14 @@ public class FileOperationsManualTest { return resultStringBuilder.toString(); } + + @Test + public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException { + String expectedData = "This is a content of the file"; + + FileInputStream fis = new FileInputStream("src/test/resources/fileToRead.txt"); + String data = IOUtils.toString(fis, "UTF-8"); + + assertEquals(expectedData, data.trim()); + } } \ No newline at end of file diff --git a/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java index 47a7973b34..f9a2ce972d 100644 --- a/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java +++ b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java @@ -18,7 +18,7 @@ public class FilenameFilterManualTest { @BeforeClass public static void setupClass() { directory = new File(FilenameFilterManualTest.class.getClassLoader() - .getResource("testFolder") + .getResource("fileNameFilterManualTestFolder") .getFile()); } diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java new file mode 100644 index 0000000000..78f900d796 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class BufferedReaderUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java new file mode 100644 index 0000000000..a38e58d348 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class FileReaderUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java new file mode 100644 index 0000000000..c0b742fd47 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class FilesReadAllLinesUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java new file mode 100644 index 0000000000..0a398ba7c6 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class ScannerIntUnitTest { + + protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException { + List numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME); + assertTrue("File does not has 2 lines", numbers.size() == 2); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java new file mode 100644 index 0000000000..8f9b0a56c0 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class ScannerStringUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesUnitTest.java b/core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesUnitTest.java new file mode 100644 index 0000000000..aa949259a0 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.stream; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; + +import org.junit.Before; +import org.junit.Test; + +public class OutputStreamExamplesUnitTest { + + StringBuilder filePath = new StringBuilder(); + + @Before + public void init() { + filePath.append("src"); + filePath.append(File.separator); + filePath.append("test"); + filePath.append(File.separator); + filePath.append("resources"); + filePath.append(File.separator); + filePath.append("output_file.txt"); + } + + @Test + public void givenOutputStream_whenWriteSingleByteCalled_thenOutputCreated() throws IOException { + + final File file = new File(filePath.toString()); + OutputStreamExamples examples = new OutputStreamExamples(); + examples.fileOutputStreamByteSingle(filePath.toString(), "Hello World!"); + assertTrue(file.exists()); + file.delete(); + } + + @Test + public void givenOutputStream_whenWriteByteSequenceCalled_thenOutputCreated() throws IOException { + + final File file = new File(filePath.toString()); + OutputStreamExamples examples = new OutputStreamExamples(); + examples.fileOutputStreamByteSequence(filePath.toString(), "Hello World!"); + assertTrue(file.exists()); + file.delete(); + } + + @Test + public void givenOutputStream_whenWriteByteSubSequenceCalled_thenOutputCreated() throws IOException { + + final File file = new File(filePath.toString()); + OutputStreamExamples examples = new OutputStreamExamples(); + examples.fileOutputStreamByteSubSequence(filePath.toString(), "Hello World!"); + assertTrue(file.exists()); + file.delete(); + } + + @Test + public void givenBufferedOutputStream_whenCalled_thenOutputCreated() throws IOException { + + final File file = new File(filePath.toString()); + OutputStreamExamples examples = new OutputStreamExamples(); + examples.bufferedOutputStream(filePath.toString(), "Hello", "World!"); + assertTrue(file.exists()); + file.delete(); + } + + @Test + public void givenOutputStreamWriter_whenCalled_thenOutputCreated() throws IOException { + + final File file = new File(filePath.toString()); + OutputStreamExamples examples = new OutputStreamExamples(); + examples.outputStreamWriter(filePath.toString(), "Hello World!"); + assertTrue(file.exists()); + file.delete(); + } + +} diff --git a/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleUnitTest.java b/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java similarity index 96% rename from core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleUnitTest.java rename to core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java index 803d8881b4..caa7049475 100644 --- a/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleUnitTest.java +++ b/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java @@ -9,7 +9,7 @@ import java.nio.file.Paths; import org.junit.Test; -public class SymLinkExampleUnitTest { +public class SymLinkExampleManualTest { @Test public void whenUsingFiles_thenCreateSymbolicLink() throws IOException { diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java index 08a4c673cd..6604d75ed1 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java @@ -1,10 +1,12 @@ package org.baeldung.java.io; import java.io.ByteArrayInputStream; +import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.SequenceInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -74,6 +76,28 @@ public class JavaXToInputStreamUnitTest { IOUtils.closeQuietly(targetStream); } + @Test + public final void givenUsingPlainJava_whenConvertingFileToDataInputStream_thenCorrect() throws IOException { + final File initialFile = new File("src/test/resources/sample.txt"); + final InputStream targetStream = new DataInputStream(new FileInputStream(initialFile)); + + IOUtils.closeQuietly(targetStream); + } + + @Test + public final void givenUsingPlainJava_whenConvertingFileToSequenceInputStream_thenCorrect() throws IOException { + final File initialFile = new File("src/test/resources/sample.txt"); + final File anotherFile = new File("src/test/resources/anothersample.txt"); + final InputStream targetStream = new FileInputStream(initialFile); + final InputStream anotherTargetStream = new FileInputStream(anotherFile); + + InputStream sequenceTargetStream = new SequenceInputStream(targetStream, anotherTargetStream); + + IOUtils.closeQuietly(targetStream); + IOUtils.closeQuietly(anotherTargetStream); + IOUtils.closeQuietly(sequenceTargetStream); + } + @Test public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException { final File initialFile = new File("src/test/resources/sample.txt"); diff --git a/core-java-io/src/test/resources/anothersample.txt b/core-java-io/src/test/resources/anothersample.txt new file mode 100644 index 0000000000..f06f18ce02 --- /dev/null +++ b/core-java-io/src/test/resources/anothersample.txt @@ -0,0 +1 @@ +...Continues \ No newline at end of file diff --git a/core-java-io/src/test/resources/testFolder/people.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json similarity index 100% rename from core-java-io/src/test/resources/testFolder/people.json rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json diff --git a/core-java-io/src/test/resources/testFolder/students.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json similarity index 100% rename from core-java-io/src/test/resources/testFolder/students.json rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json diff --git a/core-java-io/src/test/resources/testFolder/teachers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml similarity index 100% rename from core-java-io/src/test/resources/testFolder/teachers.xml rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml diff --git a/core-java-io/src/test/resources/testFolder/workers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml similarity index 100% rename from core-java-io/src/test/resources/testFolder/workers.xml rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml diff --git a/core-java-io/src/test/resources/fileTest.txt b/core-java-io/src/test/resources/fileTest.txt new file mode 100644 index 0000000000..ce4bea208b --- /dev/null +++ b/core-java-io/src/test/resources/fileTest.txt @@ -0,0 +1 @@ +Hello World from fileTest.txt!!! \ No newline at end of file diff --git a/core-java-io/src/test/resources/sampleNumberFile.txt b/core-java-io/src/test/resources/sampleNumberFile.txt new file mode 100644 index 0000000000..7787faa3c1 --- /dev/null +++ b/core-java-io/src/test/resources/sampleNumberFile.txt @@ -0,0 +1,2 @@ +111 +222 \ No newline at end of file diff --git a/core-java-io/src/test/resources/sampleTextFile.txt b/core-java-io/src/test/resources/sampleTextFile.txt new file mode 100644 index 0000000000..75cb50aafa --- /dev/null +++ b/core-java-io/src/test/resources/sampleTextFile.txt @@ -0,0 +1,2 @@ +Hello +World \ No newline at end of file diff --git a/core-java-persistence/README.md b/core-java-persistence/README.md new file mode 100644 index 0000000000..ca0ce81eef --- /dev/null +++ b/core-java-persistence/README.md @@ -0,0 +1,9 @@ +========= + +## Core Java Persistence Examples + +### Relevant Articles: +- [Introduction to JDBC](http://www.baeldung.com/java-jdbc) +- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing) +- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset) +- [A Simple Guide to Connection Pooling in Java](https://www.baeldung.com/java-connection-pooling) diff --git a/core-java-persistence/pom.xml b/core-java-persistence/pom.xml index 0cb142c7b8..7279fd763b 100644 --- a/core-java-persistence/pom.xml +++ b/core-java-persistence/pom.xml @@ -39,6 +39,16 @@ c3p0 ${c3p0.version} + + org.springframework + spring-web + ${springframework.spring-web.version} + + + org.springframework.boot + spring-boot-starter + ${springframework.boot.spring-boot-starter.version} + core-java-persistence @@ -55,5 +65,7 @@ 2.4.0 3.2.0 0.9.5.2 + 1.5.8.RELEASE + 4.3.4.RELEASE \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/jdbc/BatchProcessing.java b/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbc/BatchProcessing.java rename to core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java diff --git a/core-java/src/main/java/com/baeldung/jdbc/Employee.java b/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbc/Employee.java rename to core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/FilterExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/FilterExample.java diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java diff --git a/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java rename to core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java diff --git a/core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java rename to core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java diff --git a/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java rename to core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml index f489f3b030..57d5e9da5b 100644 --- a/core-java-sun/pom.xml +++ b/core-java-sun/pom.xml @@ -166,22 +166,6 @@ - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - org.apache.maven.plugins maven-jar-plugin @@ -303,7 +287,7 @@ 1.7.0 - 2.19.1 + 2.21.0 1.8.0 3.0.2 diff --git a/core-java-sun/src/main/resources/logback.xml b/core-java-sun/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/core-java-sun/src/main/resources/logback.xml +++ b/core-java-sun/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java/README.md b/core-java/README.md index f05b2625e8..9e38dfc47d 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -3,18 +3,14 @@ ## Core Java Cookbooks and Examples ### Relevant Articles: -- [Java – Generate Random String](http://www.baeldung.com/java-random-string) - [Java Timer](http://www.baeldung.com/java-timer-and-timertask) - [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java) - [MD5 Hashing in Java](http://www.baeldung.com/java-md5) - [Guide to Java Reflection](http://www.baeldung.com/java-reflection) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) -- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) -- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) - [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) - [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) - [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) -- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions) - [Introduction to Java Generics](http://www.baeldung.com/java-generics) - [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode) - [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java) @@ -29,7 +25,6 @@ - [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) - [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm) -- [Spring Security – Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers) - [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions) - [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda) - [Introduction to Nashorn](http://www.baeldung.com/java-nashorn) @@ -37,13 +32,10 @@ - [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng) - [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) -- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum) -- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer) - [JVM Log Forging](http://www.baeldung.com/jvm-log-forging) - [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe) - [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) - [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection) -- [Guide to UUID in JAVA](http://www.baeldung.com/guide-to-uuid-in-java) - [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend) - [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration) - [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability) @@ -53,44 +45,33 @@ - [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) - [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) - [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy) -- [Introduction to JDBC](http://www.baeldung.com/java-jdbc) -- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) - [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string) -- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) - [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization) - [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error) -- [Split a String in Java](http://www.baeldung.com/java-split-string) - [Introduction to Java Serialization](http://www.baeldung.com/java-serialization) -- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) - [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror) - [Guide to UUID in Java](http://www.baeldung.com/java-uuid) - [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char) - [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode) - [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri) - [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast) -- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) - [Period and Duration in Java](http://www.baeldung.com/java-period-duration) - [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator) - [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws) - [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded) -- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) - [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) - [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static) - [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array) -- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) - [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable) - [Quick Guide to Java Stack](http://www.baeldung.com/java-stack) - [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break) - [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) -- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing) - [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value) - [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array) - [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class) - [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) - [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree) - [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random) -- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions) -- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset) - [Nested Classes in Java](http://www.baeldung.com/java-nested-classes) - [A Guide to Java Loops](http://www.baeldung.com/java-loops) - [Varargs in Java](http://www.baeldung.com/java-varargs) @@ -105,16 +86,12 @@ - [The Trie Data Structure in Java](http://www.baeldung.com/trie-java) - [Introduction to Javadoc](http://www.baeldung.com/javadoc) - [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy) -- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) -- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) - [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance) - [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) - [Object Type Casting in Java](http://www.baeldung.com/java-type-casting) - [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat) - [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os) - [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java) -- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) -- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) - [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition) - [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) - [The "final" Keyword in Java](http://www.baeldung.com/java-final) @@ -128,7 +105,6 @@ - [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average) - [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception) - [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure) -- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) - [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split) - [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) - [Sending Emails with Java](http://www.baeldung.com/java-email) @@ -139,11 +115,9 @@ - [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) - [Using Java Assertions](http://www.baeldung.com/java-assert) - [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference) -- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) - [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding) - [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers) - [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) -- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords) - [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns) - [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) - [Singletons in Java](http://www.baeldung.com/java-singleton) @@ -155,15 +129,11 @@ - [Guide to the this Java Keyword](http://www.baeldung.com/java-this) - [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays) - [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) -- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day) -- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time) -- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case) - [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension) - [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object) - [Console I/O in Java](http://www.baeldung.com/java-console-input-output) - [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays) - [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception) -- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar) - [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) - [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream) - [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object) @@ -171,3 +141,18 @@ - [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation) - [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type) - [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) +- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) +- [Differences Between Final, Finally and Finalize in Java](https://www.baeldung.com/java-final-finally-finalize) +- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding) +- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line) +- [Difference Between Throw and Throws in Java](https://www.baeldung.com/java-throw-throws) +- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist) +- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) +- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) +- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic) +- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string) +- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture) +- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts) +- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) +- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) +- [Java Switch Statement](https://www.baeldung.com/java-switch) diff --git a/core-java/pom.xml b/core-java/pom.xml index b83cb478d4..477a01375d 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -127,11 +127,6 @@ spring-web ${springframework.spring-web.version} - - org.springframework.boot - spring-boot-starter - ${springframework.boot.spring-boot-starter.version} - com.h2database h2 @@ -142,11 +137,6 @@ mail ${javax.mail.version} - - com.ibm.icu - icu4j - ${icu4j.version} - org.apache.tika @@ -530,9 +520,8 @@ 3.10.0 - 2.19.1 + 2.21.0 4.3.4.RELEASE - 1.5.8.RELEASE 1.1 1.4.197 diff --git a/core-java/src/main/java/com/baeldung/binding/Animal.java b/core-java/src/main/java/com/baeldung/binding/Animal.java new file mode 100644 index 0000000000..12eaa2a7a3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/binding/Animal.java @@ -0,0 +1,23 @@ +package com.baeldung.binding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by madhumita.g on 25-07-2018. + */ +public class Animal { + + final static Logger logger = LoggerFactory.getLogger(Animal.class); + + public void makeNoise() { + logger.info("generic animal noise"); + } + + public void makeNoise(Integer repetitions) { + while(repetitions != 0) { + logger.info("generic animal noise countdown " + repetitions); + repetitions -= 1; + } + } +} diff --git a/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java b/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java new file mode 100644 index 0000000000..1bd36123e3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java @@ -0,0 +1,43 @@ +package com.baeldung.binding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by madhumita.g on 25-07-2018. + */ +public class AnimalActivity { + + final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class); + + + public static void sleep(Animal animal) { + logger.info("Animal is sleeping"); + } + + public static void sleep(Cat cat) { + logger.info("Cat is sleeping"); + } + + public static void main(String[] args) { + + Animal animal = new Animal(); + + //calling methods of animal object + animal.makeNoise(); + + animal.makeNoise(3); + + + //assigning a dog object to reference of type Animal + Animal catAnimal = new Cat(); + + catAnimal.makeNoise(); + + // calling static function + AnimalActivity.sleep(catAnimal); + + return; + + } +} diff --git a/core-java/src/main/java/com/baeldung/binding/Cat.java b/core-java/src/main/java/com/baeldung/binding/Cat.java new file mode 100644 index 0000000000..bbe740e412 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/binding/Cat.java @@ -0,0 +1,18 @@ +package com.baeldung.binding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by madhumita.g on 25-07-2018. + */ +public class Cat extends Animal { + + final static Logger logger = LoggerFactory.getLogger(Cat.class); + + public void makeNoise() { + + logger.info("meow"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java b/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java new file mode 100644 index 0000000000..26e5bf0c6b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java @@ -0,0 +1,21 @@ +package com.baeldung.classcastexception; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ClassCastException { + + public static void main(String[] args) { + + String p1 = new String("John"); + String p2 = new String("Snow"); + String[] strArray = new String[] { p1, p2 }; + ArrayList strList = (ArrayList) Arrays.asList(strArray); + // To fix the ClassCastException at above line, modify the code as: + // List strList = Arrays.asList(strArray); + System.out.println("String list: " + strList); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java b/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java index c44e863776..532adce1ab 100644 --- a/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java +++ b/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java @@ -1,11 +1,14 @@ package com.baeldung.classloader; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; public class CustomClassLoader extends ClassLoader { - - public Class getClass(String name) throws ClassNotFoundException { + @Override + public Class findClass(String name) throws ClassNotFoundException { byte[] b = loadClassFromFile(name); return defineClass(name, b, 0, b.length); } diff --git a/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java new file mode 100644 index 0000000000..d19772072f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.constructorsstaticfactorymethods.application; + +import com.baeldung.constructorsstaticfactorymethods.entities.User; + +public class Application { + + public static void main(String[] args) { + User user1 = User.createWithDefaultCountry("John", "john@domain.com"); + User user2 = User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina"); + User user3 = User.getSingletonInstance("John", "john@domain.com", "Argentina"); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java new file mode 100644 index 0000000000..4036b622c6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java @@ -0,0 +1,63 @@ +package com.baeldung.constructorsstaticfactorymethods.entities; + +import java.time.LocalTime; +import java.util.logging.ConsoleHandler; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.logging.SimpleFormatter; + +public class User { + + private static volatile User instance = null; + private static final Logger LOGGER = Logger.getLogger(User.class.getName()); + private final String name; + private final String email; + private final String country; + + public static User createWithDefaultCountry(String name, String email) { + return new User(name, email, "Argentina"); + } + + public static User createWithLoggedInstantiationTime(String name, String email, String country) { + setLoggerProperties(); + LOGGER.log(Level.INFO, "Creating User instance at : {0}", LocalTime.now()); + return new User(name, email, country); + } + + public static User getSingletonInstance(String name, String email, String country) { + if (instance == null) { + synchronized (User.class) { + if (instance == null) { + instance = new User(name, email, country); + } + } + } + return instance; + + } + + private User(String name, String email, String country) { + this.name = name; + this.email = email; + this.country = country; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + public String getCountry() { + return country; + } + + private static void setLoggerProperties() { + ConsoleHandler handler = new ConsoleHandler(); + handler.setLevel(Level.INFO); + handler.setFormatter(new SimpleFormatter()); + LOGGER.addHandler(handler); + } +} diff --git a/core-java/src/main/java/com/baeldung/doubles/SplitFloatingPointNumbers.java b/core-java/src/main/java/com/baeldung/doubles/SplitFloatingPointNumbers.java new file mode 100644 index 0000000000..a28ac3d5a1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/doubles/SplitFloatingPointNumbers.java @@ -0,0 +1,40 @@ +package com.baeldung.doubles; + +import java.math.BigDecimal; + +public class SplitFloatingPointNumbers { + + public static void main(String[] args) { + + double doubleNumber = 24.04; + splitUsingFloatingTypes(doubleNumber); + splitUsingString(doubleNumber); + splitUsingBigDecimal(doubleNumber); + } + + private static void splitUsingFloatingTypes(double doubleNumber) { + System.out.println("Using Floating Point Arithmetics:"); + int intPart = (int) doubleNumber; + System.out.println("Double Number: "+doubleNumber); + System.out.println("Integer Part: "+ intPart); + System.out.println("Decimal Part: "+ (doubleNumber - intPart)); + } + + private static void splitUsingString(double doubleNumber) { + System.out.println("Using String Operations:"); + String doubleAsString = String.valueOf(doubleNumber); + int indexOfDecimal = doubleAsString.indexOf("."); + System.out.println("Double Number: "+doubleNumber); + System.out.println("Integer Part: "+ doubleAsString.substring(0, indexOfDecimal)); + System.out.println("Decimal Part: "+ doubleAsString.substring(indexOfDecimal)); + } + + private static void splitUsingBigDecimal(double doubleNumber) { + System.out.println("Using BigDecimal Operations:"); + BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber)); + int intValue = bigDecimal.intValue(); + System.out.println("Double Number: "+bigDecimal.toPlainString()); + System.out.println("Integer Part: "+intValue); + System.out.println("Decimal Part: "+bigDecimal.subtract(new BigDecimal(intValue)).toPlainString()); + } +} diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java index eb8b733f82..9690648386 100644 --- a/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java +++ b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java @@ -163,7 +163,7 @@ public class Exceptions { } } - public void throwAsGotoAntiPattern() { + public void throwAsGotoAntiPattern() throws MyException { try { // bunch of code throw new MyException(); diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java index c46c3de65a..524f176e6b 100644 --- a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java +++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java @@ -25,7 +25,7 @@ public class User { if (this.getClass() != o.getClass()) return false; User user = (User) o; - return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); + return id == user.id && (name.equals(user.name) && email.equals(user.email)); } @Override @@ -38,4 +38,5 @@ public class User { return hash; } // getters and setters here + } diff --git a/core-java/src/main/java/com/baeldung/heapdump/HeapDump.java b/core-java/src/main/java/com/baeldung/heapdump/HeapDump.java new file mode 100644 index 0000000000..8cce20de8d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/heapdump/HeapDump.java @@ -0,0 +1,25 @@ +package com.baeldung.heapdump; + +import com.sun.management.HotSpotDiagnosticMXBean; + +import javax.management.MBeanServer; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.nio.file.Paths; + +public class HeapDump { + + public static void dumpHeap(String filePath, boolean live) throws IOException { + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy( + server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class); + mxBean.dumpHeap(filePath, live); + } + + public static void main(String[] args) throws IOException { + String file = Paths.get("dump.hprof").toFile().getPath(); + + dumpHeap(file, true); + } +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java b/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java new file mode 100644 index 0000000000..af0449c0da --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java @@ -0,0 +1,18 @@ +package com.baeldung.keywords.finalize; + +public class FinalizeObject { + + @Override + protected void finalize() throws Throwable { + System.out.println("Execute finalize method"); + super.finalize(); + } + + public static void main(String[] args) throws Exception { + FinalizeObject object = new FinalizeObject(); + object = null; + System.gc(); + Thread.sleep(1000); + } + +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java new file mode 100644 index 0000000000..8615c78652 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java @@ -0,0 +1,15 @@ +package com.baeldung.keywords.finalkeyword; + +public final class Child extends Parent { + + @Override + void method1(int arg1, final int arg2) { + // OK + } + +/* @Override + void method2() { + // Compilation error + }*/ + +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java new file mode 100644 index 0000000000..1530c5037f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java @@ -0,0 +1,5 @@ +package com.baeldung.keywords.finalkeyword; + +/*public class GrandChild extends Child { + // Compilation error +}*/ diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java new file mode 100644 index 0000000000..5cd2996e7a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java @@ -0,0 +1,23 @@ +package com.baeldung.keywords.finalkeyword; + +public class Parent { + + int field1 = 1; + final int field2 = 2; + + Parent() { + field1 = 2; // OK +// field2 = 3; // Compilation error + } + + void method1(int arg1, final int arg2) { + arg1 = 2; // OK +// arg2 = 3; // Compilation error + } + + final void method2() { + final int localVar = 2; // OK +// localVar = 3; // Compilation error + } + +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java b/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java new file mode 100644 index 0000000000..3c0aee3196 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java @@ -0,0 +1,29 @@ +package com.baeldung.keywords.finallykeyword; + +public class FinallyExample { + + public static void main(String args[]) throws Exception { + try { + System.out.println("Execute try block"); + throw new Exception(); + } catch (Exception e) { + System.out.println("Execute catch block"); + } finally { + System.out.println("Execute finally block"); + } + + try { + System.out.println("Execute try block"); + } finally { + System.out.println("Execute finally block"); + } + + try { + System.out.println("Execute try block"); + throw new Exception(); + } finally { + System.out.println("Execute finally block"); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java new file mode 100755 index 0000000000..e16d1ae6da --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java @@ -0,0 +1,9 @@ +package com.baeldung.memoryleaks.equalshashcode; + +public class Person { + public String name; + + public Person(String name) { + this.name = name; + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java new file mode 100755 index 0000000000..3af70dd1eb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java @@ -0,0 +1,25 @@ +package com.baeldung.memoryleaks.equalshashcode; + +public class PersonOptimized { + public String name; + + public PersonOptimized(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof PersonOptimized)) { + return false; + } + PersonOptimized person = (PersonOptimized) o; + return person.name.equals(name); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + name.hashCode(); + return result; + }} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java new file mode 100755 index 0000000000..ce77d883f6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java @@ -0,0 +1,32 @@ +package com.baeldung.memoryleaks.finalize; + +import java.nio.charset.Charset; +import java.util.Random; + +public class BulkyObject { + private String data[]; + + public BulkyObject() { + data = new String[1000000]; + + for(int i=0; i<1000000; i++) { + data[i] = getRandomString(); + } + } + + private String getRandomString() { + byte[] array = new byte[1000]; + new Random().nextBytes(array); + return new String(array, Charset.forName("UTF-8")); + } + + @Override + public void finalize() { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Finalizer called"); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java new file mode 100644 index 0000000000..dc1302432e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java @@ -0,0 +1,22 @@ +package com.baeldung.memoryleaks.finalize; + +import java.nio.charset.Charset; +import java.util.Random; + +public class BulkyObjectOptimized { + private String data[]; + + public BulkyObjectOptimized() { + data = new String[1000000]; + + for(int i=0; i<1000000; i++) { + data[i] = getRandomString(); + } + } + + private String getRandomString() { + byte[] array = new byte[1000]; + new Random().nextBytes(array); + return new String(array, Charset.forName("UTF-8")); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java new file mode 100755 index 0000000000..bbd5310182 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java @@ -0,0 +1,22 @@ +package com.baeldung.memoryleaks.innerclass; + +import java.nio.charset.Charset; +import java.util.Random; + +public class BulkyObject { + private String data[]; + + public BulkyObject() { + data = new String[1000000]; + + for(int i=0; i<1000000; i++) { + data[i] = getRandomString(); + } + } + + private String getRandomString() { + byte[] array = new byte[1000]; + new Random().nextBytes(array); + return new String(array, Charset.forName("UTF-8")); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java new file mode 100755 index 0000000000..06f928bc4a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java @@ -0,0 +1,17 @@ +package com.baeldung.memoryleaks.innerclass; + +public class InnerClassDriver { + public static InnerClassWrapper.SimpleInnerClass getSimpleInnerClassObj() { + return new InnerClassWrapper().new SimpleInnerClass(); + } + + public static void main2(String[] args) { + InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = getSimpleInnerClassObj(); + System.out.println("Debug point"); + } + + public static void main(String[] args) { + StaticNestedClassWrapper.StaticNestedClass simpleInnerClassObj = new StaticNestedClassWrapper.StaticNestedClass(); + System.out.println("Debug point"); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java new file mode 100755 index 0000000000..25fecf9bb3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java @@ -0,0 +1,10 @@ +package com.baeldung.memoryleaks.innerclass; + + +public class InnerClassWrapper { + private BulkyObject bulkyObject = new BulkyObject(); + + public class SimpleInnerClass { + + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java new file mode 100755 index 0000000000..d1729d78a3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java @@ -0,0 +1,10 @@ +package com.baeldung.memoryleaks.innerclass; + + +public class StaticNestedClassWrapper { + private BulkyObject bulkyObject = new BulkyObject(); + + public static class StaticNestedClass { + + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java new file mode 100644 index 0000000000..cbba8f849d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java @@ -0,0 +1,17 @@ +package com.baeldung.memoryleaks.internedstrings; + +public class InternedString { + private static final String FILEPATH = "C:\\bigstring.txt"; + + public void readString() { + String s1 = ReadStringFromFileUtil.read(FILEPATH).intern(); + String s2 = ReadStringFromFileUtil.read(FILEPATH).intern(); + + if (s1 == s2) { + System.out.println("Both the strings objects are same"); + } + else { + System.out.println("Both the strings objects are different"); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java new file mode 100644 index 0000000000..2b7d72accc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java @@ -0,0 +1,34 @@ +package com.baeldung.memoryleaks.internedstrings; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class ReadStringFromFileUtil { + + public static String read(String fileName) { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(fileName)); + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + return sb.toString(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } + +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java new file mode 100644 index 0000000000..e48e448d18 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java @@ -0,0 +1,17 @@ +package com.baeldung.memoryleaks.internedstrings; + +public class StringObject { + private static final String FILEPATH = "C:\\bigstring.txt"; + + public void readString() { + String s1 = ReadStringFromFileUtil.read(FILEPATH); + String s2 = ReadStringFromFileUtil.read(FILEPATH); + + if (s1 == s2) { + System.out.println("Both the strings objects are same"); + } + else { + System.out.println("Both the strings objects are different"); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java new file mode 100644 index 0000000000..f2b220e76d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java @@ -0,0 +1,21 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +public class NonStaticFieldsDemo { + public List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + public static void main(String[] args) { + System.out.println("Debug Point 1"); + new NonStaticFieldsDemo().populateList(); + System.out.println("Debug Point 3"); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java new file mode 100644 index 0000000000..17cebc2843 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java @@ -0,0 +1,21 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +public class StaticFieldsDemo { + public static List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + public static void main(String[] args) { + System.out.println("Debug Point 1"); + new StaticFieldsDemo().populateList(); + System.out.println("Debug Point 3"); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java b/core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java new file mode 100644 index 0000000000..217f1e06de --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java @@ -0,0 +1,8 @@ +package com.baeldung.nth.root.calculator; + +public class NthRootCalculator +{ + public Double calculate(Double base, Double n) { + return Math.pow(Math.E, Math.log(base)/n); + } +} diff --git a/core-java/src/main/java/com/baeldung/nth/root/main/Main.java b/core-java/src/main/java/com/baeldung/nth/root/main/Main.java new file mode 100644 index 0000000000..3fcd36812f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nth/root/main/Main.java @@ -0,0 +1,13 @@ +package com.baeldung.nth.root.main; + +import com.baeldung.nth.root.calculator.NthRootCalculator; + +public class Main { + public static void main(String[] args) { + NthRootCalculator calculator = new NthRootCalculator(); + Double base = Double.parseDouble(args[0]); + Double n = Double.parseDouble(args[1]); + Double result = calculator.calculate(base, n); + System.out.println("The " + n + " root of " + base + " equals to " + result + "."); + } +} diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java new file mode 100644 index 0000000000..e2259e4249 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java @@ -0,0 +1,149 @@ +package com.baeldung.passwordhashing; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; + +/** + * Hash passwords for storage, and test passwords against password tokens. + * + * Instances of this class can be used concurrently by multiple threads. + * + * @author erickson + * @see StackOverflow + */ +public final class PBKDF2Hasher +{ + + /** + * Each token produced by this class uses this identifier as a prefix. + */ + public static final String ID = "$31$"; + + /** + * The minimum recommended cost, used by default + */ + public static final int DEFAULT_COST = 16; + + private static final String ALGORITHM = "PBKDF2WithHmacSHA1"; + + private static final int SIZE = 128; + + private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})"); + + private final SecureRandom random; + + private final int cost; + + public PBKDF2Hasher() + { + this(DEFAULT_COST); + } + + /** + * Create a password manager with a specified cost + * + * @param cost the exponential computational cost of hashing a password, 0 to 30 + */ + public PBKDF2Hasher(int cost) + { + iterations(cost); /* Validate cost */ + this.cost = cost; + this.random = new SecureRandom(); + } + + private static int iterations(int cost) + { + if ((cost < 0) || (cost > 30)) + throw new IllegalArgumentException("cost: " + cost); + return 1 << cost; + } + + /** + * Hash a password for storage. + * + * @return a secure authentication token to be stored for later authentication + */ + public String hash(char[] password) + { + byte[] salt = new byte[SIZE / 8]; + random.nextBytes(salt); + byte[] dk = pbkdf2(password, salt, 1 << cost); + byte[] hash = new byte[salt.length + dk.length]; + System.arraycopy(salt, 0, hash, 0, salt.length); + System.arraycopy(dk, 0, hash, salt.length, dk.length); + Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding(); + return ID + cost + '$' + enc.encodeToString(hash); + } + + /** + * Authenticate with a password and a stored password token. + * + * @return true if the password and token match + */ + public boolean checkPassword(char[] password, String token) + { + Matcher m = layout.matcher(token); + if (!m.matches()) + throw new IllegalArgumentException("Invalid token format"); + int iterations = iterations(Integer.parseInt(m.group(1))); + byte[] hash = Base64.getUrlDecoder().decode(m.group(2)); + byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8); + byte[] check = pbkdf2(password, salt, iterations); + int zero = 0; + for (int idx = 0; idx < check.length; ++idx) + zero |= hash[salt.length + idx] ^ check[idx]; + return zero == 0; + } + + private static byte[] pbkdf2(char[] password, byte[] salt, int iterations) + { + KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE); + try { + SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM); + return f.generateSecret(spec).getEncoded(); + } + catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex); + } + catch (InvalidKeySpecException ex) { + throw new IllegalStateException("Invalid SecretKeyFactory", ex); + } + } + + /** + * Hash a password in an immutable {@code String}. + * + *

Passwords should be stored in a {@code char[]} so that it can be filled + * with zeros after use instead of lingering on the heap and elsewhere. + * + * @deprecated Use {@link #hash(char[])} instead + */ + @Deprecated + public String hash(String password) + { + return hash(password.toCharArray()); + } + + /** + * Authenticate with a password in an immutable {@code String} and a stored + * password token. + * + * @deprecated Use {@link #checkPassword(char[],String)} instead. + * @see #hash(String) + */ + @Deprecated + public boolean checkPassword(String password, String token) + { + return checkPassword(password.toCharArray(), token); + } + +} diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java new file mode 100644 index 0000000000..4f5337f963 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java @@ -0,0 +1,35 @@ +package com.baeldung.passwordhashing; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + + +/** A really simple SHA_512 Encryption example. + * + */ +public class SHA512Hasher { + + public String hash(String passwordToHash, byte[] salt){ + String generatedPassword = null; + try { + MessageDigest md = MessageDigest.getInstance("SHA-512"); + md.update(salt); + byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for(int i=0; i< bytes.length ;i++){ + sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); + } + generatedPassword = sb.toString(); + } + catch (NoSuchAlgorithmException e){ + e.printStackTrace(); + } + return generatedPassword; + } + + public boolean checkPassword(String hash, String attempt, byte[] salt){ + String generatedHash = hash(attempt, salt); + return hash.equals(generatedHash); + } +} diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java b/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java new file mode 100644 index 0000000000..36c9b65070 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java @@ -0,0 +1,18 @@ +package com.baeldung.passwordhashing; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import java.security.spec.KeySpec; + +/** A really simple SimplePBKDF2 Encryption example. + * + */ +public class SimplePBKDF2Hasher { + + public static String hashSimple(String password, byte[] salt) throws Exception{ + KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128); + SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + byte[] hash = f.generateSecret(spec).getEncoded(); + return String.valueOf(hash); + } +} diff --git a/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java new file mode 100644 index 0000000000..bebffe52f1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java @@ -0,0 +1,45 @@ +/** + * + */ +package com.baeldung.string; + +/** + * @author swpraman + * + */ +public class AppendCharAtPositionX { + + public String addCharUsingCharArray(String str, char ch, int position) { + validate(str, position); + int len = str.length(); + char[] updatedArr = new char[len + 1]; + str.getChars(0, position, updatedArr, 0); + updatedArr[position] = ch; + str.getChars(position, len, updatedArr, position + 1); + return new String(updatedArr); + } + + public String addCharUsingSubstring(String str, char ch, int position) { + validate(str, position); + return str.substring(0, position) + ch + str.substring(position); + } + + public String addCharUsingStringBuilder(String str, char ch, int position) { + validate(str, position); + StringBuilder sb = new StringBuilder(str); + sb.insert(position, ch); + return sb.toString(); + } + + private void validate(String str, int position) { + if (str == null) { + throw new IllegalArgumentException("Str should not be null"); + } + int len = str.length(); + if (position < 0 || position > len) { + throw new IllegalArgumentException("position[" + position + "] should be " + + "in the range 0.." + len + " for string " + str); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java b/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java new file mode 100644 index 0000000000..69e151bfcb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/switchstatement/SwitchStatement.java @@ -0,0 +1,70 @@ +package com.baeldung.switchstatement; + +public class SwitchStatement { + + public String exampleOfIF(String animal) { + + String result; + + if (animal.equals("DOG") || animal.equals("CAT")) { + result = "domestic animal"; + } else if (animal.equals("TIGER")) { + result = "wild animal"; + } else { + result = "unknown animal"; + } + return result; + } + + public String exampleOfSwitch(String animal) { + + String result; + + switch (animal) { + case "DOG": + case "CAT": + result = "domestic animal"; + break; + case "TIGER": + result = "wild animal"; + break; + default: + result = "unknown animal"; + break; + } + return result; + } + + public String forgetBreakInSwitch(String animal) { + + String result; + + switch (animal) { + + case "DOG": + System.out.println("domestic animal"); + result = "domestic animal"; + + default: + System.out.println("unknown animal"); + result = "unknown animal"; + + } + return result; + } + + public String constantCaseValue(String animal) { + + String result = ""; + + final String dog = "DOG"; + + switch (animal) { + + case dog: + result = "domestic animal"; + } + return result; + } + +} diff --git a/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java b/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java new file mode 100644 index 0000000000..bdf6684f78 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java @@ -0,0 +1,23 @@ +package com.baeldung.synthetic; + +import java.util.Comparator; + +/** + * Class which contains a synthetic bridge method. + * + * @author Donato Rimenti + * + */ +public class BridgeMethodDemo implements Comparator { + + /* + * (non-Javadoc) + * + * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) + */ + @Override + public int compare(Integer o1, Integer o2) { + return 0; + } + +} diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java new file mode 100644 index 0000000000..d3d75ac05e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java @@ -0,0 +1,34 @@ +package com.baeldung.synthetic; + +/** + * Wrapper for a class which contains a synthetic constructor. + * + * @author Donato Rimenti + * + */ +public class SyntheticConstructorDemo { + + /** + * We need to instantiate the {@link NestedClass} using a private + * constructor from the enclosing instance in order to generate a synthetic + * constructor. + */ + private NestedClass nestedClass = new NestedClass(); + + /** + * Class which contains a synthetic constructor. + * + * @author Donato Rimenti + * + */ + class NestedClass { + + /** + * In order to generate a synthetic constructor, this class must have a + * private constructor. + */ + private NestedClass() { + } + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java new file mode 100644 index 0000000000..1813e03953 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java @@ -0,0 +1,22 @@ +package com.baeldung.synthetic; + +/** + * Wrapper for a class which contains a synthetic field reference to the outer + * class. + * + * @author Donato Rimenti + * + */ +public class SyntheticFieldDemo { + + /** + * Class which contains a synthetic field reference to the outer class. + * + * @author Donato Rimenti + * + */ + class NestedClass { + + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java new file mode 100644 index 0000000000..59be4e1429 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java @@ -0,0 +1,48 @@ +package com.baeldung.synthetic; + +/** + * Wrapper for a class which contains two synthetic methods accessors to a + * private field. + * + * @author Donato Rimenti + * + */ +public class SyntheticMethodDemo { + + /** + * Class which contains two synthetic methods accessors to a private field. + * + * @author Donato Rimenti + * + */ + class NestedClass { + + /** + * Field for which will be generated synthetic methods accessors. It's + * important that this field is private for this purpose. + */ + private String nestedField; + } + + /** + * Gets the private nested field. We need to read the nested field in order + * to generate the synthetic getter. + * + * @return the {@link NestedClass#nestedField} + */ + public String getNestedField() { + return new NestedClass().nestedField; + } + + /** + * Sets the private nested field. We need to write the nested field in order + * to generate the synthetic setter. + * + * @param nestedField + * the {@link NestedClass#nestedField} + */ + public void setNestedField(String nestedField) { + new NestedClass().nestedField = nestedField; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java b/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java new file mode 100644 index 0000000000..50dbc9c774 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java @@ -0,0 +1,15 @@ +package com.baeldung.throwsexception; + +public class Calculator { + + public double divide(double a, double b) { + if (b == 0) { + throw new DivideByZeroException("Divider cannot be equal to zero!"); + } + return a/b; + } + +} + + + diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java b/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java new file mode 100644 index 0000000000..0b371dcedb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java @@ -0,0 +1,9 @@ +package com.baeldung.throwsexception; + +public class DataAccessException extends RuntimeException { + + public DataAccessException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java b/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java new file mode 100644 index 0000000000..4413374c99 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java @@ -0,0 +1,9 @@ +package com.baeldung.throwsexception; + +public class DivideByZeroException extends RuntimeException { + + public DivideByZeroException(String message) { + super(message); + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Main.java b/core-java/src/main/java/com/baeldung/throwsexception/Main.java new file mode 100644 index 0000000000..17fbf5a582 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/Main.java @@ -0,0 +1,41 @@ +package com.baeldung.throwsexception; + +import com.sun.mail.iap.ConnectionException; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.net.SocketException; + +public class Main { + + public static void main(String[] args) throws FileNotFoundException { + TryCatch tryCatch = new TryCatch(); + + try { + tryCatch.execute(); + } catch (ConnectionException | SocketException ex) { + System.out.println("IOException"); + } catch (Exception ex) { + System.out.println("General exception"); + } + + checkedException(); + checkedExceptionWithThrows(); + } + + private static void checkedExceptionWithThrows() throws FileNotFoundException { + File file = new File("not_existing_file.txt"); + FileInputStream stream = new FileInputStream(file); + } + + private static void checkedException() { + File file = new File("not_existing_file.txt"); + try { + FileInputStream stream = new FileInputStream(file); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java new file mode 100644 index 0000000000..7d8345c3c1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.throwsexception; + +import java.sql.SQLException; +import java.util.List; + +public class PersonRepository { + + public List findAll() throws SQLException { + throw new SQLException(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java b/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java new file mode 100644 index 0000000000..6bb8b90bf1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java @@ -0,0 +1,22 @@ +package com.baeldung.throwsexception; + +import java.sql.SQLException; + +public class SimpleService { + + private PersonRepository personRepository = new PersonRepository(); + + public void wrappingException() { + try { + personRepository.findAll(); + } catch (SQLException e) { + throw new DataAccessException("SQL Exception", e); + } + } + + public void runtimeNullPointerException() { + String a = null; + a.length(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java b/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java new file mode 100644 index 0000000000..2fd87f124d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java @@ -0,0 +1,13 @@ +package com.baeldung.throwsexception; + +import com.sun.mail.iap.ConnectionException; + +import java.net.SocketException; + +public class TryCatch { + + public void execute() throws SocketException, ConnectionException, Exception { + //code that would throw any of: SocketException, ConnectionException, Exception + } + +} diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java new file mode 100644 index 0000000000..fb92eb8d0d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java @@ -0,0 +1,13 @@ +package com.baeldung.zoneddatetime; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +public class OffsetDateTimeExample { + + public OffsetDateTime getCurrentTimeByZoneOffset(String offset) { + ZoneOffset zoneOffSet= ZoneOffset.of(offset); + OffsetDateTime date = OffsetDateTime.now(zoneOffSet); + return date; + } +} diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java new file mode 100644 index 0000000000..58e2d4d5ad --- /dev/null +++ b/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java @@ -0,0 +1,13 @@ +package com.baeldung.zoneddatetime; + +import java.time.OffsetTime; +import java.time.ZoneOffset; + +public class OffsetTimeExample { + + public OffsetTime getCurrentTimeByZoneOffset(String offset) { + ZoneOffset zoneOffSet = ZoneOffset.of(offset); + OffsetTime time = OffsetTime.now(zoneOffSet); + return time; + } +} diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java b/core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java new file mode 100644 index 0000000000..b54b8c5225 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java @@ -0,0 +1,21 @@ +package com.baeldung.zoneddatetime; + +import java.time.ZoneId; +import java.time.ZonedDateTime; + +public class ZoneDateTimeExample { + + public ZonedDateTime getCurrentTimeByZoneId(String region) { + ZoneId zone = ZoneId.of(region); + ZonedDateTime date = ZonedDateTime.now(zone); + return date; + } + + public ZonedDateTime convertZonedDateTime(ZonedDateTime sourceDate, String destZone) { + + ZoneId destZoneId = ZoneId.of(destZone); + ZonedDateTime destDate = sourceDate.withZoneSameInstant(destZoneId); + + return destDate; + } +} diff --git a/core-java/src/main/resources/logback.xml b/core-java/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/core-java/src/main/resources/logback.xml +++ b/core-java/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java/src/test/java/com/baeldung/array/RemoveFirstElementUnitTest.java b/core-java/src/test/java/com/baeldung/array/RemoveFirstElementUnitTest.java deleted file mode 100644 index 7d11016d7f..0000000000 --- a/core-java/src/test/java/com/baeldung/array/RemoveFirstElementUnitTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.array; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -public class RemoveFirstElementUnitTest { - - @Test - public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() { - String[] stringArray = {"foo", "bar", "baz"}; - - String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length); - - assertThat(modifiedArray.length).isEqualTo(2); - assertThat(modifiedArray[0]).isEqualTo("bar"); - } - - @Test - public void givenArrayList_whenRemovingFirstElement_thenListSmallerAndElementRemoved() { - List stringList = new ArrayList<>(Arrays.asList("foo", "bar", "baz")); - stringList.remove(0); - - assertThat(stringList.size()).isEqualTo(2); - assertThat(stringList.get(0)).isEqualTo("bar"); - } - - @Test - public void givenLinkedList_whenRemovingFirstElement_thenListSmallerAndElementRemoved() { - List stringList = new LinkedList<>(Arrays.asList("foo", "bar", "baz")); - stringList.remove(0); - - assertThat(stringList.size()).isEqualTo(2); - assertThat(stringList.get(0)).isEqualTo("bar"); - } - -} diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java new file mode 100644 index 0000000000..41c67ff389 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java @@ -0,0 +1,95 @@ +package com.baeldung.binding; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.verify; + +/** + *https://gist.github.com/bloodredsun/a041de13e57bf3c6c040 + */ +@RunWith(MockitoJUnitRunner.class) + +public class AnimalActivityUnitTest { + + @Mock + private Appender mockAppender; + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void givenAnimalReference__whenRefersAnimalObject_shouldCallFunctionWithAnimalParam() { + + Animal animal = new Animal(); + + AnimalActivity.sleep(animal); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("Animal is sleeping")); + } + + @Test + public void givenDogReference__whenRefersCatObject_shouldCallFunctionWithAnimalParam() { + + Cat cat = new Cat(); + + AnimalActivity.sleep(cat); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("Cat is sleeping")); + } + + @Test + public void givenAnimaReference__whenRefersDogObject_shouldCallFunctionWithAnimalParam() { + + Animal cat = new Cat(); + + AnimalActivity.sleep(cat); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("Animal is sleeping")); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java new file mode 100644 index 0000000000..a34640b58a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.binding; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.List; + +/** + * Created by madhumita.g on 01-08-2018. + */ + +@RunWith(MockitoJUnitRunner.class) +public class AnimalUnitTest { + @Mock + private Appender mockAppender; + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void whenCalledWithoutParameters_shouldCallFunctionMakeNoiseWithoutParameters() { + + Animal animal = new Animal(); + + animal.makeNoise(); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("generic animal noise")); + } + + @Test + public void whenCalledWithParameters_shouldCallFunctionMakeNoiseWithParameters() { + + Animal animal = new Animal(); + + int testValue = 3; + animal.makeNoise(testValue); + + verify(mockAppender,times(3)).doAppend(captorLoggingEvent.capture()); + + final List loggingEvents = captorLoggingEvent.getAllValues(); + + for(LoggingEvent loggingEvent : loggingEvents) + { + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("generic animal noise countdown "+testValue)); + + testValue--; + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java new file mode 100644 index 0000000000..76ccfb7719 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.binding; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.verify; + +/** + * Created by madhumita.g on 01-08-2018. + */ +@RunWith(MockitoJUnitRunner.class) +public class CatUnitTest { + + @Mock + private Appender mockAppender; + + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void makeNoiseTest() { + + Cat cat = new Cat(); + + cat.makeNoise(); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("meow")); + + } +} diff --git a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java index ec35885b84..cabf9f7bdb 100644 --- a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java +++ b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java @@ -11,7 +11,7 @@ public class CustomClassLoaderUnitTest { public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { CustomClassLoader customClassLoader = new CustomClassLoader(); - Class c = customClassLoader.getClass(PrintClassLoader.class.getName()); + Class c = customClassLoader.findClass(PrintClassLoader.class.getName()); Object ob = c.newInstance(); diff --git a/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java b/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java new file mode 100644 index 0000000000..0c0266a111 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.constructorsstaticfactorymethods; + +import com.baeldung.constructorsstaticfactorymethods.entities.User; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class UserUnitTest { + + @Test + public void givenUserClass_whenCalledcreateWithDefaultCountry_thenCorrect() { + assertThat(User.createWithDefaultCountry("John", "john@domain.com")).isInstanceOf(User.class); + } + + @Test + public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetName_thenCorrect() { + User user = User.createWithDefaultCountry("John", "john@domain.com"); + assertThat(user.getName()).isEqualTo("John"); + } + + @Test + public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetEmail_thenCorrect() { + User user = User.createWithDefaultCountry("John", "john@domain.com"); + assertThat(user.getEmail()).isEqualTo("john@domain.com"); + } + + @Test + public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetCountry_thenCorrect() { + User user = User.createWithDefaultCountry("John", "john@domain.com"); + assertThat(user.getCountry()).isEqualTo("Argentina"); + } + + @Test + public void givenUserInstanceCreatedWithcreateWithInstantiationTime_whenCalledcreateWithInstantiationTime_thenCorrect() { + assertThat(User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina")).isInstanceOf(User.class); + } + + @Test + public void givenUserInstanceCreatedWithgetSingletonIntance_whenCalledgetSingletonInstance_thenCorrect() { + User user1 = User.getSingletonInstance("John", "john@domain.com", "Argentina"); + User user2 = User.getSingletonInstance("John", "john@domain.com", "Argentina"); + assertThat(user1).isEqualTo(user2); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java index 35aa07821c..70bfe168dd 100644 --- a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java +++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java @@ -75,26 +75,5 @@ public class PizzaUnitTest { pz.setStatus(Pizza.PizzaStatusEnum.READY); pz.deliver(); assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); - } - - @Test - public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() { - String pizzaEnumValue = "READY"; - PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); - assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY); - } - - @Test(expected = IllegalArgumentException.class) - public void whenConvertedIntoEnum_thenThrowsException() { - String pizzaEnumValue = "rEAdY"; - PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); - } - - @Test(expected = IllegalArgumentException.class) - public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() { - String pizzaEnumValue = "invalid"; - PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); - } - - + } } diff --git a/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java b/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java index 1e86132116..b3f585cfe4 100644 --- a/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java @@ -21,7 +21,7 @@ public class ExceptionsUnitTest { @Test public void loadAllPlayers() { assertThatThrownBy(() -> exceptions.loadAllPlayers("")) - .isInstanceOf(IOException.class); + .isInstanceOf(IllegalStateException.class); } @Test @@ -72,12 +72,6 @@ public class ExceptionsUnitTest { .isInstanceOf(NullPointerException.class); } - @Test - public void throwAsGotoAntiPattern() { - assertThatThrownBy(() -> exceptions.throwAsGotoAntiPattern()) - .isInstanceOf(MyException.class); - } - @Test public void getPlayerScoreSwallowingExceptionAntiPatternAlternative2() { assertThatThrownBy(() -> exceptions.getPlayerScoreSwallowingExceptionAntiPatternAlternative2("")) diff --git a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java index bc012dae6b..b484eecef7 100644 --- a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java @@ -9,28 +9,15 @@ import java.util.stream.Stream; import lombok.extern.java.Log; import org.junit.Assert; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; @Log public class ListInitializationUnitTest { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Test public void givenAnonymousInnerClass_thenInitialiseList() { List cities = new ArrayList() { - // Inside declaration of the subclass - - // You can have multiple initializer block { - log.info("Inside the first initializer block."); - } - - { - log.info("Inside the second initializer block."); add("New York"); add("Rio"); add("Tokyo"); @@ -47,11 +34,10 @@ public class ListInitializationUnitTest { Assert.assertTrue(list.contains("foo")); } - @Test + @Test(expected = UnsupportedOperationException.class) public void givenArraysAsList_whenAdd_thenUnsupportedException() { List list = Arrays.asList("foo", "bar"); - exception.expect(UnsupportedOperationException.class); list.add("baz"); } diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java new file mode 100644 index 0000000000..3fa1db18d2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.memoryleaks.equalshashcode; + +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Ignore; +import org.junit.Test; + +public class PersonMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() { + Map map = new HashMap(); + for(int i=0; i<10000000; i++) { + map.put(new Person("jon"), 1); + } + assertTrue(map.size() > 1); + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenMap_whenEqualsAndHashCodeOverridden_thenNoMemoryLeak() { + Map map = new HashMap(); + for(int i=0; i<10000; i++) { + map.put(new PersonOptimized("jon"), 1); + } + assertTrue(map.size() == 1); + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java new file mode 100644 index 0000000000..b6d81a8968 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.memoryleaks.finalize; + +import org.junit.Ignore; +import org.junit.Test; + +public class FinalizeMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenObjectWithFinalizer_whenCreatingAndDestroyingThisObject_thenMemoryLeak() { + BulkyObject[] stock = new BulkyObject[100000]; + + for(int i=0; i<100000; i++) { + stock[i] = new BulkyObject(); + } + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenObjectWithoutFinalizer_whenCreatingAndDestroyingThisObject_thenNoMemoryLeak() { + BulkyObjectOptimized[] stock = new BulkyObjectOptimized[100000]; + + for(int i=0; i<100000; i++) { + stock[i] = new BulkyObjectOptimized(); + } + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java new file mode 100644 index 0000000000..0854e4a38a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.memoryleaks.innerclass; + +import org.junit.Ignore; +import org.junit.Test; + +public class StaticInnerClassMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenUsingInnerClass_whenInitializingInnerClass_thenInnerClassHoldsReferenceOfOuterObject() { + InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = new InnerClassWrapper().new SimpleInnerClass(); + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenUsingStaticNestedClass_whenInitializingInnerClass_thenStaticNestedClassDoesntReferenceOuterObject() { + StaticNestedClassWrapper.StaticNestedClass staticNestedClassObj = new StaticNestedClassWrapper.StaticNestedClass(); + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java new file mode 100644 index 0000000000..6d363e0bdc --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.memoryleaks.internedstrings; + +import org.junit.Ignore; +import org.junit.Test; + +public class StringInternMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenJava6OrBelow_whenInterningLargeStrings_thenPermgenIncreases() { + new InternedString().readString(); + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenJava6OrBelow_whenNotInterningLargeStrings_thenPermgenDoesntIncrease() { + new StringObject().readString(); + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java new file mode 100644 index 0000000000..e64fdb73e0 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +public class NonStaticFieldsMemoryLeakUnitTest { + public List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenNonStaticLargeList_whenPopulatingList_thenListGarbageCollected() { + System.out.println("Debug Point 1"); + new NonStaticFieldsMemoryLeakUnitTest().populateList(); + System.out.println("Debug Point 3"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java new file mode 100644 index 0000000000..1765f0cf0d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +public class StaticFieldsMemoryLeakUnitTest { + public static List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenStaticLargeList_whenPopulatingList_thenListIsNotGarbageCollected() { + System.out.println("Debug Point 1"); + new StaticFieldsDemo().populateList(); + System.out.println("Debug Point 3"); + } +} diff --git a/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java new file mode 100644 index 0000000000..286dffb56a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.nth.root.calculator; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class NthRootCalculatorUnitTest { + + @InjectMocks + private NthRootCalculator nthRootCalculator; + + @Test + public void giventThatTheBaseIs125_andTheExpIs3_whenCalculateIsCalled_thenTheResultIsTheCorrectOne() { + Double result = nthRootCalculator.calculate(125.0, 3.0); + assertEquals(result, (Double) 5.0d); + } +} diff --git a/core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java b/core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java new file mode 100644 index 0000000000..a2fd839ba4 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.nth.root.main; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import static org.junit.Assert.assertEquals; + +public class MainUnitTest { + @InjectMocks + private Main main; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final PrintStream originalOut = System.out; + + @Before + public void setUpStreams() { + System.setOut(new PrintStream(outContent)); + } + + @After + public void restoreStreams() { + System.setOut(originalOut); + } + + @Test + public void givenThatTheBaseIs125_andTheExpIs3_whenMainIsCalled_thenTheCorrectResultIsPrinted() { + main.main(new String[]{"125.0", "3.0"}); + assertEquals("The 3.0 root of 125.0 equals to 5.0.\n", outContent.toString().replaceAll("\r", "")); + } +} diff --git a/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java b/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java new file mode 100644 index 0000000000..8e90725c77 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.passwordhashing; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + + +public class PBKDF2HasherUnitTest { + + private PBKDF2Hasher mPBKDF2Hasher; + + @Before + public void setUp() throws Exception { + mPBKDF2Hasher = new PBKDF2Hasher(); + } + + @Test + public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception { + String message1 = "password123"; + + String hash1 = mPBKDF2Hasher.hash(message1.toCharArray()); + + assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1)); + + } + + @Test + public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception { + String message1 = "password123"; + + String hash1 = mPBKDF2Hasher.hash(message1.toCharArray()); + + String wrongPasswordAttempt = "IamWrong"; + + assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1)); + + } + + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java b/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java new file mode 100644 index 0000000000..3acfb0ba9d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.passwordhashing; + +import org.junit.Before; +import org.junit.Test; + +import java.security.SecureRandom; + +import static org.junit.Assert.*; + +/** + * Created by PhysicsSam on 06-Sep-18. + */ +public class SHA512HasherUnitTest { + + private SHA512Hasher hasher; + private SecureRandom secureRandom; + + @Before + public void setUp() throws Exception { + hasher = new SHA512Hasher(); + secureRandom = new SecureRandom(); + } + + @Test + public void givenSamePasswordAndSalt_whenHashed_checkResultingHashesAreEqual() throws Exception { + + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String hash1 = hasher.hash("password", salt); + String hash2 = hasher.hash("password", salt); + + assertEquals(hash1, hash2); + + } + + @Test + public void givenSamePasswordAndDifferentSalt_whenHashed_checkResultingHashesNotEqual() throws Exception { + + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + String hash1 = hasher.hash("password", salt); + //generate a second salt + byte[] secondSalt = new byte[16]; + String hash2 = hasher.hash("password", secondSalt); + + assertNotEquals(hash1, hash2); + + } + + @Test + public void givenPredefinedHash_whenCorrectAttemptGiven_checkAuthenticationSucceeds() throws Exception { + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String originalHash = hasher.hash("password123", salt); + + assertTrue(hasher.checkPassword(originalHash, "password123", salt)); + } + + @Test + public void givenPredefinedHash_whenIncorrectAttemptGiven_checkAuthenticationFails() throws Exception { + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String originalHash = hasher.hash("password123", salt); + + assertFalse(hasher.checkPassword(originalHash, "password124", salt)); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java new file mode 100644 index 0000000000..f21a755b01 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java @@ -0,0 +1,109 @@ +package com.baeldung.regexp.optmization; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.assertTrue; + +public class OptimizedMatcherUnitTest { + + private long time; + private long mstimePreCompiled; + private long mstimeNotPreCompiled; + + private String action; + + private List items; + + @Before + public void setup() { + Random random = new Random(); + items = new ArrayList(); + long average = 0; + + for (int i = 0; i < 100000; ++i) { + StringBuilder s = new StringBuilder(); + int characters = random.nextInt(7) + 1; + for (int k = 0; k < characters; ++ k) { + char c = (char)(random.nextInt('Z' - 'A') + 'A'); + int rep = random.nextInt(95) + 5; + for (int j = 0; j < rep; ++ j) + s.append(c); + average += rep; + } + items.add(s.toString()); + } + + average /= 100000; + System.out.println("generated data, average length: " + average); + } + + + @Test + public void givenANotPreCompiledAndAPreCompiledPatternA_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() { + + testPatterns("A*"); + assertTrue(mstimePreCompiled < mstimeNotPreCompiled); + } + + @Test + public void givenANotPreCompiledAndAPreCompiledPatternABC_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() { + + testPatterns("A*B*C*"); + assertTrue(mstimePreCompiled < mstimeNotPreCompiled); + } + + @Test + public void givenANotPreCompiledAndAPreCompiledPatternECWF_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() { + + testPatterns("E*C*W*F*"); + assertTrue(mstimePreCompiled < mstimeNotPreCompiled); + } + + private void testPatterns(String regex) { + time = System.nanoTime(); + int matched = 0; + int unmatched = 0; + + for (String item : this.items) { + if (item.matches(regex)) { + ++matched; + } + else { + ++unmatched; + } + } + + this.action = "uncompiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched; + + this.mstimeNotPreCompiled = (System.nanoTime() - time) / 1000000; + System.out.println(this.action + ": " + mstimeNotPreCompiled + "ms"); + + time = System.nanoTime(); + + Matcher matcher = Pattern.compile(regex).matcher(""); + matched = 0; + unmatched = 0; + + for (String item : this.items) { + if (matcher.reset(item).matches()) { + ++matched; + } + else { + ++unmatched; + } + } + + this.action = "compiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched; + + this.mstimePreCompiled = (System.nanoTime() - time) / 1000000; + System.out.println(this.action + ": " + mstimePreCompiled + "ms"); + } +} diff --git a/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java new file mode 100644 index 0000000000..8dbfcaf5e7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java @@ -0,0 +1,100 @@ +package com.baeldung.removingdecimals; + +import org.junit.Test; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.concurrent.TimeUnit; + +/** + * This benchmark compares some of the approaches to formatting a floating-point + * value into a {@link String} while removing the decimal part. + * + * To run, simply run the {@link RemovingDecimalsManualTest#runBenchmarks()} test + * at the end of this class. + * + * The benchmark takes about 15 minutes to run. Since it is using {@link Mode#Throughput}, + * higher numbers mean better performance. + */ +@BenchmarkMode(Mode.Throughput) +@Warmup(iterations = 5) +@Measurement(iterations = 20) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@State(Scope.Benchmark) +public class RemovingDecimalsManualTest { + @Param(value = {"345.56", "345345345.56", "345345345345345345.56"}) double doubleValue; + + NumberFormat nf; + DecimalFormat df; + + @Setup + public void readyFormatters() { + nf = NumberFormat.getInstance(); + nf.setMaximumFractionDigits(0); + df = new DecimalFormat("#,###"); + } + + @Benchmark + public String whenCastToInt_thenValueIsTruncated() { + return String.valueOf((int) doubleValue); + } + + @Benchmark + public String whenUsingStringFormat_thenValueIsRounded() { + return String.format("%.0f", doubleValue); + } + + @Benchmark + public String whenUsingNumberFormat_thenValueIsRounded() { + nf.setRoundingMode(RoundingMode.HALF_UP); + return nf.format(doubleValue); + } + + @Benchmark + public String whenUsingNumberFormatWithFloor_thenValueIsTruncated() { + nf.setRoundingMode(RoundingMode.FLOOR); + return nf.format(doubleValue); + } + + @Benchmark + public String whenUsingDecimalFormat_thenValueIsRounded() { + df.setRoundingMode(RoundingMode.HALF_UP); + return df.format(doubleValue); + } + + @Benchmark + public String whenUsingDecimalFormatWithFloor_thenValueIsTruncated() { + df.setRoundingMode(RoundingMode.FLOOR); + return df.format(doubleValue); + } + + @Benchmark + public String whenUsingBigDecimalDoubleValue_thenValueIsTruncated() { + BigDecimal big = new BigDecimal(doubleValue); + big = big.setScale(0, RoundingMode.FLOOR); + return big.toString(); + } + + @Benchmark + public String whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() { + BigDecimal big = new BigDecimal(doubleValue); + big = big.setScale(0, RoundingMode.HALF_UP); + return big.toString(); + } + + @Test + public void runBenchmarks() throws Exception { + Options options = new OptionsBuilder() + .include(this.getClass().getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true).shouldDoGC(true) + .jvmArgs("-server").build(); + + new Runner(options).run(); + } +} diff --git a/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java new file mode 100644 index 0000000000..2f634b553b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java @@ -0,0 +1,95 @@ +package com.baeldung.removingdecimals; + +import org.junit.Test; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.text.NumberFormat; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +/** + * Tests that demonstrate some different approaches for formatting a + * floating-point value into a {@link String} while removing the decimal part. + */ +public class RemovingDecimalsUnitTest { + private final double doubleValue = 345.56; + + @Test + public void whenCastToInt_thenValueIsTruncated() { + String truncated = String.valueOf((int) doubleValue); + assertEquals("345", truncated); + } + + @Test + public void givenALargeDouble_whenCastToInt_thenValueIsNotTruncated() { + double outOfIntRange = 6_000_000_000.56; + String truncationAttempt = String.valueOf((int) outOfIntRange); + assertNotEquals("6000000000", truncationAttempt); + } + + @Test + public void whenUsingStringFormat_thenValueIsRounded() { + String rounded = String.format("%.0f", doubleValue); + assertEquals("346", rounded); + } + + @Test + public void givenALargeDouble_whenUsingStringFormat_thenValueIsStillRounded() { + double outOfIntRange = 6_000_000_000.56; + String rounded = String.format("%.0f", outOfIntRange); + assertEquals("6000000001", rounded); + } + + @Test + public void whenUsingNumberFormat_thenValueIsRounded() { + NumberFormat nf = NumberFormat.getInstance(); + nf.setMaximumFractionDigits(0); + nf.setRoundingMode(RoundingMode.HALF_UP); + String rounded = nf.format(doubleValue); + assertEquals("346", rounded); + } + + @Test + public void whenUsingNumberFormatWithFloor_thenValueIsTruncated() { + NumberFormat nf = NumberFormat.getInstance(); + nf.setMaximumFractionDigits(0); + nf.setRoundingMode(RoundingMode.FLOOR); + String truncated = nf.format(doubleValue); + assertEquals("345", truncated); + } + + @Test + public void whenUsingDecimalFormat_thenValueIsRounded() { + DecimalFormat df = new DecimalFormat("#,###"); + df.setRoundingMode(RoundingMode.HALF_UP); + String rounded = df.format(doubleValue); + assertEquals("346", rounded); + } + + @Test + public void whenUsingDecimalFormatWithFloor_thenValueIsTruncated() { + DecimalFormat df = new DecimalFormat("#,###"); + df.setRoundingMode(RoundingMode.FLOOR); + String truncated = df.format(doubleValue); + assertEquals("345", truncated); + } + + @Test + public void whenUsingBigDecimalDoubleValue_thenValueIsTruncated() { + BigDecimal big = new BigDecimal(doubleValue); + big = big.setScale(0, RoundingMode.FLOOR); + String truncated = big.toString(); + assertEquals("345", truncated); + } + + @Test + public void whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() { + BigDecimal big = new BigDecimal(doubleValue); + big = big.setScale(0, RoundingMode.HALF_UP); + String truncated = big.toString(); + assertEquals("346", truncated); + } +} diff --git a/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java new file mode 100644 index 0000000000..2cdf6145d3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java @@ -0,0 +1,110 @@ +/** + * + */ +package com.baeldung.string; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * @author swpraman + * + */ +public class AppendCharAtPositionXUnitTest { + + private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX(); + private String word = "Titanc"; + private char letter = 'i'; + + @Test + public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() { + assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0)); + } + + @Test + public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() { + assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0)); + } + + @Test + public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() { + assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0)); + } + + @Test + public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() { + assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3)); + } + + @Test + public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() { + assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3)); + } + + @Test + public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() { + assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3)); + } + + @Test + public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() { + assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length())); + } + + @Test + public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() { + assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length())); + } + + @Test + public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() { + assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length())); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { + appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); + } + +} diff --git a/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java b/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java new file mode 100644 index 0000000000..e8ac645531 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.switchstatement; + +import org.junit.Test; + +import org.junit.Assert; + +public class SwitchStatementUnitTest { + private SwitchStatement s = new SwitchStatement(); + + + @Test + public void whenDog_thenDomesticAnimal() { + + String animal = "DOG"; + Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal)); + } + + @Test + public void whenNoBreaks_thenGoThroughBlocks() { + String animal = "DOG"; + Assert.assertEquals("unknown animal", s.forgetBreakInSwitch(animal)); + } + + @Test(expected=NullPointerException.class) + public void whenSwitchAgumentIsNull_thenNullPointerException() { + String animal = null; + Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal)); + } + + + @Test + public void whenCompareStrings_thenByEqual() { + String animal = new String("DOG"); + Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal)); + } + + +} diff --git a/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java b/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java new file mode 100644 index 0000000000..20f7647f48 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java @@ -0,0 +1,99 @@ +package com.baeldung.synthetic; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Unit test for {@link SyntheticFieldDemo}, {@link SyntheticMethodDemo}, + * {@link SyntheticConstructorDemo} and {@link BridgeMethodDemo} classes. + * + * @author Donato Rimenti + * + */ +public class SyntheticUnitTest { + + /** + * Tests that the {@link SyntheticMethodDemo.NestedClass} contains two synthetic + * methods. + */ + @Test + public void givenSyntheticMethod_whenIsSinthetic_thenTrue() { + // Checks that the nested class contains exactly two synthetic methods. + Method[] methods = SyntheticMethodDemo.NestedClass.class.getDeclaredMethods(); + Assert.assertEquals("This class should contain only two methods", 2, methods.length); + + for (Method m : methods) { + System.out.println("Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic()); + Assert.assertTrue("All the methods of this class should be synthetic", m.isSynthetic()); + } + } + + /** + * Tests that {@link SyntheticConstructorDemo.NestedClass} contains a synthetic + * constructor. + */ + @Test + public void givenSyntheticConstructor_whenIsSinthetic_thenTrue() { + // Checks that the nested class contains exactly a synthetic + // constructor. + int syntheticConstructors = 0; + Constructor[] constructors = SyntheticConstructorDemo.NestedClass.class.getDeclaredConstructors(); + Assert.assertEquals("This class should contain only two constructors", 2, constructors.length); + + for (Constructor c : constructors) { + System.out.println("Constructor: " + c.getName() + ", isSynthetic: " + c.isSynthetic()); + + // Counts the synthetic constructors. + if (c.isSynthetic()) { + syntheticConstructors++; + } + } + + // Checks that there's exactly one synthetic constructor. + Assert.assertEquals(1, syntheticConstructors); + } + + /** + * Tests that {@link SyntheticFieldDemo.NestedClass} contains a synthetic field. + */ + @Test + public void givenSyntheticField_whenIsSinthetic_thenTrue() { + // This class should contain exactly one synthetic field. + Field[] fields = SyntheticFieldDemo.NestedClass.class.getDeclaredFields(); + Assert.assertEquals("This class should contain only one field", 1, fields.length); + + for (Field f : fields) { + System.out.println("Field: " + f.getName() + ", isSynthetic: " + f.isSynthetic()); + Assert.assertTrue("All the fields of this class should be synthetic", f.isSynthetic()); + } + } + + /** + * Tests that {@link BridgeMethodDemo} contains a synthetic bridge method. + */ + @Test + public void givenBridgeMethod_whenIsBridge_thenTrue() { + // This class should contain exactly one synthetic bridge method. + int syntheticMethods = 0; + Method[] methods = BridgeMethodDemo.class.getDeclaredMethods(); + for (Method m : methods) { + System.out.println( + "Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic() + ", isBridge: " + m.isBridge()); + + // Counts the synthetic methods and checks that they are also bridge + // methods. + if (m.isSynthetic()) { + syntheticMethods++; + Assert.assertTrue("The synthetic method in this class should also be a bridge method", m.isBridge()); + } + } + + // Checks that there's exactly one synthetic bridge method. + Assert.assertEquals("There should be exactly 1 synthetic bridge method in this class", 1, syntheticMethods); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java b/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java new file mode 100644 index 0000000000..6b292ad8ab --- /dev/null +++ b/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.ternaryoperator; + +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class TernaryOperatorUnitTest { + + @Test + public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() { + int number = 10; + String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10"; + + assertThat(msg).isEqualTo("Number is less than or equal to 10"); + } + + @Test + public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() { + int exp1 = 0, exp2 = 0; + int result = 12 > 10 ? ++exp1 : ++exp2; + + assertThat(exp1).isEqualTo(1); + assertThat(exp2).isEqualTo(0); + assertThat(result).isEqualTo(1); + } + + @Test + public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() { + int exp1 = 0, exp2 = 0; + int result = 8 > 10 ? ++exp1 : ++exp2; + + assertThat(exp1).isEqualTo(0); + assertThat(exp2).isEqualTo(1); + assertThat(result).isEqualTo(1); + } + + @Test + public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned() { + int number = 6; + String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5"; + + assertThat(msg).isEqualTo("Number is greater than 5"); + } +} diff --git a/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java new file mode 100644 index 0000000000..ef838ed304 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.throwsexception; + +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class CalculatorUnitTest { + + @Test + public void whenDividerIsZero_thenDivideByZeroExceptionIsThrown() { + Calculator calculator = new Calculator(); + + assertThrows(DivideByZeroException.class, + () -> calculator.divide(10, 0)); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java new file mode 100644 index 0000000000..b9a658a960 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.throwsexception; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class SimpleServiceUnitTest { + + SimpleService simpleService = new SimpleService(); + + @Test + void whenSQLExceptionIsThrown_thenShouldBeRethrownWithWrappedException() { + assertThrows(DataAccessException.class, + () -> simpleService.wrappingException()); + } + + @Test + void whenCalled_thenNullPointerExceptionIsThrown() { + assertThrows(NullPointerException.class, + () -> simpleService.runtimeNullPointerException()); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java b/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java index 6aa59e68d0..22fe0f5e57 100644 --- a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.unsafe; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import sun.misc.Unsafe; @@ -56,6 +57,7 @@ public class UnsafeUnitTest { } @Test + @Ignore // Uncomment for local public void givenArrayBiggerThatMaxInt_whenAllocateItOffHeapMemory_thenSuccess() throws NoSuchFieldException, IllegalAccessException { //given long SUPER_SIZE = (long) Integer.MAX_VALUE * 2; diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java new file mode 100644 index 0000000000..a08d3737cd --- /dev/null +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.zoneddatetime; + +import static org.junit.Assert.assertTrue; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +import org.junit.Test; + +public class OffsetDateTimeExampleUnitTest { + + OffsetDateTimeExample offsetDateTimeExample = new OffsetDateTimeExample(); + + @Test + public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() { + String offset = "+02:00"; + OffsetDateTime time = offsetDateTimeExample.getCurrentTimeByZoneOffset(offset); + + assertTrue(time.getOffset() + .equals(ZoneOffset.of(offset))); + } +} diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java new file mode 100644 index 0000000000..488f934179 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.zoneddatetime; + +import static org.junit.Assert.assertTrue; + +import java.time.OffsetTime; +import java.time.ZoneOffset; + +import org.junit.Test; + +public class OffsetTimeExampleUnitTest { + + OffsetTimeExample offsetTimeExample = new OffsetTimeExample(); + + @Test + public void givenZoneOffset_whenGetCurrentTime_thenResultHasZone() { + String offset = "+02:00"; + OffsetTime time = offsetTimeExample.getCurrentTimeByZoneOffset(offset); + + assertTrue(time.getOffset() + .equals(ZoneOffset.of(offset))); + } +} diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java b/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java new file mode 100644 index 0000000000..e78ff3e3fd --- /dev/null +++ b/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.zoneddatetime; + +import static org.junit.Assert.assertTrue; + +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.junit.Test; + +public class ZoneDateTimeExampleUnitTest { + + ZoneDateTimeExample zoneDateTimeExample = new ZoneDateTimeExample(); + + @Test + public void givenZone_whenGetCurrentTime_thenResultHasZone() { + String zone = "Europe/Berlin"; + ZonedDateTime time = zoneDateTimeExample.getCurrentTimeByZoneId(zone); + + assertTrue(time.getZone() + .equals(ZoneId.of(zone))); + } + + @Test + public void givenZones_whenConvertDateByZone_thenGetConstantDiff() { + String sourceZone = "Europe/Berlin"; + String destZone = "Asia/Tokyo"; + ZonedDateTime sourceDate = zoneDateTimeExample.getCurrentTimeByZoneId(sourceZone); + ZonedDateTime destDate = zoneDateTimeExample.convertZonedDateTime(sourceDate, destZone); + + assertTrue(sourceDate.toInstant() + .compareTo(destDate.toInstant()) == 0); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java deleted file mode 100644 index bb3abff28d..0000000000 --- a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.baeldung.java.enums; - -import static junit.framework.TestCase.assertTrue; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; - -import org.junit.Test; - -import com.baeldung.enums.Pizza; - -public class PizzaUnitTest { - - @Test - public void givenPizaOrder_whenReady_thenDeliverable() { - Pizza testPz = new Pizza(); - testPz.setStatus(Pizza.PizzaStatusEnum.READY); - assertTrue(testPz.isDeliverable()); - } - - @Test - public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() { - List pzList = new ArrayList<>(); - Pizza pz1 = new Pizza(); - pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); - - Pizza pz2 = new Pizza(); - pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); - - Pizza pz3 = new Pizza(); - pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); - - Pizza pz4 = new Pizza(); - pz4.setStatus(Pizza.PizzaStatusEnum.READY); - - pzList.add(pz1); - pzList.add(pz2); - pzList.add(pz3); - pzList.add(pz4); - - List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList); - assertTrue(undeliveredPzs.size() == 3); - } - - @Test - public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() { - - List pzList = new ArrayList<>(); - Pizza pz1 = new Pizza(); - pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); - - Pizza pz2 = new Pizza(); - pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); - - Pizza pz3 = new Pizza(); - pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); - - Pizza pz4 = new Pizza(); - pz4.setStatus(Pizza.PizzaStatusEnum.READY); - - pzList.add(pz1); - pzList.add(pz2); - pzList.add(pz3); - pzList.add(pz4); - - EnumMap> map = Pizza.groupPizzaByStatus(pzList); - assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1); - assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2); - assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1); - } - - @Test - public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() { - Pizza pz = new Pizza(); - pz.setStatus(Pizza.PizzaStatusEnum.READY); - pz.deliver(); - assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); - } - -} diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 734b2c08b3..523f5b6e78 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -8,7 +8,6 @@ - [Generics in Kotlin](http://www.baeldung.com/kotlin-generics) - [Introduction to Kotlin Coroutines](http://www.baeldung.com/kotlin-coroutines) - [Destructuring Declarations in Kotlin](http://www.baeldung.com/kotlin-destructuring-declarations) -- [Kotlin with Mockito](http://www.baeldung.com/kotlin-mockito) - [Lazy Initialization in Kotlin](http://www.baeldung.com/kotlin-lazy-initialization) - [Overview of Kotlin Collections API](http://www.baeldung.com/kotlin-collections-api) - [Converting a List to Map in Kotlin](http://www.baeldung.com/kotlin-list-to-map) @@ -19,8 +18,6 @@ - [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods) - [Infix Functions in Kotlin](http://www.baeldung.com/kotlin-infix-functions) - [Try-with-resources in Kotlin](http://www.baeldung.com/kotlin-try-with-resources) -- [HTTP Requests with Kotlin and khttp](http://www.baeldung.com/kotlin-khttp) -- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection) - [Regular Expressions in Kotlin](http://www.baeldung.com/kotlin-regular-expressions) - [Objects in Kotlin](http://www.baeldung.com/kotlin-objects) - [Reading from a File in Kotlin](http://www.baeldung.com/kotlin-read-file) @@ -28,13 +25,17 @@ - [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection) - [Writing to a File in Kotlin](http://www.baeldung.com/kotlin-write-file) - [Lambda Expressions in Kotlin](http://www.baeldung.com/kotlin-lambda-expressions) -- [Writing Specifications with Kotlin and Spek](http://www.baeldung.com/kotlin-spek) -- [Processing JSON with Kotlin and Klaxson](http://www.baeldung.com/kotlin-json-klaxson) - [Kotlin String Templates](http://www.baeldung.com/kotlin-string-template) -- [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security) -- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor) - [Working with Enums in Kotlin](http://www.baeldung.com/kotlin-enum) - [Create a Java and Kotlin Project with Maven](http://www.baeldung.com/kotlin-maven-java-project) - [Reflection with Kotlin](http://www.baeldung.com/kotlin-reflection) - [Get a Random Number in Kotlin](http://www.baeldung.com/kotlin-random-number) - [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging) +- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors) +- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern) +- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes) +- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor) +- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) +- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) +- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) +- [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings) diff --git a/core-kotlin/build.gradle b/core-kotlin/build.gradle index 6c1e06aa25..2b6527fca7 100755 --- a/core-kotlin/build.gradle +++ b/core-kotlin/build.gradle @@ -6,7 +6,6 @@ version '1.0-SNAPSHOT' buildscript { ext.kotlin_version = '1.2.41' - ext.ktor_version = '0.9.2' repositories { mavenCentral() @@ -44,14 +43,6 @@ sourceSets { } dependencies { - compile "io.ktor:ktor-server-netty:$ktor_version" compile "ch.qos.logback:logback-classic:1.2.1" - compile "io.ktor:ktor-gson:$ktor_version" testCompile group: 'junit', name: 'junit', version: '4.12' - implementation 'com.beust:klaxon:3.0.1' - -} -task runServer(type: JavaExec) { - main = 'APIServer' - classpath = sourceSets.main.runtimeClasspath } \ No newline at end of file diff --git a/core-kotlin/kotlin-ktor/webapp/WEB-INF/web.xml b/core-kotlin/kotlin-ktor/webapp/WEB-INF/web.xml deleted file mode 100755 index 513a80cb27..0000000000 --- a/core-kotlin/kotlin-ktor/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - io.ktor.ktor.config - application.conf - - - - KtorServlet - KtorServlet - io.ktor.server.servlet.ServletApplicationEngine - - - true - - - - 304857600 - 304857600 - 0 - - - - - KtorServlet - / - - - \ No newline at end of file diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index afa7d8a963..0894a57320 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -3,26 +3,15 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-kotlin - 1.0-SNAPSHOT jar com.baeldung - parent-modules + parent-kotlin 1.0.0-SNAPSHOT + ../parent-kotlin - - - jcenter - http://jcenter.bintray.com - - - kotlin-ktor - https://dl.bintray.com/kotlin/ktor/ - - - org.apache.commons @@ -35,66 +24,6 @@ ${junit.platform.version} test - - org.jetbrains.kotlin - kotlin-stdlib - ${kotlin-stdlib.version} - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin-stdlib.version} - - - khttp - khttp - ${khttp.version} - - - org.jetbrains.kotlin - kotlin-test-junit - ${kotlin-test-junit.version} - test - - - org.jetbrains.kotlin - kotlin-reflect - ${kotlin-reflect.version} - - - org.jetbrains.kotlinx - kotlinx-coroutines-core - ${kotlinx.version} - - - org.jetbrains.spek - spek-api - 1.1.5 - test - - - org.jetbrains.spek - spek-subject-extension - 1.1.5 - test - - - org.jetbrains.spek - spek-junit-platform-engine - 1.1.5 - test - - - com.nhaarman - mockito-kotlin - ${mockito-kotlin.version} - test - - - com.github.salomonbrys.kodein - kodein - ${kodein.version} - org.assertj assertj-core @@ -102,142 +31,45 @@ test - com.beust - klaxon - ${klaxon.version} + com.h2database + h2 + ${h2database.version} + + + com.github.kittinunf.fuel + fuel + ${fuel.version} + + + com.github.kittinunf.fuel + fuel-gson + ${fuel.version} + + + com.github.kittinunf.fuel + fuel-rxjava + ${fuel.version} + + + com.github.kittinunf.fuel + fuel-coroutines + ${fuel.version} + + + nl.komponents.kovenant + kovenant + 3.3.0 + pom - - io.ktor - ktor-server-netty - ${ktor.io.version} - - - io.ktor - ktor-gson - ${ktor.io.version} - - - ch.qos.logback - logback-classic - 1.2.1 - test - - - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin-maven-plugin.version} - - - compile - - compile - - - - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/main/java - - - - - test-compile - - test-compile - - - - ${project.basedir}/src/test/kotlin - ${project.basedir}/src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - - - default-compile - none - - - - default-testCompile - none - - - java-compile - compile - - compile - - - - java-test-compile - test-compile - - testCompile - - - - - - maven-failsafe-plugin - ${maven-failsafe-plugin.version} - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - - - - - junit5 - - integration-test - verify - - - - **/*Test5.java - - - - - - - - - UTF-8 - 1.2.51 - 1.2.51 - 1.2.51 - 1.2.51 - 0.22.5 - 0.9.2 - 1.5.0 - 4.1.0 - 3.0.4 - 0.1.0 3.6.1 - 1.0.0 + 1.1.1 5.2.0 3.10.0 + 1.4.197 + 1.15.0 diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt new file mode 100644 index 0000000000..72b8d330e8 --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt @@ -0,0 +1,17 @@ +package com.baeldung.constructor + +class Car { + val id: String + val type: String + + constructor(id: String, type: String) { + this.id = id + this.type = type + } + +} + +fun main(args: Array) { + val car = Car("1", "sport") + val s= Car("2", "suv") +} \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt new file mode 100644 index 0000000000..4483bfcf08 --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt @@ -0,0 +1,3 @@ +package com.baeldung.constructor + +class Employee(name: String, val salary: Int): Person(name) \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Person.java b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java new file mode 100644 index 0000000000..57911b24ee --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java @@ -0,0 +1,19 @@ +package com.baeldung.constructor; + +class PersonJava { + final String name; + final String surname; + final Integer age; + + public PersonJava(String name, String surname) { + this.name = name; + this.surname = surname; + this.age = null; + } + + public PersonJava(String name, String surname, Integer age) { + this.name = name; + this.surname = surname; + this.age = age; + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt index 7d10d849b9..1384cd9937 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt +++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt @@ -1,39 +1,22 @@ package com.baeldung.builder -class FoodOrder private constructor(builder: FoodOrder.Builder) { - - val bread: String? - val condiments: String? - val meat: String? - val fish: String? - - init { - this.bread = builder.bread - this.condiments = builder.condiments - this.meat = builder.meat - this.fish = builder.fish - } - - class Builder { - - var bread: String? = null - private set - var condiments: String? = null - private set - var meat: String? = null - private set - var fish: String? = null - private set +class FoodOrder( + val bread: String?, + val condiments: String?, + val meat: String?, + val fish: String? +) { + data class Builder( + var bread: String? = null, + var condiments: String? = null, + var meat: String? = null, + var fish: String? = null) { fun bread(bread: String) = apply { this.bread = bread } - fun condiments(condiments: String) = apply { this.condiments = condiments } - fun meat(meat: String) = apply { this.meat = meat } - fun fish(fish: String) = apply { this.fish = fish } - - fun build() = FoodOrder(this) - + fun build() = FoodOrder(bread, condiments, meat, fish) } } + diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt index 6e20cf51b9..0e4219b40e 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt +++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt @@ -1,7 +1,7 @@ package com.baeldung.builder data class FoodOrderNamed( - val bread: String? = null, - val condiments: String? = null, - val meat: String? = null, - val fish: String? = null) + val bread: String? = null, + val condiments: String? = null, + val meat: String? = null, + val fish: String? = null) diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt new file mode 100644 index 0000000000..cc348e3fbf --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt @@ -0,0 +1,9 @@ +package com.baeldung.builder + +fun main(args: Array) { + FoodOrder.Builder() + .bread("bread") + .condiments("condiments") + .meat("meat") + .fish("bread").let { println(it) } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt new file mode 100644 index 0000000000..3779d74541 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt @@ -0,0 +1,26 @@ +package com.baeldung.constructor + +open class Person( + val name: String, + val age: Int? = null +) { + val upperCaseName: String = name.toUpperCase() + + init { + println("Hello, I'm $name") + + if (age != null && age < 0) { + throw IllegalArgumentException("Age cannot be less than zero!") + } + } + + init { + println("upperCaseName is $upperCaseName") + } + +} + +fun main(args: Array) { + val person = Person("John") + val personWithAge = Person("John", 22) +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt new file mode 100644 index 0000000000..4fd8aa27c7 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt @@ -0,0 +1,19 @@ +package com.baeldung.datastructures + +/** + * Example of how to use the {@link Node} class. + * + */ +fun main(args: Array) { + val tree = Node(4) + val keys = arrayOf(8, 15, 21, 3, 7, 2, 5, 10, 2, 3, 4, 6, 11) + for (key in keys) { + tree.insert(key) + } + val node = tree.find(4)!! + println("Node with value ${node.key} [left = ${node.left?.key}, right = ${node.right?.key}]") + println("Delete node with key = 3") + node.delete(3) + print("Tree content after the node elimination: ") + println(tree.visit().joinToString { it.toString() }) +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt new file mode 100644 index 0000000000..b81afe1e4c --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt @@ -0,0 +1,167 @@ +package com.baeldung.datastructures + +/** + * An ADT for a binary search tree. + * Note that this data type is neither immutable nor thread safe. + */ +class Node( + var key: Int, + var left: Node? = null, + var right: Node? = null) { + + /** + * Return a node with given value. If no such node exists, return null. + * @param value + */ + fun find(value: Int): Node? = when { + this.key > value -> left?.find(value) + this.key < value -> right?.find(value) + else -> this + + } + + /** + * Insert a given value into the tree. + * After insertion, the tree should contain a node with the given value. + * If the tree already contains the given value, nothing is performed. + * @param value + */ + fun insert(value: Int) { + if (value > this.key) { + if (this.right == null) { + this.right = Node(value) + } else { + this.right?.insert(value) + } + } else if (value < this.key) { + if (this.left == null) { + this.left = Node(value) + } else { + this.left?.insert(value) + } + } + } + + /** + * Delete the value from the given tree. If the tree does not contain the value, the tree remains unchanged. + * @param value + */ + fun delete(value: Int) { + when { + value > key -> scan(value, this.right, this) + value < key -> scan(value, this.left, this) + else -> removeNode(this, null) + } + } + + /** + * Scan the tree in the search of the given value. + * @param value + * @param node sub-tree that potentially might contain the sought value + * @param parent node's parent + */ + private fun scan(value: Int, node: Node?, parent: Node?) { + if (node == null) { + System.out.println("value " + value + + " seems not present in the tree.") + return + } + when { + value > node.key -> scan(value, node.right, node) + value < node.key -> scan(value, node.left, node) + value == node.key -> removeNode(node, parent) + } + + } + + /** + * Remove the node. + * + * Removal process depends on how many children the node has. + * + * @param node node that is to be removed + * @param parent parent of the node to be removed + */ + private fun removeNode(node: Node, parent: Node?) { + node.left?.let { leftChild -> + run { + node.right?.let { + removeTwoChildNode(node) + } ?: removeSingleChildNode(node, leftChild) + } + } ?: run { + node.right?.let { rightChild -> removeSingleChildNode(node, rightChild) } ?: removeNoChildNode(node, parent) + } + + + } + + /** + * Remove the node without children. + * @param node + * @param parent + */ + private fun removeNoChildNode(node: Node, parent: Node?) { + parent?.let { p -> + if (node == p.left) { + p.left = null + } else if (node == p.right) { + p.right = null + } + } ?: throw IllegalStateException( + "Can not remove the root node without child nodes") + + } + + /** + * Remove a node that has two children. + * + * The process of elimination is to find the biggest key in the left sub-tree and replace the key of the + * node that is to be deleted with that key. + */ + private fun removeTwoChildNode(node: Node) { + val leftChild = node.left!! + leftChild.right?.let { + val maxParent = findParentOfMaxChild(leftChild) + maxParent.right?.let { + node.key = it.key + maxParent.right = null + } ?: throw IllegalStateException("Node with max child must have the right child!") + + } ?: run { + node.key = leftChild.key + node.left = leftChild.left + } + + } + + /** + * Return a node whose right child contains the biggest value in the given sub-tree. + * Assume that the node n has a non-null right child. + * + * @param n + */ + private fun findParentOfMaxChild(n: Node): Node { + return n.right?.let { r -> r.right?.let { findParentOfMaxChild(r) } ?: n } + ?: throw IllegalArgumentException("Right child must be non-null") + + } + + /** + * Remove a parent that has only one child. + * Removal is effectively is just coping the data from the child parent to the parent parent. + * @param parent Node to be deleted. Assume that it has just one child + * @param child Assume it is a child of the parent + */ + private fun removeSingleChildNode(parent: Node, child: Node) { + parent.key = child.key + parent.left = child.left + parent.right = child.right + } + + fun visit(): Array { + val a = left?.visit() ?: emptyArray() + val b = right?.visit() ?: emptyArray() + return a + arrayOf(key) + b + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt new file mode 100644 index 0000000000..377ef979dc --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Interceptors.kt @@ -0,0 +1,11 @@ +package com.baeldung.fuel + +import com.github.kittinunf.fuel.core.Request + +fun tokenInterceptor() = { + next: (Request) -> Request -> + { req: Request -> + req.header(mapOf("Authorization" to "Bearer AbCdEf123456")) + next(req) + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt new file mode 100644 index 0000000000..035dfe7aa0 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/fuel/Post.kt @@ -0,0 +1,15 @@ +package com.baeldung.fuel + +import com.github.kittinunf.fuel.core.ResponseDeserializable +import com.google.gson.Gson + +data class Post(var userId:Int, + var id:Int, + var title:String, + var body:String){ + + + class Deserializer : ResponseDeserializable> { + override fun deserialize(content: String): Array = Gson().fromJson(content, Array::class.java) + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt b/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt new file mode 100644 index 0000000000..8238c41e56 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt @@ -0,0 +1,42 @@ +package com.baeldung.fuel + +import com.github.kittinunf.fuel.core.Method +import com.github.kittinunf.fuel.util.FuelRouting + +sealed class PostRoutingAPI : FuelRouting { + + override val basePath = "https://jsonplaceholder.typicode.com" + + class posts(val id: String, override val body: String?): PostRoutingAPI() + + class comments(val postId: String, override val body: String?): PostRoutingAPI() + + override val method: Method + get() { + return when(this) { + is PostRoutingAPI.posts -> Method.GET + is PostRoutingAPI.comments -> Method.GET + } + } + + override val path: String + get() { + return when(this) { + is PostRoutingAPI.posts -> "/posts" + is PostRoutingAPI.comments -> "/comments" + } + } + + override val params: List>? + get() { + return when(this) { + is PostRoutingAPI.posts -> listOf("id" to this.id) + is PostRoutingAPI.comments -> listOf("postId" to this.postId) + } + } + + override val headers: Map? + get() { + return null + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/ktor/APIServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/ktor/APIServer.kt deleted file mode 100755 index a12182ccc8..0000000000 --- a/core-kotlin/src/main/kotlin/com/baeldung/ktor/APIServer.kt +++ /dev/null @@ -1,73 +0,0 @@ -@file:JvmName("APIServer") - - -import io.ktor.application.call -import io.ktor.application.install -import io.ktor.features.CallLogging -import io.ktor.features.ContentNegotiation -import io.ktor.features.DefaultHeaders -import io.ktor.gson.gson -import io.ktor.request.path -import io.ktor.request.receive -import io.ktor.response.respond -import io.ktor.routing.* -import io.ktor.server.engine.embeddedServer -import io.ktor.server.netty.Netty -import org.slf4j.event.Level - -data class Author(val name: String, val website: String) -data class ToDo(var id: Int, val name: String, val description: String, val completed: Boolean) - -fun main(args: Array) { - - val toDoList = ArrayList(); - val jsonResponse = """{ - "id": 1, - "task": "Pay waterbill", - "description": "Pay water bill today", - }""" - - - embeddedServer(Netty, 8080) { - install(DefaultHeaders) { - header("X-Developer", "Baeldung") - } - install(CallLogging) { - level = Level.DEBUG - filter { call -> call.request.path().startsWith("/todo") } - filter { call -> call.request.path().startsWith("/author") } - } - install(ContentNegotiation) { - gson { - setPrettyPrinting() - } - } - routing() { - route("/todo") { - post { - var toDo = call.receive(); - toDo.id = toDoList.size; - toDoList.add(toDo); - call.respond("Added") - - } - delete("/{id}") { - call.respond(toDoList.removeAt(call.parameters["id"]!!.toInt())); - } - get("/{id}") { - - call.respond(toDoList[call.parameters["id"]!!.toInt()]); - } - get { - call.respond(toDoList); - } - } - get("/author"){ - call.respond(Author("Baeldung","baeldung.com")); - - } - - - } - }.start(wait = true) -} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt new file mode 100644 index 0000000000..ee01c06646 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt @@ -0,0 +1,75 @@ +package com.baeldung.nested + +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +class Computer(val model: String) { + + companion object { + const val originCountry = "China" + fun getBuiltDate(): String { + return "2018-05-23" + } + + val log: Logger = LoggerFactory.getLogger(Computer::class.java) + } + + //Nested class + class MotherBoard(val manufacturer: String) { + fun getInfo() = "Made by $manufacturer installed in $originCountry - ${getBuiltDate()}" + } + + //Inner class + inner class HardDisk(val sizeInGb: Int) { + fun getInfo() = "Installed on ${this@Computer} with $sizeInGb GB" + } + + interface Switcher { + fun on(): String + } + + interface Protector { + fun smart() + } + + fun powerOn(): String { + //Local class + var defaultColor = "Blue" + + class Led(val color: String) { + fun blink(): String { + return "blinking $color" + } + + fun changeDefaultPowerOnColor() { + defaultColor = "Violet" + } + } + + val powerLed = Led("Green") + log.debug("defaultColor is $defaultColor") + powerLed.changeDefaultPowerOnColor() + log.debug("defaultColor changed inside Led class to $defaultColor") + //Anonymous object + val powerSwitch = object : Switcher, Protector { + override fun on(): String { + return powerLed.blink() + } + + override fun smart() { + log.debug("Smart protection is implemented") + } + + fun changeDefaultPowerOnColor() { + defaultColor = "Yellow" + } + } + powerSwitch.changeDefaultPowerOnColor() + log.debug("defaultColor changed inside powerSwitch anonymous object to $defaultColor") + return powerSwitch.on() + } + + override fun toString(): String { + return "Computer(model=$model)" + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt index 17f5a43479..a6687b6e0a 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt @@ -93,6 +93,7 @@ internal class BuilderPatternUnitTest { Assertions.assertNull(foodOrder.fish) } + @Test fun whenBuildingFoodOrderApplySettingValues_thenFieldsNotNull() { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt new file mode 100644 index 0000000000..8a46c5f6ec --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt @@ -0,0 +1,319 @@ +package com.baeldung.datastructures + +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test + +class NodeTest { + + @Before + fun setUp() { + } + + @After + fun tearDown() { + } + + /** + * Test suit for finding the node by value + * Partition the tests as follows: + * 1. tree depth: 0, 1, > 1 + * 2. pivot depth location: not present, 0, 1, 2, > 2 + */ + + /** + * Find the node by value + * 1. tree depth: 0 + * 2. pivot depth location: not present + */ + @Test + fun givenDepthZero_whenPivotNotPresent_thenNull() { + val n = Node(1) + assertNull(n.find(2)) + } + + /** + * Find the node by value + * 1. tree depth: 0 + * 2. pivot depth location: 0 + */ + @Test + fun givenDepthZero_whenPivotDepthZero_thenReturnNodeItself() { + val n = Node(1) + assertEquals(n, n.find(1)) + } + + /** + * Find the node by value + * 1. tree depth: 1 + * 2. pivot depth location: not present + */ + @Test + fun givenDepthOne_whenPivotNotPresent_thenNull() { + val n = Node(1, Node(0)) + assertNull(n.find(2)) + } + + /** + * Find the node by value + * 1. tree depth: 1 + * 2. pivot depth location: not present + */ + @Test + fun givenDepthOne_whenPivotAtDepthOne_thenSuccess() { + val n = Node(1, Node(0)) + assertEquals(n.left, n.find(0) + ) + } + + @Test + fun givenDepthTwo_whenPivotAtDepth2_then_Success() { + val left = Node(1, Node(0), Node(2)) + val right = Node(5, Node(4), Node(6)) + val n = Node(3, left, right) + assertEquals(left.left, n.find(0)) + } + + + /** + * Test suit for inserting a value + * Partition the test as follows: + * 1. tree depth: 0, 1, 2, > 2 + * 2. depth to insert: 0, 1, > 1 + * 3. is duplicate: no, yes + * 4. sub-tree: left, right + */ + /** + * Test for inserting a value + * 1. tree depth: 0 + * 2. depth to insert: 1 + * 3. is duplicate: no + * 4. sub-tree: right + */ + @Test + fun givenTreeDepthZero_whenInsertNoDuplicateToRight_thenAddNode() { + val n = Node(1) + n.insert(2) + assertEquals(1, n.key) + with(n.right!!) { + assertEquals(2, key) + assertNull(left) + assertNull(right) + } + assertNull(n.left) + } + + /** + * Test for inserting a value + * 1. tree depth: 0 + * 2. depth to insert: 1 + * 3. is duplicate: no + * 4. sub-tree: right + */ + @Test + fun givenTreeDepthZero_whenInsertNoDuplicateToLeft_thenSuccess() { + val n = Node(1) + n.insert(0) + assertEquals(1, n.key) + with(n.left!!) { + assertEquals(0, key) + assertNull(left) + assertNull(right) + } + assertNull(n.right) + } + + /** + * Test for inserting a value + * 1. tree depth: 0 + * 2. depth to insert: 1 + * 3. is duplicate: yes + */ + @Test + fun givenTreeDepthZero_whenInsertDuplicate_thenSuccess() { + val n = Node(1) + n.insert(1) + assertEquals(1, n.key) + assertNull(n.right) + assertNull(n.left) + } + + + /** + * Test suit for inserting a value + * Partition the test as follows: + * 1. tree depth: 0, 1, 2, > 2 + * 2. depth to insert: 0, 1, > 1 + * 3. is duplicate: no, yes + * 4. sub-tree: left, right + */ + /** + * Test for inserting a value + * 1. tree depth: 1 + * 2. depth to insert: 1 + * 3. is duplicate: no + * 4. sub-tree: right + */ + @Test + fun givenTreeDepthOne_whenInsertNoDuplicateToRight_thenSuccess() { + val n = Node(10, Node(3)) + n.insert(15) + assertEquals(10, n.key) + with(n.right!!) { + assertEquals(15, key) + assertNull(left) + assertNull(right) + } + with(n.left!!) { + assertEquals(3, key) + assertNull(left) + assertNull(right) + } + } + + /** + * Test for inserting a value + * 1. tree depth: 1 + * 2. depth to insert: 1 + * 3. is duplicate: no + * 4. sub-tree: left + */ + @Test + fun givenTreeDepthOne_whenInsertNoDuplicateToLeft_thenAddNode() { + val n = Node(10, null, Node(15)) + n.insert(3) + assertEquals(10, n.key) + with(n.right!!) { + assertEquals(15, key) + assertNull(left) + assertNull(right) + } + with(n.left!!) { + assertEquals(3, key) + assertNull(left) + assertNull(right) + } + } + + /** + * Test for inserting a value + * 1. tree depth: 1 + * 2. depth to insert: 1 + * 3. is duplicate: yes + */ + @Test + fun givenTreeDepthOne_whenInsertDuplicate_thenNoChange() { + val n = Node(10, null, Node(15)) + n.insert(15) + assertEquals(10, n.key) + with(n.right!!) { + assertEquals(15, key) + assertNull(left) + assertNull(right) + } + assertNull(n.left) + } + + /** + * Test suit for removal + * Partition the input as follows: + * 1. tree depth: 0, 1, 2, > 2 + * 2. value to delete: absent, present + * 3. # child nodes: 0, 1, 2 + */ + /** + * Test for removal value + * 1. tree depth: 0 + * 2. value to delete: absent + */ + @Test + fun givenTreeDepthZero_whenValueAbsent_thenNoChange() { + val n = Node(1) + n.delete(0) + assertEquals(1, n.key) + assertNull(n.left) + assertNull(n.right) + } + + /** + * Test for removal + * 1. tree depth: 1 + * 2. value to delete: absent + */ + @Test + fun givenTreeDepthOne_whenValueAbsent_thenNoChange() { + val n = Node(1, Node(0), Node(2)) + n.delete(3) + assertEquals(1, n.key) + assertEquals(2, n.right!!.key) + with(n.left!!) { + assertEquals(0, key) + assertNull(left) + assertNull(right) + } + with(n.right!!) { + assertNull(left) + assertNull(right) + } + } + + /** + * Test suit for removal + * 1. tree depth: 1 + * 2. value to delete: present + * 3. # child nodes: 0 + */ + @Test + fun givenTreeDepthOne_whenNodeToDeleteHasNoChildren_thenChangeTree() { + val n = Node(1, Node(0)) + n.delete(0) + assertEquals(1, n.key) + assertNull(n.left) + assertNull(n.right) + } + + /** + * Test suit for removal + * 1. tree depth: 2 + * 2. value to delete: present + * 3. # child nodes: 1 + */ + @Test + fun givenTreeDepthTwo_whenNodeToDeleteHasOneChild_thenChangeTree() { + val n = Node(2, Node(0, null, Node(1)), Node(3)) + n.delete(0) + assertEquals(2, n.key) + with(n.right!!) { + assertEquals(3, key) + assertNull(left) + assertNull(right) + } + with(n.left!!) { + assertEquals(1, key) + assertNull(left) + assertNull(right) + } + } + + @Test + fun givenTreeDepthThree_whenNodeToDeleteHasTwoChildren_thenChangeTree() { + val l = Node(2, Node(1), Node(5, Node(4), Node(6))) + val r = Node(10, Node(9), Node(11)) + val n = Node(8, l, r) + n.delete(8) + assertEquals(6, n.key) + with(n.left!!) { + assertEquals(2, key) + assertEquals(1, left!!.key) + assertEquals(5, right!!.key) + assertEquals(4, right!!.left!!.key) + } + with(n.right!!) { + assertEquals(10, key) + assertEquals(9, left!!.key) + assertEquals(11, right!!.key) + } + } + +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt new file mode 100644 index 0000000000..f0f9267618 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt @@ -0,0 +1,286 @@ +package com.baeldung.fuel + +import awaitObjectResult +import awaitStringResponse +import com.github.kittinunf.fuel.Fuel +import com.github.kittinunf.fuel.core.FuelManager +import com.github.kittinunf.fuel.core.Request +import com.github.kittinunf.fuel.core.interceptors.cUrlLoggingRequestInterceptor +import com.github.kittinunf.fuel.gson.responseObject +import com.github.kittinunf.fuel.httpGet +import com.github.kittinunf.fuel.rx.rx_object +import com.google.gson.Gson +import kotlinx.coroutines.experimental.runBlocking +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Test +import java.io.File +import java.util.concurrent.CountDownLatch + +internal class FuelHttpUnitTest { + + @Test + fun whenMakingAsyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val latch = CountDownLatch(1) + + "http://httpbin.org/get".httpGet().response{ + request, response, result -> + + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + + latch.countDown() + } + + latch.await() + + } + + @Test + fun whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val (request, response, result) = "http://httpbin.org/get".httpGet().response() + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + + } + + @Test + fun whenMakingSyncHttpGetURLEncodedRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val (request, response, result) = + "https://jsonplaceholder.typicode.com/posts" + .httpGet(listOf("id" to "1")).response() + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + + } + + @Test + fun whenMakingAsyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val latch = CountDownLatch(1) + + Fuel.post("http://httpbin.org/post").response{ + request, response, result -> + + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + + latch.countDown() + } + + latch.await() + + } + + @Test + fun whenMakingSyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val (request, response, result) = Fuel.post("http://httpbin.org/post").response() + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + } + + @Test + fun whenMakingSyncHttpPostRequestwithBody_thenResponseNotNullAndErrorNullAndStatusCode200() { + + val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts") + .body("{ \"title\" : \"foo\",\"body\" : \"bar\",\"id\" : \"1\"}") + .response() + + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(201,response.statusCode) + } + + @Test + fun givenFuelInstance_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + FuelManager.instance.basePath = "http://httpbin.org" + FuelManager.instance.baseHeaders = mapOf("OS" to "macOS High Sierra") + + FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor()) + FuelManager.instance.addRequestInterceptor(tokenInterceptor()) + + + val (request, response, result) = "/get" + .httpGet().response() + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + } + + @Test + fun givenInterceptors_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { + + FuelManager.instance.basePath = "http://httpbin.org" + FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor()) + FuelManager.instance.addRequestInterceptor(tokenInterceptor()) + + val (request, response, result) = "/get" + .httpGet().response() + val (data, error) = result + + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + } + + @Test + fun whenDownloadFile_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() { + + Fuel.download("http://httpbin.org/bytes/32768").destination { response, url -> + File.createTempFile("temp", ".tmp") + }.response{ + request, response, result -> + + val (data, error) = result + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + } + } + + @Test + fun whenDownloadFilewithProgressHandler_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() { + + val (request, response, result) = Fuel.download("http://httpbin.org/bytes/327680") + .destination { response, url -> File.createTempFile("temp", ".tmp") + }.progress { readBytes, totalBytes -> + val progress = readBytes.toFloat() / totalBytes.toFloat() + }.response () + + val (data, error) = result + Assertions.assertNull(error) + Assertions.assertNotNull(data) + Assertions.assertEquals(200,response.statusCode) + + + } + + @Test + fun whenMakeGetRequest_thenDeserializePostwithGson() { + + val latch = CountDownLatch(1) + + "https://jsonplaceholder.typicode.com/posts/1".httpGet().responseObject { _,_, result -> + val post = result.component1() + Assertions.assertEquals(1, post?.userId) + latch.countDown() + } + + latch.await() + + } + + @Test + fun whenMakePOSTRequest_thenSerializePostwithGson() { + + val post = Post(1,1, "Lorem", "Lorem Ipse dolor sit amet") + + val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts") + .header("Content-Type" to "application/json") + .body(Gson().toJson(post).toString()) + .response() + + Assertions.assertEquals(201,response.statusCode) + + } + + @Test + fun whenMakeGETRequestWithRxJava_thenDeserializePostwithGson() { + + val latch = CountDownLatch(1) + + + "https://jsonplaceholder.typicode.com/posts?id=1" + .httpGet().rx_object(Post.Deserializer()).subscribe{ + res, throwable -> + + val post = res.component1() + Assertions.assertEquals(1, post?.get(0)?.userId) + latch.countDown() + } + + latch.await() + + } + + @Test + fun whenMakeGETRequestUsingCoroutines_thenResponseStatusCode200() { + + runBlocking { + val (request, response, result) = Fuel.get("http://httpbin.org/get").awaitStringResponse() + + result.fold({ data -> + Assertions.assertEquals(200, response.statusCode) + + }, { error -> }) + } + + } + + @Test + fun whenMakeGETRequestUsingCoroutines_thenDeserializeResponse() { + + + runBlocking { + Fuel.get("https://jsonplaceholder.typicode.com/posts?id=1").awaitObjectResult(Post.Deserializer()) + .fold({ data -> + Assertions.assertEquals(1, data.get(0).userId) + }, { error -> }) + } + + } + + @Test + fun whenMakeGETPostRequestUsingRoutingAPI_thenDeserializeResponse() { + + val latch = CountDownLatch(1) + + Fuel.request(PostRoutingAPI.posts("1",null)) + .responseObject(Post.Deserializer()) { + request, response, result -> + Assertions.assertEquals(1, result.component1()?.get(0)?.userId) + latch.countDown() + } + + latch.await() + } + + @Test + fun whenMakeGETCommentRequestUsingRoutingAPI_thenResponseStausCode200() { + + val latch = CountDownLatch(1) + + Fuel.request(PostRoutingAPI.comments("1",null)) + .responseString { request, response, result -> + Assertions.assertEquals(200, response.statusCode) + latch.countDown() + } + + latch.await() + } + + +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt similarity index 99% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt rename to core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt index 54fafdb3e1..d724933654 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesUnitTest.kt @@ -103,7 +103,7 @@ class CoroutinesTest { //given val job = launch(CommonPool) { while (isActive) { - println("is working") + //println("is working") } } diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt new file mode 100644 index 0000000000..469118f0f6 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTest.kt @@ -0,0 +1,191 @@ +package com.baeldung.kotlin + +import nl.komponents.kovenant.* +import nl.komponents.kovenant.Kovenant.deferred +import nl.komponents.kovenant.combine.and +import nl.komponents.kovenant.combine.combine +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import java.io.IOException +import java.util.* +import java.util.concurrent.TimeUnit + +class KovenantTest { + @Before + fun setupTestMode() { + Kovenant.testMode { error -> + println("An unexpected error occurred") + Assert.fail(error.message) + } + } + + @Test + fun testSuccessfulDeferred() { + val def = deferred() + Assert.assertFalse(def.promise.isDone()) + + def.resolve(1L) + Assert.assertTrue(def.promise.isDone()) + Assert.assertTrue(def.promise.isSuccess()) + Assert.assertFalse(def.promise.isFailure()) + } + + @Test + fun testFailedDeferred() { + val def = deferred() + Assert.assertFalse(def.promise.isDone()) + + def.reject(RuntimeException()) + Assert.assertTrue(def.promise.isDone()) + Assert.assertFalse(def.promise.isSuccess()) + Assert.assertTrue(def.promise.isFailure()) + } + + @Test + fun testResolveDeferredTwice() { + val def = deferred() + def.resolve(1L) + try { + def.resolve(1L) + } catch (e: AssertionError) { + // Expected. + // This is slightly unusual. The AssertionError comes from Assert.fail() from setupTestMode() + } + } + + @Test + fun testSuccessfulTask() { + val promise = task { 1L } + Assert.assertTrue(promise.isDone()) + Assert.assertTrue(promise.isSuccess()) + Assert.assertFalse(promise.isFailure()) + } + + @Test + fun testFailedTask() { + val promise = task { throw RuntimeException() } + Assert.assertTrue(promise.isDone()) + Assert.assertFalse(promise.isSuccess()) + Assert.assertTrue(promise.isFailure()) + } + + @Test + fun testCallbacks() { + val promise = task { 1L } + + promise.success { + println("This was a success") + Assert.assertEquals(1L, it) + } + + promise.fail { + println(it) + Assert.fail("This shouldn't happen") + } + + promise.always { + println("This always happens") + } + } + + @Test + fun testGetValues() { + val promise = task { 1L } + Assert.assertEquals(1L, promise.get()) + } + + @Test + fun testAllSucceed() { + val numbers = all( + task { 1L }, + task { 2L }, + task { 3L } + ) + + Assert.assertEquals(listOf(1L, 2L, 3L), numbers.get()) + } + + @Test + fun testOneFails() { + val runtimeException = RuntimeException() + + val numbers = all( + task { 1L }, + task { 2L }, + task { throw runtimeException } + ) + + Assert.assertEquals(runtimeException, numbers.getError()) + } + + @Test + fun testAnySucceeds() { + val promise = any( + task { + TimeUnit.SECONDS.sleep(3) + 1L + }, + task { + TimeUnit.SECONDS.sleep(2) + 2L + }, + task { + TimeUnit.SECONDS.sleep(1) + 3L + } + ) + + Assert.assertTrue(promise.isDone()) + Assert.assertTrue(promise.isSuccess()) + Assert.assertFalse(promise.isFailure()) + } + + @Test + fun testAllFails() { + val runtimeException = RuntimeException() + val ioException = IOException() + val illegalStateException = IllegalStateException() + val promise = any( + task { + TimeUnit.SECONDS.sleep(3) + throw runtimeException + }, + task { + TimeUnit.SECONDS.sleep(2) + throw ioException + }, + task { + TimeUnit.SECONDS.sleep(1) + throw illegalStateException + } + ) + + Assert.assertTrue(promise.isDone()) + Assert.assertFalse(promise.isSuccess()) + Assert.assertTrue(promise.isFailure()) + } + + @Test + fun testSimpleCombine() { + val promise = task { 1L } and task { "Hello" } + val result = promise.get() + + Assert.assertEquals(1L, result.first) + Assert.assertEquals("Hello", result.second) + } + + @Test + fun testLongerCombine() { + val promise = combine( + task { 1L }, + task { "Hello" }, + task { Currency.getInstance("USD") } + ) + val result = promise.get() + + Assert.assertEquals(1L, result.first) + Assert.assertEquals("Hello", result.second) + Assert.assertEquals(Currency.getInstance("USD"), result.third) + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt new file mode 100644 index 0000000000..e37d2cc2fa --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/KovenantTimeoutTest.kt @@ -0,0 +1,38 @@ +package com.baeldung.kotlin + +import nl.komponents.kovenant.Promise +import nl.komponents.kovenant.any +import nl.komponents.kovenant.task +import org.junit.Assert +import org.junit.Ignore +import org.junit.Test + +@Ignore +// Note that this can not run in the same test run if KovenantTest has already been executed +class KovenantTimeoutTest { + @Test + fun testTimeout() { + val promise = timedTask(1000) { "Hello" } + val result = promise.get() + Assert.assertEquals("Hello", result) + } + + @Test + fun testTimeoutExpired() { + val promise = timedTask(1000) { + Thread.sleep(3000) + "Hello" + } + val result = promise.get() + Assert.assertNull(result) + } + + fun timedTask(millis: Long, body: () -> T) : Promise> { + val timeoutTask = task { + Thread.sleep(millis) + null + } + val activeTask = task(body = body) + return any(activeTask, timeoutTask) + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StringConcatenationTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StringConcatenationTest.kt new file mode 100644 index 0000000000..9c371614a4 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StringConcatenationTest.kt @@ -0,0 +1,48 @@ +package com.baeldung.kotlin + +import org.junit.Test +import kotlin.test.assertEquals + +class StringConcatenationTest { + + @Test + fun givenTwoStrings_concatenateWithTemplates_thenEquals() { + val a = "Hello" + val b = "Baeldung" + val c = "$a $b" + + assertEquals("Hello Baeldung", c) + } + + @Test + fun givenTwoStrings_concatenateWithPlusOperator_thenEquals() { + val a = "Hello" + val b = "Baeldung" + val c = a + " " + b + + assertEquals("Hello Baeldung", c) + } + + @Test + fun givenTwoStrings_concatenateWithStringBuilder_thenEquals() { + val a = "Hello" + val b = "Baeldung" + + val builder = StringBuilder() + builder.append(a).append(" ").append(b) + + val c = builder.toString() + + assertEquals("Hello Baeldung", c) + } + + @Test + fun givenTwoStrings_concatenateWithPlusMethod_thenEquals() { + val a = "Hello" + val b = "Baeldung" + val c = a.plus(" ").plus(b) + + assertEquals("Hello Baeldung", c) + } + +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt new file mode 100644 index 0000000000..436dc9e2ba --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt @@ -0,0 +1,121 @@ +package com.baeldung.kotlin + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse + +class StructuralJumpUnitTest { + + @Test + fun givenLoop_whenBreak_thenComplete() { + var value = "" + for (i in "hello_world") { + if (i == '_') + break + value += i.toString() + } + assertEquals("hello", value) + } + @Test + fun givenLoop_whenBreakWithLabel_thenComplete() { + var value = "" + outer_loop@ for (i in 'a'..'d') { + for (j in 1..3) { + value += "" + i + j + if (i == 'b' && j == 1) + break@outer_loop + } + } + assertEquals("a1a2a3b1", value) + } + + @Test + fun givenLoop_whenContinue_thenComplete() { + var result = "" + for (i in "hello_world") { + if (i == '_') + continue + result += i + } + assertEquals("helloworld", result) + } + @Test + fun givenLoop_whenContinueWithLabel_thenComplete() { + var result = "" + outer_loop@ for (i in 'a'..'c') { + for (j in 1..3) { + if (i == 'b') + continue@outer_loop + result += "" + i + j + } + } + assertEquals("a1a2a3c1c2c3", result) + } + + @Test + fun givenLambda_whenReturn_thenComplete() { + var result = returnInLambda(); + assertEquals("hello", result) + } + + private fun returnInLambda(): String { + var result = "" + "hello_world".forEach { + // non-local return directly to the caller + if (it == '_') return result + result += it.toString() + } + //this line won't be reached + return result; + } + + @Test + fun givenLambda_whenReturnWithExplicitLabel_thenComplete() { + var result = "" + "hello_world".forEach lit@{ + if (it == '_') { + // local return to the caller of the lambda, i.e. the forEach loop + return@lit + } + result += it.toString() + } + assertEquals("helloworld", result) + } + + @Test + fun givenLambda_whenReturnWithImplicitLabel_thenComplete() { + var result = "" + "hello_world".forEach { + if (it == '_') { + // local return to the caller of the lambda, i.e. the forEach loop + return@forEach + } + result += it.toString() + } + assertEquals("helloworld", result) + } + + @Test + fun givenAnonymousFunction_return_thenComplete() { + var result = "" + "hello_world".forEach(fun(element) { + // local return to the caller of the anonymous fun, i.e. the forEach loop + if (element == '_') return + result += element.toString() + }) + assertEquals("helloworld", result) + } + + @Test + fun givenAnonymousFunction_returnToLabel_thenComplete() { + var result = "" + run loop@{ + "hello_world".forEach { + // non-local return from the lambda passed to run + if (it == '_') return@loop + result += it.toString() + } + } + assertEquals("hello", result) + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt new file mode 100644 index 0000000000..bdf44d3b49 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt @@ -0,0 +1,30 @@ +package com.baeldung.kotlin.gson + +import com.google.gson.Gson + +import org.junit.Assert +import org.junit.Test + +class GsonUnitTest { + + var gson = Gson() + + @Test + fun givenObject_thenGetJSONString() { + var jsonString = gson.toJson(TestModel(1,"Test")) + Assert.assertEquals(jsonString, "{\"id\":1,\"description\":\"Test\"}") + } + + @Test + fun givenJSONString_thenGetObject() { + var jsonString = "{\"id\":1,\"description\":\"Test\"}"; + var testModel = gson.fromJson(jsonString, TestModel::class.java) + Assert.assertEquals(testModel.id, 1) + Assert.assertEquals(testModel.description, "Test") + } + + data class TestModel( + val id: Int, + val description: String + ) +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt new file mode 100644 index 0000000000..7882d85b3c --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt @@ -0,0 +1,28 @@ +package com.baeldung.nested + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ComputerUnitTest { + + @Test + fun givenComputer_whenPowerOn_thenBlink() { + val computer = Computer("Desktop") + + assertThat(computer.powerOn()).isEqualTo("blinking Green") + } + + @Test + fun givenMotherboard_whenGetInfo_thenGetInstalledAndBuiltDetails() { + val motherBoard = Computer.MotherBoard("MotherBoard Inc.") + + assertThat(motherBoard.getInfo()).isEqualTo("Made by MotherBoard Inc. installed in China - 2018-05-23") + } + + @Test + fun givenHardDisk_whenGetInfo_thenGetComputerModelAndDiskSizeInGb() { + val hardDisk = Computer("Desktop").HardDisk(1000) + + assertThat(hardDisk.getInfo()).isEqualTo("Installed on Computer(model=Desktop) with 1000 GB") + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt new file mode 100644 index 0000000000..2956a35f8a --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt @@ -0,0 +1,55 @@ + +import org.junit.jupiter.api.Test +import java.util.concurrent.ThreadLocalRandom +import kotlin.test.assertTrue + +class RandomNumberTest { + + @Test + fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() { + val randomNumber = Math.random() + assertTrue { randomNumber >=0 } + assertTrue { randomNumber <= 1 } + } + + @Test + fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInDefaultRanges() { + val randomDouble = ThreadLocalRandom.current().nextDouble() + val randomInteger = ThreadLocalRandom.current().nextInt() + val randomLong = ThreadLocalRandom.current().nextLong() + assertTrue { randomDouble >= 0 } + assertTrue { randomDouble <= 1 } + assertTrue { randomInteger >= Integer.MIN_VALUE } + assertTrue { randomInteger <= Integer.MAX_VALUE } + assertTrue { randomLong >= Long.MIN_VALUE } + assertTrue { randomLong <= Long.MAX_VALUE } + } + + @Test + fun whenRandomNumberWithKotlinJSMath_thenResultIsBetween0And1() { + val randomDouble = Math.random() + assertTrue { randomDouble >=0 } + assertTrue { randomDouble <= 1 } + } + + @Test + fun whenRandomNumberWithKotlinNumberRange_thenResultInGivenRange() { + val randomInteger = (1..12).shuffled().first() + assertTrue { randomInteger >= 1 } + assertTrue { randomInteger <= 12 } + } + + @Test + fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInGivenRanges() { + val randomDouble = ThreadLocalRandom.current().nextDouble(1.0, 10.0) + val randomInteger = ThreadLocalRandom.current().nextInt(1, 10) + val randomLong = ThreadLocalRandom.current().nextLong(1, 10) + assertTrue { randomDouble >= 1 } + assertTrue { randomDouble <= 10 } + assertTrue { randomInteger >= 1 } + assertTrue { randomInteger <= 10 } + assertTrue { randomLong >= 1 } + assertTrue { randomLong <= 10 } + } + +} \ No newline at end of file diff --git a/core-kotlin/src/test/resources/Kotlin.out b/core-kotlin/src/test/resources/Kotlin.out new file mode 100644 index 0000000000..63d15d2528 --- /dev/null +++ b/core-kotlin/src/test/resources/Kotlin.out @@ -0,0 +1,2 @@ +Kotlin +Concise, Safe, Interoperable, Tool-friendly \ No newline at end of file diff --git a/couchbase/pom.xml b/couchbase/pom.xml index f6397fe309..4f0f8787ca 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -3,11 +3,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - couchbase-sdk + couchbase 0.1-SNAPSHOT jar couchbase - Couchbase SDK Tutorials + Couchbase Tutorials com.baeldung diff --git a/couchbase/src/main/resources/logback.xml b/couchbase/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/couchbase/src/main/resources/logback.xml +++ b/couchbase/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/couchbase/src/test/resources/logback.xml b/couchbase/src/test/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/couchbase/src/test/resources/logback.xml +++ b/couchbase/src/test/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java index e3179dca32..f435e41afa 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -57,7 +57,7 @@ public class BinaryTree { } public void delete(int value) { - deleteRecursive(root, value); + root = deleteRecursive(root, value); } private Node deleteRecursive(Node current, int value) { diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java similarity index 90% rename from data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java rename to data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java index 99e656fe28..f81247b74d 100644 --- a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java +++ b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.assertTrue; import org.junit.Test; -public class BinaryTreeTest { +public class BinaryTreeUnitTest { @Test public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() { @@ -70,6 +70,17 @@ public class BinaryTreeTest { assertEquals(initialSize, bt.getSize()); } + @Test + public void it_deletes_the_root() { + int value = 12; + BinaryTree bt = new BinaryTree(); + bt.add(value); + + assertTrue(bt.containsNode(value)); + bt.delete(value); + assertFalse(bt.containsNode(value)); + } + @Test public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() { diff --git a/data-structures/src/test/java/com/baeldung/trie/TrieTest.java b/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java similarity index 98% rename from data-structures/src/test/java/com/baeldung/trie/TrieTest.java rename to data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java index 6f7073651e..bf9555315c 100644 --- a/data-structures/src/test/java/com/baeldung/trie/TrieTest.java +++ b/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java @@ -6,7 +6,7 @@ import org.junit.jupiter.api.Assertions; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -public class TrieTest { +public class TrieUnitTest { @Test public void whenEmptyTrie_thenNoElements() { diff --git a/disruptor/pom.xml b/disruptor/pom.xml index 6f3a8d9bfd..c26dcc0cd4 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -36,22 +36,6 @@ - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - org.apache.maven.plugins maven-jar-plugin @@ -112,6 +96,7 @@ com.jolira onejar-maven-plugin + ${onejar-maven-plugin.version} @@ -138,6 +123,7 @@ 2.4.3 3.0.2 + 1.4.4 \ No newline at end of file diff --git a/drools/pom.xml b/drools/pom.xml index 631bc8c792..009ac8acec 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -48,12 +48,18 @@ poi-ooxml ${apache-poi-version} + + org.optaplanner + optaplanner-core + ${opta-planner-version} + 4.4.6 7.4.1.Final 3.13 + 7.10.0.Final diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java b/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java new file mode 100644 index 0000000000..7b2ba117a1 --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java @@ -0,0 +1,63 @@ +package com.baeldung.drools.optaplanner; + +import java.util.ArrayList; +import java.util.List; + +import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; +import org.optaplanner.core.api.domain.solution.PlanningScore; +import org.optaplanner.core.api.domain.solution.PlanningSolution; +import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty; +import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@PlanningSolution +public class CourseSchedule { + + Logger logger = LoggerFactory.getLogger("CourseSchedule"); + + private List roomList; + private List periodList; + private List lectureList; + private HardSoftScore score; + + public CourseSchedule(){ + roomList = new ArrayList<>(); + periodList = new ArrayList<>(); + lectureList = new ArrayList<>(); + } + + @ValueRangeProvider(id = "availableRooms") + @ProblemFactCollectionProperty + public List getRoomList() { + return roomList; + } + + @ValueRangeProvider(id = "availablePeriods") + @ProblemFactCollectionProperty + public List getPeriodList() { + return periodList; + } + + @PlanningEntityCollectionProperty + public List getLectureList() { + return lectureList; + } + + @PlanningScore + public HardSoftScore getScore() { + return score; + } + + public void setScore(HardSoftScore score) { + this.score = score; + } + + public void printCourseSchedule() { + lectureList.stream() + .map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString()) + .forEach(k -> logger.info(k)); + } + +} diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/Lecture.java b/drools/src/main/java/com/baeldung/drools/optaplanner/Lecture.java new file mode 100644 index 0000000000..193cdb08b1 --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/Lecture.java @@ -0,0 +1,30 @@ +package com.baeldung.drools.optaplanner; + +import org.optaplanner.core.api.domain.entity.PlanningEntity; +import org.optaplanner.core.api.domain.variable.PlanningVariable; + +@PlanningEntity +public class Lecture { + + private Integer roomNumber; + private Integer period; + + @PlanningVariable(valueRangeProviderRefs = {"availablePeriods"}) + public Integer getPeriod() { + return period; + } + + @PlanningVariable(valueRangeProviderRefs = {"availableRooms"}) + public Integer getRoomNumber() { + return roomNumber; + } + + public void setPeriod(Integer period) { + this.period = period; + } + + public void setRoomNumber(Integer roomNumber) { + this.roomNumber = roomNumber; + } + +} diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java b/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java new file mode 100644 index 0000000000..86501cdccd --- /dev/null +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java @@ -0,0 +1,32 @@ +package com.baeldung.drools.optaplanner; + +import java.util.HashSet; + +import org.optaplanner.core.api.score.Score; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; +import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator; + +public class ScoreCalculator implements EasyScoreCalculator { + + @Override + public Score calculateScore(CourseSchedule courseSchedule) { + int hardScore = 0; + int softScore = 0; + + HashSet occupiedRooms = new HashSet<>(); + for (Lecture lecture : courseSchedule.getLectureList()) { + if(lecture.getPeriod() != null && lecture.getRoomNumber() != null) { + String roomInUse = lecture.getPeriod().toString() + ":" + lecture.getRoomNumber().toString(); + if (occupiedRooms.contains(roomInUse)) { + hardScore += -1; + } else { + occupiedRooms.add(roomInUse); + } + } else { + hardScore += -1; + } + } + + return HardSoftScore.valueOf(hardScore, softScore); + } +} diff --git a/drools/src/main/resources/courseSchedule.drl b/drools/src/main/resources/courseSchedule.drl new file mode 100644 index 0000000000..35dd57df84 --- /dev/null +++ b/drools/src/main/resources/courseSchedule.drl @@ -0,0 +1,14 @@ +package com.baeldung.drools.optaplanner + +import com.baeldung.drools.optaplanner.Lecture; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder; + +global HardSoftScoreHolder scoreHolder; + +rule "noNullRoomPeriod" + when + Lecture( roomNumber == null ); + Lecture( period == null ); + then + scoreHolder.addHardConstraintMatch(kcontext, -1); +end \ No newline at end of file diff --git a/drools/src/main/resources/courseScheduleSolverConfigDrools.xml b/drools/src/main/resources/courseScheduleSolverConfigDrools.xml new file mode 100644 index 0000000000..7cf95fdcd3 --- /dev/null +++ b/drools/src/main/resources/courseScheduleSolverConfigDrools.xml @@ -0,0 +1,12 @@ + + + + + + courseSchedule.drl + + + + 10 + + \ No newline at end of file diff --git a/drools/src/main/resources/courseScheduleSolverConfiguration.xml b/drools/src/main/resources/courseScheduleSolverConfiguration.xml new file mode 100644 index 0000000000..dfedb8f2fd --- /dev/null +++ b/drools/src/main/resources/courseScheduleSolverConfiguration.xml @@ -0,0 +1,12 @@ + + + + + + com.baeldung.drools.optaplanner.ScoreCalculator + + + + 10 + + \ No newline at end of file diff --git a/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java b/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java new file mode 100644 index 0000000000..1880e30b86 --- /dev/null +++ b/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.drools.optaplanner; + +import java.util.Arrays; + +import org.junit.Assert; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.optaplanner.core.api.solver.Solver; +import org.optaplanner.core.api.solver.SolverFactory; + +public class OptaPlannerUnitTest { + + static CourseSchedule unsolvedCourseSchedule; + + @BeforeAll + public static void setUp() { + + unsolvedCourseSchedule = new CourseSchedule(); + + for(int i = 0; i < 10; i++){ + unsolvedCourseSchedule.getLectureList().add(new Lecture()); + } + + unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 })); + unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 })); + } + + @Test + public void test_whenCustomJavaSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(-4, solvedCourseSchedule.getScore().getHardScore()); + } + + @Test + public void test_whenDroolsSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(0, solvedCourseSchedule.getScore().getHardScore()); + } +} diff --git a/eclipse/formatter.xml b/eclipse/formatter.xml index 808f65cda9..6887946a4c 100644 --- a/eclipse/formatter.xml +++ b/eclipse/formatter.xml @@ -1,297 +1,5 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml index 44112a4396..6231030cec 100755 --- a/ejb/ejb-client/pom.xml +++ b/ejb/ejb-client/pom.xml @@ -16,7 +16,6 @@ org.wildfly wildfly-ejb-client-bom pom - import com.baeldung.ejb diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml index fffbbdb1da..dac2fefb84 100755 --- a/ejb/ejb-remote/pom.xml +++ b/ejb/ejb-remote/pom.xml @@ -15,7 +15,6 @@ javax javaee-api - ${javaee-api.version} provided diff --git a/ejb/ejb-session-beans/pom.xml b/ejb/ejb-session-beans/pom.xml index 14ab0790e7..da76169729 100644 --- a/ejb/ejb-session-beans/pom.xml +++ b/ejb/ejb-session-beans/pom.xml @@ -24,7 +24,6 @@ javax javaee-api - ${javaee-api.version} provided diff --git a/ejb/pom.xml b/ejb/pom.xml index a188d43272..4cb700d087 100755 --- a/ejb/pom.xml +++ b/ejb/pom.xml @@ -17,7 +17,6 @@ ejb-remote - ejb-client ejb-session-beans diff --git a/ejb/wildfly/pom.xml b/ejb/wildfly/pom.xml index 7159096f3c..53d10a90ed 100644 --- a/ejb/wildfly/pom.xml +++ b/ejb/wildfly/pom.xml @@ -2,9 +2,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.wildfly - wildfly-example + wildfly 0.0.1-SNAPSHOT pom + wildfly com.baeldung.ejb diff --git a/ejb/wildfly/wildfly-mdb/pom.xml b/ejb/wildfly/wildfly-mdb/pom.xml index 0b2ec7d5a3..186ddc50c0 100644 --- a/ejb/wildfly/wildfly-mdb/pom.xml +++ b/ejb/wildfly/wildfly-mdb/pom.xml @@ -1,8 +1,9 @@ 4.0.0 - widlfly-mdb - + wildfly-mdb + wildfly-mdb + com.baeldung.wildfly wildfly-example diff --git a/enterprise-patterns/README.md b/enterprise-patterns/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/enterprise-patterns/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java deleted file mode 100644 index d24c0a94b3..0000000000 --- a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.enterprise.patterns.front.controller.filters; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import java.io.IOException; - -public class AuditFilter extends BaseFilter { - @Override - public void doFilter( - ServletRequest request, - ServletResponse response, - FilterChain chain - ) throws IOException, ServletException { - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - HttpSession session = httpServletRequest.getSession(false); - if (session != null && session.getAttribute("username") != null) { - request.setAttribute("username", session.getAttribute("username")); - } - chain.doFilter(request, response); - } -} diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java deleted file mode 100644 index 0ae7cd73fd..0000000000 --- a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.enterprise.patterns.front.controller.filters; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.annotation.WebFilter; -import java.io.IOException; - -@WebFilter(servletNames = "front-controller") -public class VisitorCounterFilter extends BaseFilter { - private int counter; - - @Override - public void doFilter( - ServletRequest request, - ServletResponse response, - FilterChain chain - ) throws IOException, ServletException { - request.setAttribute("counter", ++counter); - chain.doFilter(request, response); - } -} diff --git a/enterprise-patterns/pom.xml b/enterprise-patterns/pom.xml deleted file mode 100644 index ffd0b66aad..0000000000 --- a/enterprise-patterns/pom.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - 4.0.0 - com.baeldung.enterprise.patterns - enterprise-patterns-parent - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - spring-dispatcher-servlet - - - diff --git a/ethereum/pom.xml b/ethereum/pom.xml index f07ed2c6a0..bd1bacb221 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -184,6 +184,7 @@ org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} org.apache.maven.plugins @@ -213,7 +214,7 @@ 3.3.1 5.0.5.RELEASE 1.5.6.RELEASE - 1.10.19 + 2.21.0 2.5.0 1.3 2.9.3 @@ -224,6 +225,7 @@ 4.12 1.2.3 1.7.25 + 2.0.4.RELEASE diff --git a/feign/pom.xml b/feign/pom.xml index 29c2a784bc..ea645383c1 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.feign - feign-client + feign + feign com.baeldung diff --git a/flyway-cdi-extension/README.md b/flyway-cdi-extension/README.md new file mode 100644 index 0000000000..3e03d5aee8 --- /dev/null +++ b/flyway-cdi-extension/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [CDI Portable Extension and Flyway](https://www.baeldung.com/cdi-portable-extension) diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml new file mode 100644 index 0000000000..c6ee26f783 --- /dev/null +++ b/flyway-cdi-extension/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + + com.baeldung + flyway-cdi-extension + 1.0-SNAPSHOT + + + 1.8 + 1.8 + + + + + javax.enterprise + cdi-api + 2.0.SP1 + + + org.jboss.weld.se + weld-se-core + 3.0.5.Final + runtime + + + org.flywaydb + flyway-core + 5.1.4 + + + org.apache.tomcat + tomcat-jdbc + 8.5.33 + + + javax.annotation + javax.annotation-api + 1.3.2 + + + com.h2database + h2 + 1.4.197 + runtime + + + + diff --git a/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java new file mode 100644 index 0000000000..a5019b82c1 --- /dev/null +++ b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java @@ -0,0 +1,74 @@ +package com.baeldung.cdi.extension; + +import org.apache.tomcat.jdbc.pool.DataSource; +import org.flywaydb.core.Flyway; + +import javax.annotation.sql.DataSourceDefinition; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.Any; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.literal.InjectLiteral; +import javax.enterprise.inject.spi.*; +import javax.enterprise.util.AnnotationLiteral; + + +/** + * Flyway is now under CDI container like: + * + * @ApplicationScoped + * @FlywayType public class Flyway{ + * @Inject setDataSource(DataSource dataSource){ + * //... + * } + * } + */ + +public class FlywayExtension implements Extension { + + DataSourceDefinition dataSourceDefinition = null; + + public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) { + bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName()); + } + + public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType patEvent) { + AnnotatedType at = patEvent.getAnnotatedType(); + dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class); + } + + public void processAnnotatedType(@Observes ProcessAnnotatedType patEvent) { + patEvent.configureAnnotatedType() + //Add Scope + .add(ApplicationScoped.Literal.INSTANCE) + //Add Qualifier + .add(new AnnotationLiteral() { + }) + //Decorate setDataSource(DataSource dataSource){} with @Inject + .filterMethods(annotatedMethod -> { + return annotatedMethod.getParameters().size() == 1 && + annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class); + }) + .findFirst().get().add(InjectLiteral.INSTANCE); + } + + void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) { + abdEvent.addBean() + .types(javax.sql.DataSource.class, DataSource.class) + .qualifiers(new AnnotationLiteral() {}, new AnnotationLiteral() {}) + .scope(ApplicationScoped.class) + .name(DataSource.class.getName()) + .beanClass(DataSource.class) + .createWith(creationalContext -> { + DataSource instance = new DataSource(); + instance.setUrl(dataSourceDefinition.url()); + instance.setDriverClassName(dataSourceDefinition.className()); + return instance; + }); + } + + void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) { + Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral() {}).get(); + flyway.migrate(); + } +} diff --git a/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayType.java b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayType.java new file mode 100644 index 0000000000..7c3a5affa6 --- /dev/null +++ b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayType.java @@ -0,0 +1,14 @@ +package com.baeldung.cdi.extension; + +import javax.inject.Qualifier; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target({FIELD, METHOD, PARAMETER, TYPE}) +@Qualifier +public @interface FlywayType { +} \ No newline at end of file diff --git a/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/MainApp.java b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/MainApp.java new file mode 100644 index 0000000000..1f6c5b43ba --- /dev/null +++ b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/MainApp.java @@ -0,0 +1,16 @@ +package com.baeldung.cdi.extension; + +import javax.annotation.sql.DataSourceDefinition; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.se.SeContainer; +import javax.enterprise.inject.se.SeContainerInitializer; + +@ApplicationScoped +@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb") +public class MainApp { + public static void main(String[] args) { + SeContainerInitializer initializer = SeContainerInitializer.newInstance(); + try (SeContainer container = initializer.initialize()) { + } + } +} \ No newline at end of file diff --git a/flyway-cdi-extension/src/main/resources/META-INF/beans.xml b/flyway-cdi-extension/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..44959bfa99 --- /dev/null +++ b/flyway-cdi-extension/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/flyway-cdi-extension/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/flyway-cdi-extension/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension new file mode 100644 index 0000000000..a82dc47714 --- /dev/null +++ b/flyway-cdi-extension/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension @@ -0,0 +1,2 @@ +com.baeldung.cdi.extension.FlywayExtension + diff --git a/flyway-cdi-extension/src/main/resources/db/migration/V1__Create_person_table.sql b/flyway-cdi-extension/src/main/resources/db/migration/V1__Create_person_table.sql new file mode 100644 index 0000000000..6bddc7689e --- /dev/null +++ b/flyway-cdi-extension/src/main/resources/db/migration/V1__Create_person_table.sql @@ -0,0 +1,4 @@ +create table PERSON ( + ID int not null, + NAME varchar(100) not null +); diff --git a/flyway-cdi-extension/src/main/resources/db/migration/V2__Add_people.sql b/flyway-cdi-extension/src/main/resources/db/migration/V2__Add_people.sql new file mode 100644 index 0000000000..d8f1d62667 --- /dev/null +++ b/flyway-cdi-extension/src/main/resources/db/migration/V2__Add_people.sql @@ -0,0 +1,3 @@ +insert into PERSON (ID, NAME) values (1, 'Axel'); +insert into PERSON (ID, NAME) values (2, 'Mr. Foo'); +insert into PERSON (ID, NAME) values (3, 'Ms. Bar'); diff --git a/flyway/pom.xml b/flyway/pom.xml index b1cc58af3d..353bbfb1ec 100644 --- a/flyway/pom.xml +++ b/flyway/pom.xml @@ -65,6 +65,7 @@ 5.0.2 5.0.2 + 1.4.195 diff --git a/flyway/src/main/resources/logback.xml b/flyway/src/main/resources/logback.xml index 7f4aa46e0d..56af2d397e 100644 --- a/flyway/src/main/resources/logback.xml +++ b/flyway/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java b/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java similarity index 98% rename from flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java rename to flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java index 5e96fff64d..bf30ce604d 100644 --- a/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java +++ b/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java @@ -16,7 +16,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) @ContextConfiguration(classes = FlywayCallbackTestConfig.class) -public class FlywayApplicationTest { +public class FlywayApplicationUnitTest { private Log log = LogFactory.getLog(getClass()); diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index b2f7cab355..db9ce2eac0 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -6,10 +6,11 @@ 4.0.0 com.baeldung - google_web_toolkit + google-web-toolkit war 1.0-SNAPSHOT - + google-web-toolkit + com.baeldung parent-modules diff --git a/gradle/junit5/build.gradle b/gradle/junit5/build.gradle new file mode 100644 index 0000000000..5f056d8c23 --- /dev/null +++ b/gradle/junit5/build.gradle @@ -0,0 +1,25 @@ +plugins { + // Apply the java-library plugin to add support for Java Library + id 'java-library' +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1' + + // Only necessary for JUnit 3 and 4 tests + testCompileOnly 'junit:junit:4.12' + testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.3.1' + +} + +repositories { + jcenter() +} + +test { + useJUnitPlatform { + includeTags 'fast' + excludeTags 'slow' + } +} \ No newline at end of file diff --git a/gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java b/gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java new file mode 100644 index 0000000000..4cf63642ee --- /dev/null +++ b/gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java @@ -0,0 +1,12 @@ +package com.example; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class CalculatorJUnit4Test { + @Test + public void testAdd() { + assertEquals(42, Integer.sum(19, 23)); + } +} diff --git a/gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java b/gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java new file mode 100644 index 0000000000..59fdb0f8ae --- /dev/null +++ b/gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java @@ -0,0 +1,36 @@ +package com.example; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test;; + +public class CalculatorJUnit5Test { + + @Tag("fast") + @Test + public void testAdd() { + assertEquals(42, Integer.sum(19, 23)); + } + + @Tag("slow") + @Test + public void testAddMaxInteger() { + assertEquals(2147483646, Integer.sum(2147183646, 300000)); + } + + @Tag("fast") + @Test + public void testAddZero() { + assertEquals(21, Integer.sum(21, 0)); + } + + @Tag("fast") + @Test + public void testDivide() { + assertThrows(ArithmeticException.class, () -> { + Integer.divideUnsigned(42, 0); + }); + } +} diff --git a/gradle/settings.gradle b/gradle/settings.gradle index 38704681bd..f1d64de58a 100644 --- a/gradle/settings.gradle +++ b/gradle/settings.gradle @@ -5,6 +5,6 @@ include 'greeting-library' include 'greeting-library-java' include 'greeter' include 'gradletaskdemo' - +include 'junit5' println 'This will be executed during the initialization phase.' diff --git a/grpc/pom.xml b/grpc/pom.xml index 218e2df008..949f26d376 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -1,11 +1,11 @@ 4.0.0 - grpc - grpc-demo + grpc 0.0.1-SNAPSHOT jar - + grpc + com.baeldung parent-modules diff --git a/gson/README.md b/gson/README.md index bedfbd206c..4122b21431 100644 --- a/gson/README.md +++ b/gson/README.md @@ -7,3 +7,4 @@ - [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide) - [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson) - [Exclude Fields from Serialization in Gson](http://www.baeldung.com/gson-exclude-fields-serialization) +- [Save Data to a JSON File with Gson](https://www.baeldung.com/gson-save-file) diff --git a/gson/pom.xml b/gson/pom.xml index 6e7779d26a..8222cb50e1 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -1,73 +1,73 @@ - 4.0.0 - com.baeldung - gson - 0.1-SNAPSHOT - gson + 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 + com.baeldung + gson + 0.1-SNAPSHOT + gson - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + - - - - org.projectlombok - lombok - ${lombok.version} - provided - - - joda-time - joda-time - ${joda-time.version} - - - commons-io - commons-io - ${commons-io.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - com.google.code.gson - gson - ${gson.version} - - + + + + org.projectlombok + lombok + ${lombok.version} + provided + + + joda-time + joda-time + ${joda-time.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + com.google.code.gson + gson + ${gson.version} + + - - gson - - - src/main/resources - true - - - + + gson + + + src/main/resources + true + + + - - - 2.8.0 - - 3.5 - 4.1 - 2.9.6 + + + 2.8.0 + + 3.5 + 4.1 + 2.9.6 1.16.10 - + \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/entities/Employee.java b/gson/src/main/java/org/baeldung/gson/entities/Employee.java new file mode 100644 index 0000000000..cedcd6572e --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Employee.java @@ -0,0 +1,36 @@ +package org.baeldung.gson.entities; + +public class Employee { + private int id; + private String name; + private String address; + + public Employee(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/entities/User.java b/gson/src/main/java/org/baeldung/gson/entities/User.java new file mode 100644 index 0000000000..b413f3300e --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/User.java @@ -0,0 +1,19 @@ +package org.baeldung.gson.entities; + +public class User { + + private int id; + private String name; + private transient String nationality; + + public User(int id, String name, String nationality) { + this.id = id; + this.name = name; + this.nationality = nationality; + } + + public User(int id, String name) { + this(id, name, null); + } + +} diff --git a/gson/src/main/java/org/baeldung/gson/serialization/HashMapDeserializer.java b/gson/src/main/java/org/baeldung/gson/serialization/HashMapDeserializer.java new file mode 100644 index 0000000000..bb73e32559 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serialization/HashMapDeserializer.java @@ -0,0 +1,66 @@ +package org.baeldung.gson.serialization; + +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +import org.baeldung.gson.entities.Employee; + +import com.google.gson.*; + +public class HashMapDeserializer implements JsonDeserializer> { + + @Override + public HashMap deserialize(JsonElement elem, Type type, JsonDeserializationContext context) throws JsonParseException { + HashMap map = new HashMap<>(); + for (Map.Entry entry : elem.getAsJsonObject().entrySet()) { + JsonElement jsonValue = entry.getValue(); + Object value = null; + if (jsonValue.isJsonPrimitive()) { + value = toPrimitive(jsonValue.getAsJsonPrimitive(), context); + } else { + value = context.deserialize(jsonValue, Employee.class); + } + map.put(entry.getKey(), value); + } + return map; + + } + + private Object toPrimitive(JsonPrimitive jsonValue, JsonDeserializationContext context) { + if (jsonValue.isBoolean()) + return jsonValue.getAsBoolean(); + else if (jsonValue.isString()) + return jsonValue.getAsString(); + else { + BigDecimal bigDec = jsonValue.getAsBigDecimal(); + Long l; + Integer i; + if ((i = toInteger(bigDec)) != null) { + return i; + } else if ((l = toLong(bigDec)) != null) { + return l; + } else { + return bigDec.doubleValue(); + } + } + } + + private Long toLong(BigDecimal val) { + try { + return val.toBigIntegerExact().longValue(); + } catch (ArithmeticException e) { + return null; + } + } + + private Integer toInteger(BigDecimal val) { + try { + return val.intValueExact(); + } catch (ArithmeticException e) { + return null; + } + } + +} diff --git a/gson/src/main/resources/logback.xml b/gson/src/main/resources/logback.xml index ec0dc2469a..7bd5154680 100644 --- a/gson/src/main/resources/logback.xml +++ b/gson/src/main/resources/logback.xml @@ -2,18 +2,18 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - + + - + - + \ No newline at end of file diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/HashMapDeserializationUnitTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/HashMapDeserializationUnitTest.java new file mode 100644 index 0000000000..6905ade0da --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/deserialization/HashMapDeserializationUnitTest.java @@ -0,0 +1,86 @@ +package org.baeldung.gson.deserialization; + +import java.lang.reflect.Type; +import java.util.HashMap; + +import org.baeldung.gson.entities.Employee; +import org.baeldung.gson.serialization.HashMapDeserializer; +import org.junit.Assert; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonSyntaxException; +import com.google.gson.internal.LinkedTreeMap; +import com.google.gson.reflect.TypeToken; + +public class HashMapDeserializationUnitTest { + + private static final Logger logger = LoggerFactory.getLogger(HashMapDeserializationUnitTest.class); + + @Test + public void whenUsingHashMapClass_thenShouldReturnMapWithDefaultClasses() { + + String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, " + + "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}"; + + Gson gson = new Gson(); + HashMap map = gson.fromJson(jsonString, HashMap.class); + + logger.info("The converted map: {}", map); + Assert.assertEquals(4, map.size()); + Assert.assertEquals(Double.class, map.get("employee.salary").getClass()); + Assert.assertEquals(LinkedTreeMap.class, map.get("employee").getClass()); + + } + + @Test(expected = JsonSyntaxException.class) + public void whenUsingJsonStringWithDuplicateKey_thenShouldThrowJsonSyntaxException() { + + String jsonString = "{'employee.name':'Bob', 'employee.name':'Jenny','employee.salary':10000, " + + "'employee.active':true, " + "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}"; + + Gson gson = new Gson(); + HashMap map = gson.fromJson(jsonString, HashMap.class); + + logger.info("The converted map: {}", map); + } + + @Test + public void whenUsingTypeToken_thenShouldReturnMapWithProperClass() { + + String jsonString = "{'Bob':{'id':10, 'name': 'Bob Willis', 'address':'UK'}," + + "'Jenny':{'id':10, 'name': 'Jenny McCarthy', 'address':'USA'}, " + + "'Steve':{'id':10, 'name': 'Steven Waugh', 'address':'Australia'}}"; + + Gson gson = new Gson(); + Type empMapType = new TypeToken>(){}.getType(); + HashMap nameEmployeeMap = gson.fromJson(jsonString, empMapType); + + logger.info("The converted map: {}", nameEmployeeMap); + Assert.assertEquals(3, nameEmployeeMap.size()); + Assert.assertEquals(Employee.class, nameEmployeeMap.get("Bob").getClass()); + } + + @Test + public void whenUsingCustomDeserializer_thenShouldReturnMapWithProperClass() { + + String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, " + + "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}"; + + Type type = new TypeToken>(){}.getType(); + Gson gson = new GsonBuilder() + .registerTypeAdapter(type, new HashMapDeserializer()) + .create(); + HashMap blendedMap = gson.fromJson(jsonString, type); + + logger.info("The converted map: {}", blendedMap); + Assert.assertEquals(4, blendedMap.size()); + Assert.assertEquals(Integer.class, blendedMap.get("employee.salary").getClass()); + Assert.assertEquals(Employee.class, blendedMap.get("employee").getClass()); + + } + +} diff --git a/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java b/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java new file mode 100644 index 0000000000..f6a8de080c --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java @@ -0,0 +1,43 @@ +package org.baeldung.gson.serialization.test; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.baeldung.gson.entities.User; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +@RunWith(Parameterized.class) +public class JsonFileUnitTest { + + @Parameter + public Object object; + + @Parameters + public static Object[] data() { + return new Object[] { 123.45, new User(1, "Tom", "American") }; + } + + @Test + public void givenProperData_whenStoredInFile_shouldSaveJsonSuccessfully() { + String filePath = "target/output.json"; + try (Writer writer = new FileWriter(filePath)) { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + gson.toJson(object, writer); + Assert.assertTrue(Files.exists(Paths.get(filePath))); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/gson/src/test/resources/logback-test.xml b/gson/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..7bd5154680 --- /dev/null +++ b/gson/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guava/README.md b/guava/README.md index bb4e225649..fe1a347d72 100644 --- a/guava/README.md +++ b/guava/README.md @@ -33,3 +33,4 @@ - [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream) - [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers) - [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) diff --git a/guava/src/main/resources/logback.xml b/guava/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/guava/src/main/resources/logback.xml +++ b/guava/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java b/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java new file mode 100644 index 0000000000..69a7505316 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java @@ -0,0 +1,30 @@ +package org.baeldung.guava; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.*; + +import java.util.Map; +import org.junit.Test; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; + +public class GuavaMapInitializeUnitTest { + + @Test + public void givenKeyValuesShoudInitializeMap() { + Map articles = ImmutableMap.of("Title", "My New Article", "Title2", "Second Article"); + + assertThat(articles.get("Title"), equalTo("My New Article")); + assertThat(articles.get("Title2"), equalTo("Second Article")); + + } + + + @Test + public void givenKeyValuesShouldCreateMutableMap() { + Map articles = Maps.newHashMap(ImmutableMap.of("Title", "My New Article", "Title2", "Second Article")); + + assertThat(articles.get("Title"), equalTo("My New Article")); + assertThat(articles.get("Title2"), equalTo("Second Article")); + } +} diff --git a/core-kotlin/kotlin-ktor/.gitignore b/guest/core-kotlin/.gitignore similarity index 100% rename from core-kotlin/kotlin-ktor/.gitignore rename to guest/core-kotlin/.gitignore diff --git a/guest/core-kotlin/pom.xml b/guest/core-kotlin/pom.xml new file mode 100644 index 0000000000..6b189143a4 --- /dev/null +++ b/guest/core-kotlin/pom.xml @@ -0,0 +1,199 @@ + + + 4.0.0 + core-kotlin + 1.0-SNAPSHOT + com.stackify + jar + + + + jcenter + http://jcenter.bintray.com + + + + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin-stdlib.version} + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin-stdlib.version} + + + org.jetbrains.kotlin + kotlin-test-junit + ${kotlin-test-junit.version} + test + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin-reflect.version} + + + org.jetbrains.spek + spek-api + 1.1.5 + test + + + org.jetbrains.spek + spek-subject-extension + 1.1.5 + test + + + org.jetbrains.spek + spek-junit-platform-engine + 1.1.5 + test + + + com.nhaarman + mockito-kotlin + ${mockito-kotlin.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + org.apache.maven.plugins + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + test + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin-maven-plugin.version} + provided + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin-maven-plugin.version} + + + compile + + compile + + + + ${project.basedir}/src/main/kotlin + + + + + test-compile + + test-compile + + + + ${project.basedir}/src/test/kotlin + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + default-compile + none + + + + default-testCompile + none + + + java-compile + compile + + compile + + + + + + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + junit5 + + integration-test + verify + + + + **/*Test5.java + + + + + + + + + + 2.22.0 + UTF-8 + 1.2.60 + 1.2.51 + 1.2.51 + 1.2.51 + 0.22.5 + 1.5.0 + 3.6.1 + 1.0.0 + 5.2.0 + 3.10.0 + 3.7.0 + + + diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt similarity index 88% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt index d1b3390544..073c4dd890 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt +++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt @@ -24,7 +24,7 @@ class ExceptionsTest { fun givenANullString_whenUsingElvisOperator_thenExceptionIsThrown() { val sampleString: String? = null - val length: Int = sampleString?.length ?: throw IllegalArgumentException("String must not be null") + sampleString?.length ?: throw IllegalArgumentException("String must not be null") } private fun funThrowingException(): Nothing { diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt rename to guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt diff --git a/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceTest.java b/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceUnitTest.java similarity index 98% rename from guest/log4j2-example/src/test/java/com/stackify/services/MyServiceTest.java rename to guest/log4j2-example/src/test/java/com/stackify/services/MyServiceUnitTest.java index 49e367e45b..bd08225be4 100644 --- a/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceTest.java +++ b/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceUnitTest.java @@ -18,9 +18,9 @@ import org.junit.Test; import com.stackify.models.User; import com.stackify.services.MyService; -public class MyServiceTest { +public class MyServiceUnitTest { - private static final Logger logger = LogManager.getLogger(MyServiceTest.class); + private static final Logger logger = LogManager.getLogger(MyServiceUnitTest.class); @Test public void testService() { diff --git a/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceUnitTest.java similarity index 98% rename from guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java rename to guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceUnitTest.java index 187b27e1df..a3051f7087 100644 --- a/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java +++ b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceUnitTest.java @@ -9,7 +9,7 @@ import com.stackify.models.Employee; import ch.qos.logback.classic.Level; -public class EmployeeServiceTest { +public class EmployeeServiceUnitTest { private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); private EmployeeService employeeService = new EmployeeService(); diff --git a/guest/remote-debugging/pom.xml b/guest/remote-debugging/pom.xml index 67fed3f1a1..974421de97 100644 --- a/guest/remote-debugging/pom.xml +++ b/guest/remote-debugging/pom.xml @@ -3,9 +3,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.stackify - java-remote-debugging + remote-debugging 0.0.1-SNAPSHOT war + remote-debugging org.springframework.boot diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml index 42543b5be0..c0ef451605 100644 --- a/guest/spring-mvc/pom.xml +++ b/guest/spring-mvc/pom.xml @@ -12,7 +12,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M5 + 2.0.0.RELEASE diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml index baca3bce85..8be42ba32b 100644 --- a/guest/spring-security/pom.xml +++ b/guest/spring-security/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M6 + 2.0.0.RELEASE diff --git a/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceTest.java b/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceLiveTest.java similarity index 95% rename from guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceTest.java rename to guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceLiveTest.java index 064951fbbe..be3992b7f7 100644 --- a/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceTest.java +++ b/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceLiveTest.java @@ -6,7 +6,7 @@ import io.restassured.RestAssured; import static io.restassured.RestAssured.*; import static org.hamcrest.CoreMatchers.*; -public class UserServiceTest { +public class UserServiceLiveTest { @Test public void whenAddUser_thenGetUserOk() { RestAssured.baseURI = "http://localhost:8080/rest-server"; diff --git a/hazelcast/README.md b/hazelcast/README.md index b90f66a8d0..7adb13f2af 100644 --- a/hazelcast/README.md +++ b/hazelcast/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Guide to Hazelcast with Java](http://www.baeldung.com/java-hazelcast) +- [Introduction to Hazelcast Jet](https://www.baeldung.com/hazelcast-jet) diff --git a/hazelcast/src/main/resources/logback.xml b/hazelcast/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/hazelcast/src/main/resources/logback.xml +++ b/hazelcast/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/hibernate5/README.md b/hibernate5/README.md index 1bce52bd5e..fbf46eed50 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -13,3 +13,7 @@ - [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) - [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) - [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking) +- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle) +- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) +- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) +- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy) diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 23d7d2e201..2212e736ab 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,5 +1,11 @@ package com.baeldung.hibernate; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import com.baeldung.hibernate.entities.DeptEmployee; import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; import com.baeldung.hibernate.pessimisticlocking.Individual; @@ -16,10 +22,30 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; -import java.util.Properties; +import com.baeldung.hibernate.pojo.Course; +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.OrderEntry; +import com.baeldung.hibernate.pojo.OrderEntryIdClass; +import com.baeldung.hibernate.pojo.OrderEntryPK; +import com.baeldung.hibernate.pojo.Person; +import com.baeldung.hibernate.pojo.Phone; +import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.baeldung.hibernate.pojo.Product; +import com.baeldung.hibernate.pojo.Student; +import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.User; +import com.baeldung.hibernate.pojo.UserProfile; +import com.baeldung.hibernate.pojo.inheritance.Animal; +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.MyProduct; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; +import com.baeldung.hibernate.pojo.inheritance.Vehicle; public class HibernateUtil { private static SessionFactory sessionFactory; @@ -72,6 +98,8 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java b/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..7a51009b62 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,65 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.*; + +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String designation; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getDesignation() { + return designation; + } + + public void setDesignation(String designation) { + this.designation = designation; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java new file mode 100644 index 0000000000..8b0a51858d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.joincolumn; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(name = "ZIP") + private String zipCode; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getZipCode() { + return zipCode; + } + + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java new file mode 100644 index 0000000000..a91fb3b4c9 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.joincolumn; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +@Entity +public class Email { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String address; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "employee_id") + private Employee employee; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java new file mode 100644 index 0000000000..3fbdb3820e --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java @@ -0,0 +1,36 @@ +package com.baeldung.hibernate.joincolumn; + +import java.util.List; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "employee") + private List emails; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public List getEmails() { + return emails; + } + + public void setEmails(List emails) { + this.emails = emails; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java new file mode 100644 index 0000000000..e5b9dc06bc --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.joincolumn; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.ManyToOne; + +@Entity +public class Office { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumns({ + @JoinColumn(name="ADDR_ID", referencedColumnName="ID"), + @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP") + }) + private Address address; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java new file mode 100644 index 0000000000..4e00be2b5c --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java @@ -0,0 +1,26 @@ +package com.baeldung.hibernate.lifecycle; + +import org.hibernate.EmptyInterceptor; +import org.hibernate.type.Type; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class DirtyDataInspector extends EmptyInterceptor { + private static final ArrayList dirtyEntities = new ArrayList<>(); + + @Override + public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { + dirtyEntities.add((FootballPlayer) entity); + return true; + } + + public static List getDirtyEntities() { + return dirtyEntities; + } + + public static void clearDirtyEntitites() { + dirtyEntities.clear(); + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java new file mode 100644 index 0000000000..49799a5292 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java @@ -0,0 +1,35 @@ +package com.baeldung.hibernate.lifecycle; + +import javax.persistence.*; + +@Entity +@Table(name = "Football_Player") +public class FootballPlayer { + @Id + @GeneratedValue + private long id; + + @Column + private String name; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}'; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java new file mode 100644 index 0000000000..a06685fb9c --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java @@ -0,0 +1,96 @@ +package com.baeldung.hibernate.lifecycle; + +import org.h2.tools.RunScript; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.engine.spi.EntityEntry; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; + +public class HibernateLifecycleUtil { + private static SessionFactory sessionFactory; + private static Connection connection; + + public static void init() throws Exception { + Properties hbConfigProp = getHibernateProperties(); + Class.forName(hbConfigProp.getProperty("hibernate.connection.driver_class")); + connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password")); + + try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql"); + InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) { + RunScript.execute(connection, h2InitReader); + } + + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(new DirtyDataInspector()).build(); + } + + public static void tearDown() throws Exception { + sessionFactory.close(); + connection.close(); + } + + public static SessionFactory getSessionFactory() { + return sessionFactory; + } + + private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(FootballPlayer.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getHibernateProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties).build(); + } + + private static Properties getHibernateProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } + + public static List getManagedEntities(Session session) { + Map.Entry[] entries = ((SessionImplementor) session).getPersistenceContext().reentrantSafeEntityEntries(); + return Arrays.stream(entries).map(e -> e.getValue()).collect(Collectors.toList()); + } + + public static Transaction startTransaction(Session s) { + Transaction tx = s.getTransaction(); + tx.begin(); + return tx; + } + + public static int queryCount(String query) throws Exception { + try (ResultSet rs = connection.createStatement().executeQuery(query)) { + rs.next(); + return rs.getInt(1); + } + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/CustomPhysicalNamingStrategy.java b/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/CustomPhysicalNamingStrategy.java new file mode 100644 index 0000000000..74bcb9e411 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/CustomPhysicalNamingStrategy.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.boot.model.naming.PhysicalNamingStrategy; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; + +public class CustomPhysicalNamingStrategy implements PhysicalNamingStrategy { + + @Override + public Identifier toPhysicalCatalogName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { + return convertToSnakeCase(identifier); + } + + @Override + public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { + return convertToSnakeCase(identifier); + } + + @Override + public Identifier toPhysicalSchemaName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { + return convertToSnakeCase(identifier); + } + + @Override + public Identifier toPhysicalSequenceName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { + return convertToSnakeCase(identifier); + } + + @Override + public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { + return convertToSnakeCase(identifier); + } + + private Identifier convertToSnakeCase(final Identifier identifier) { + if (identifier == null) { + return identifier; + } + + final String regex = "([a-z])([A-Z])"; + final String replacement = "$1_$2"; + final String newName = identifier.getText() + .replaceAll(regex, replacement) + .toLowerCase(); + return Identifier.toIdentifier(newName); + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/Customer.java b/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/Customer.java new file mode 100644 index 0000000000..b3fb3b32b6 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/Customer.java @@ -0,0 +1,56 @@ +package com.baeldung.hibernate.namingstrategy; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "Customers") +public class Customer { + + @Id + @GeneratedValue + private Long id; + + private String firstName; + + private String lastName; + + @Column(name = "email") + private String emailAddress; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java new file mode 100644 index 0000000000..607269a267 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +public class Result { + private String employeeName; + + private String departmentName; + + public Result(String employeeName, String departmentName) { + this.employeeName = employeeName; + this.departmentName = departmentName; + } + + public Result() { + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } + + public String getDepartmentName() { + return departmentName; + } + + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java index 90203d29ec..ccbdf80bf1 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java @@ -4,13 +4,23 @@ import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.SequenceGenerator; + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Parameter; @Entity public class User { @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-generator") - @SequenceGenerator(name = "sequence-generator", sequenceName = "user_sequence", initialValue = 4) + @GeneratedValue(generator = "sequence-generator") + @GenericGenerator( + name = "sequence-generator", + strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", + parameters = { + @Parameter(name = "sequence_name", value = "user_sequence"), + @Parameter(name = "initial_value", value = "4"), + @Parameter(name = "increment_size", value = "1") + } + ) private long userId; public long getUserId() { diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java new file mode 100644 index 0000000000..f146a8674e --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java @@ -0,0 +1,62 @@ +package com.baeldung.hibernate.proxy; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +@Entity +public class Company implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(name = "name") + private String name; + + @OneToMany + @JoinColumn(name = "workplace_id") + private Set employees = new HashSet<>(); + + public Company() { } + + public Company(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getEmployees() { + return this.employees; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Company company = (Company) o; + return Objects.equals(id, company.id) && + Objects.equals(name, company.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java new file mode 100644 index 0000000000..4bc0b8f25c --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java @@ -0,0 +1,69 @@ +package com.baeldung.hibernate.proxy; + +import org.hibernate.annotations.BatchSize; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Objects; + +@Entity +@BatchSize(size = 5) +public class Employee implements Serializable { + + @Id + @GeneratedValue (strategy = GenerationType.SEQUENCE) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "workplace_id") + private Company workplace; + + @Column(name = "first_name") + private String firstName; + + public Employee() { } + + public Employee(Company workplace, String firstName) { + this.workplace = workplace; + this.firstName = firstName; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Company getWorkplace() { + return workplace; + } + + public void setWorkplace(Company workplace) { + this.workplace = workplace; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Employee employee = (Employee) o; + return Objects.equals(id, employee.id) && + Objects.equals(workplace, employee.workplace) && + Objects.equals(firstName, employee.firstName); + } + + @Override + public int hashCode() { + return Objects.hash(id, workplace, firstName); + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java new file mode 100644 index 0000000000..37c083049f --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.proxy; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).build(); + } + return sessionFactory; + } + + private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addPackage("com.baeldung.hibernate.proxy"); + metadataSources.addAnnotatedClass(Company.class); + metadataSources.addAnnotatedClass(Employee.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/hibernate5/src/main/resources/logback.xml b/hibernate5/src/main/resources/logback.xml index d87a87bf53..7d900d8ea8 100644 --- a/hibernate5/src/main/resources/logback.xml +++ b/hibernate5/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java new file mode 100644 index 0000000000..29ae55b773 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java @@ -0,0 +1,77 @@ +package com.baeldung.hibernate; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.util.List; + +import com.baeldung.hibernate.entities.DeptEmployee; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.query.Query; +import org.hibernate.transform.Transformers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.baeldung.hibernate.entities.Department; +import com.baeldung.hibernate.pojo.Result; + +public class CustomClassIntegrationTest { + + private Session session; + + private Transaction transaction; + + @BeforeEach + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + session.createNativeQuery("delete from manager").executeUpdate(); + session.createNativeQuery("delete from department").executeUpdate(); + Department department = new Department("Sales"); + DeptEmployee employee = new DeptEmployee("John Smith", "001", department); + session.persist(department); + session.persist(employee); + transaction.commit(); + transaction = session.beginTransaction(); + } + + @Test + public void whenAllManagersAreSelected_ThenObjectGraphIsReturned() { + Query query = session.createQuery("from com.baeldung.hibernate.entities.DeptEmployee"); + List deptEmployees = query.list(); + DeptEmployee deptEmployee = deptEmployees.get(0); + assertEquals("John Smith", deptEmployee.getName()); + assertEquals("Sales", deptEmployee.getDepartment().getName()); + } + + @Test + public void whenIndividualPropertiesAreSelected_ThenObjectArrayIsReturned() { + Query query = session.createQuery("select m.name, m.department.name from com.baeldung.hibernate.entities.DeptEmployee m"); + List managers = query.list(); + Object[] manager = (Object[]) managers.get(0); + assertEquals("John Smith", manager[0]); + assertEquals("Sales", manager[1]); + } + + @Test + public void whenResultConstructorInSelect_ThenListOfResultIsReturned() { + Query query = session.createQuery("select new com.baeldung.hibernate.pojo.Result(m.name, m.department.name) " + + "from DeptEmployee m"); + List results = query.list(); + Result result = results.get(0); + assertEquals("John Smith", result.getEmployeeName()); + assertEquals("Sales", result.getDepartmentName()); + } + + @Test + public void whenResultTransformerOnQuery_ThenListOfResultIsReturned() { + Query query = session.createQuery("select m.name as employeeName, m.department.name as departmentName " + + "from com.baeldung.hibernate.entities.DeptEmployee m"); + query.setResultTransformer(Transformers.aliasToBean(Result.class)); + List results = query.list(); + Result result = results.get(0); + assertEquals("John Smith", result.getEmployeeName()); + assertEquals("Sales", result.getDepartmentName()); + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java index 0049f3a6bd..e18e989905 100644 --- a/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java +++ b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java @@ -58,5 +58,4 @@ public class HibernateInterceptorUnitTest { transaction.commit(); session.close(); } - } diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java new file mode 100644 index 0000000000..8246a2b01e --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.joincolumn; + +import com.baeldung.hibernate.HibernateUtil; +import java.io.IOException; +import org.hibernate.Session; +import org.hibernate.Transaction; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + + +public class JoinColumnIntegrationTest { + + private Session session; + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") + .openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenOfficeEntity_setAddress_shouldPersist() { + Office office = new Office(); + + Address address = new Address(); + address.setZipCode("11-111"); + office.setAddress(address); + + session.save(office); + session.flush(); + session.clear(); + } + + @Test + public void givenEmployeeEntity_setEmails_shouldPersist() { + Employee employee = new Employee(); + + Email email = new Email(); + email.setAddress("example@email.com"); + email.setEmployee(employee); + + session.save(employee); + session.flush(); + session.clear(); + } + +} \ No newline at end of file diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java new file mode 100644 index 0000000000..e682b46481 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java @@ -0,0 +1,164 @@ +package com.baeldung.hibernate.lifecycle; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.engine.spi.Status; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static com.baeldung.hibernate.lifecycle.DirtyDataInspector.getDirtyEntities; +import static com.baeldung.hibernate.lifecycle.HibernateLifecycleUtil.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class HibernateLifecycleUnitTest { + + @BeforeClass + public static void setup() throws Exception { + HibernateLifecycleUtil.init(); + + } + + @AfterClass + public static void tearDown() throws Exception { + HibernateLifecycleUtil.tearDown(); + } + + @Before + public void beforeMethod() { + DirtyDataInspector.clearDirtyEntitites(); + } + + @Test + public void whenEntityLoaded_thenEntityManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + assertThat(getManagedEntities(session)).isEmpty(); + + List players = session.createQuery("from FootballPlayer").getResultList(); + assertThat(getManagedEntities(session)).size().isEqualTo(3); + + assertThat(getDirtyEntities()).isEmpty(); + + FootballPlayer gigiBuffon = players.stream().filter(p -> p.getId() == 3).findFirst().get(); + + gigiBuffon.setName("Gianluigi Buffon"); + transaction.commit(); + + assertThat(getDirtyEntities()).size().isEqualTo(1); + assertThat(getDirtyEntities().get(0).getId()).isEqualTo(3); + assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Gianluigi Buffon"); + } + } + + @Test + public void whenDetached_thenNotTracked() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer cr7 = session.get(FootballPlayer.class, 1L); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + assertThat(getManagedEntities(session).get(0).getId()).isEqualTo(cr7.getId()); + + session.evict(cr7); + assertThat(getManagedEntities(session)).size().isEqualTo(0); + + cr7.setName("CR7"); + transaction.commit(); + + assertThat(getDirtyEntities()).isEmpty(); + } + } + + @Test + public void whenReattached_thenTrackedAgain() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer messi = session.get(FootballPlayer.class, 2L); + + session.evict(messi); + messi.setName("Leo Messi"); + transaction.commit(); + assertThat(getDirtyEntities()).isEmpty(); + + transaction = startTransaction(session); + session.update(messi); + transaction.commit(); + assertThat(getDirtyEntities()).size().isEqualTo(1); + assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Leo Messi"); + } + } + + @Test + public void givenNewEntityWithID_whenReattached_thenManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer gigi = new FootballPlayer(); + gigi.setId(3); + gigi.setName("Gigi the Legend"); + + session.update(gigi); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + + transaction.commit(); + assertThat(getDirtyEntities()).size().isEqualTo(1); + } + } + + @Test + public void givenTransientEntity_whenSave_thenManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer neymar = new FootballPlayer(); + neymar.setName("Neymar"); + + session.save(neymar); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + assertThat(neymar.getId()).isNotNull(); + + int count = queryCount("select count(*) from Football_Player where name='Neymar'"); + assertThat(count).isEqualTo(0); + + transaction.commit(); + + count = queryCount("select count(*) from Football_Player where name='Neymar'"); + assertThat(count).isEqualTo(1); + + transaction = startTransaction(session); + session.delete(neymar); + transaction.commit(); + } + } + + @Test() + public void whenDelete_thenMarkDeleted() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer neymar = new FootballPlayer(); + neymar.setName("Neymar"); + + session.save(neymar); + transaction.commit(); + + transaction = startTransaction(session); + session.delete(neymar); + assertThat(getManagedEntities(session).get(0).getStatus()).isEqualTo(Status.DELETED); + transaction.commit(); + } + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/namingstrategy/NamingStrategyLiveTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/namingstrategy/NamingStrategyLiveTest.java new file mode 100644 index 0000000000..0d6aed3370 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/namingstrategy/NamingStrategyLiveTest.java @@ -0,0 +1,75 @@ +package com.baeldung.hibernate.namingstrategy; + +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.Properties; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class NamingStrategyLiveTest { + + private Session session; + + @Before + public void init() { + try { + Configuration configuration = new Configuration(); + + Properties properties = new Properties(); + properties.load(Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream("hibernate-namingstrategy.properties")); + + configuration.setProperties(properties); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Customer.class); + + SessionFactory factory = metadataSources.buildMetadata() + .buildSessionFactory(); + + session = factory.openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close() { + if (session != null) + session.close(); + } + + @Test + public void testCustomPhysicalNamingStrategy() { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + customer.setEmailAddress("customer@example.com"); + + session.beginTransaction(); + + Long id = (Long) session.save(customer); + + session.flush(); + session.clear(); + + Object[] result = (Object[]) session.createNativeQuery("select c.first_name, c.last_name, c.email from customers c where c.id = :id") + .setParameter("id", id) + .getSingleResult(); + + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java new file mode 100644 index 0000000000..0a4caf032b --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java @@ -0,0 +1,156 @@ +package com.baeldung.hibernate.proxy; + +import org.hibernate.*; +import org.hibernate.proxy.HibernateProxy; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +import java.io.IOException; + +import static org.junit.Assert.fail; + +public class HibernateProxyUnitTest { + + private SessionFactory factory; + + private Session session; + + private Company workplace; + + private Employee albert; + + private Employee bob; + + private Employee charlotte; + + @Before + public void init(){ + try { + factory = HibernateUtil.getSessionFactory("hibernate.properties"); + session = factory.openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close(){ + if(session != null) { + session.close(); + } + } + + @Test + public void givenAnInexistentEmployeeId_whenUseGetMethod_thenReturnNull() { + Employee employee = session.get(Employee.class, 14L); + assertNull(employee); + } + + @Test(expected = ObjectNotFoundException.class) + public void givenAnNonExistentEmployeeId_whenUseLoadMethod_thenThrowObjectNotFoundException() { + Employee employee = session.load(Employee.class, 999L); + assertNotNull(employee); + employee.getFirstName(); + } + + @Test + public void givenAnNonExistentEmployeeId_whenUseLoadMethod_thenReturnAProxy() { + Employee employee = session.load(Employee.class, 14L); + assertNotNull(employee); + assertTrue(employee instanceof HibernateProxy); + } + + @Test + public void givenAnEmployeeFromACompany_whenUseLoadMethod_thenCompanyIsAProxy() { + Transaction tx = session.beginTransaction(); + + this.workplace = new Company("Bizco"); + session.save(workplace); + + this.albert = new Employee(workplace, "Albert"); + session.save(albert); + + session.flush(); + session.clear(); + + tx.commit(); + this.session = factory.openSession(); + + Employee proxyAlbert = session.load(Employee.class, albert.getId()); + assertTrue(proxyAlbert instanceof HibernateProxy); + + // with many-to-one lazy-loading, associations remain proxies + assertTrue(proxyAlbert.getWorkplace() instanceof HibernateProxy); + } + + @Test + public void givenACompanyWithEmployees_whenUseLoadMethod_thenEmployeesAreProxies() { + Transaction tx = session.beginTransaction(); + + this.workplace = new Company("Bizco"); + session.save(workplace); + + this.albert = new Employee(workplace, "Albert"); + session.save(albert); + + session.flush(); + session.clear(); + + tx.commit(); + this.session = factory.openSession(); + + Company proxyBizco = session.load(Company.class, workplace.getId()); + assertTrue(proxyBizco instanceof HibernateProxy); + + // with one-to-many, associations aren't proxies + assertFalse(proxyBizco.getEmployees().iterator().next() instanceof HibernateProxy); + } + + @Test + public void givenThreeEmployees_whenLoadThemWithBatch_thenReturnAllOfThemWithOneQuery() { + Transaction tx = session.beginTransaction(); + + //We are saving 3 entities with one flush + + this.workplace = new Company("Bizco"); + session.save(workplace); + + this.albert = new Employee(workplace, "Albert"); + session.save(albert); + + this.bob = new Employee(workplace, "Bob"); + session.save(bob); + + this.charlotte = new Employee(workplace, "Charlotte"); + session.save(charlotte); + + session.flush(); + session.clear(); + + tx.commit(); + session = factory.openSession(); + + Employee proxyAlbert = session.load(Employee.class, this.albert.getId()); + assertNotNull(proxyAlbert); + assertTrue(proxyAlbert instanceof HibernateProxy); + + Employee proxyBob = session.load(Employee.class, this.bob.getId()); + assertNotNull(proxyBob); + assertTrue(proxyBob instanceof HibernateProxy); + + Employee proxyCharlotte = session.load(Employee.class, this.charlotte.getId()); + assertNotNull(proxyCharlotte); + assertTrue(proxyCharlotte instanceof HibernateProxy); + + //Fetching from database 3 entities with one call + //Select from log: where employee0_.id in (?, ?, ?) + proxyAlbert.getFirstName(); + + assertEquals(proxyAlbert, this.albert); + assertEquals(proxyBob, this.bob); + assertEquals(proxyCharlotte, this.charlotte); + } +} diff --git a/hibernate5/src/test/resources/hibernate-lifecycle.properties b/hibernate5/src/test/resources/hibernate-lifecycle.properties new file mode 100644 index 0000000000..d043b624f2 --- /dev/null +++ b/hibernate5/src/test/resources/hibernate-lifecycle.properties @@ -0,0 +1,9 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:lifecycledb;DB_CLOSE_DELAY=-1; +hibernate.connection.username=sa +hibernate.connection.password= +hibernate.connection.autocommit=true + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=validate \ No newline at end of file diff --git a/hibernate5/src/test/resources/hibernate-namingstrategy.properties b/hibernate5/src/test/resources/hibernate-namingstrategy.properties new file mode 100644 index 0000000000..f75a35bdfe --- /dev/null +++ b/hibernate5/src/test/resources/hibernate-namingstrategy.properties @@ -0,0 +1,10 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.dialect=org.hibernate.dialect.H2Dialect + +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.physical_naming_strategy=com.baeldung.hibernate.namingstrategy.CustomPhysicalNamingStrategy +hibernate.implicit_naming_strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl \ No newline at end of file diff --git a/hibernate5/src/test/resources/lifecycle-init.sql b/hibernate5/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/hibernate5/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/httpclient/src/main/resources/logback.xml b/httpclient/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/httpclient/src/main/resources/logback.xml +++ b/httpclient/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/influxdb/src/test/resources/logback.xml b/influxdb/src/test/resources/logback.xml index f8ebaf1ebd..7d900d8ea8 100644 --- a/influxdb/src/test/resources/logback.xml +++ b/influxdb/src/test/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/intelliJ/README.md b/intelliJ/README.md new file mode 100644 index 0000000000..d45bd0cee5 --- /dev/null +++ b/intelliJ/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Writing IntelliJ IDEA Plugins](https://www.baeldung.com/intellij-new-custom-plugin) diff --git a/intelliJ/stackoverflow-plugin/resources/META-INF/plugin.xml b/intelliJ/stackoverflow-plugin/resources/META-INF/plugin.xml new file mode 100644 index 0000000000..5931f10f05 --- /dev/null +++ b/intelliJ/stackoverflow-plugin/resources/META-INF/plugin.xml @@ -0,0 +1,62 @@ + + com.baeldung.intellij.stackoverflowplugin + Stack Overflow Plugin for IntelliJ + 1.0 + Baeldung + + + + +

  • 1.0 - Initial release
  • + + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/intelliJ/stackoverflow-plugin/resources/so-icon-16x16.png b/intelliJ/stackoverflow-plugin/resources/so-icon-16x16.png new file mode 100644 index 0000000000..fddbb6b899 Binary files /dev/null and b/intelliJ/stackoverflow-plugin/resources/so-icon-16x16.png differ diff --git a/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/AskQuestionAction.java b/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/AskQuestionAction.java new file mode 100644 index 0000000000..ee122fc2d8 --- /dev/null +++ b/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/AskQuestionAction.java @@ -0,0 +1,14 @@ +package com.baeldung.intellij.stackoverflowplugin; + +import com.intellij.ide.BrowserUtil; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; + +public class AskQuestionAction extends AnAction +{ + @Override + public void actionPerformed(AnActionEvent e) + { + BrowserUtil.browse("https://stackoverflow.com/questions/ask"); + } +} diff --git a/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/SearchAction.java b/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/SearchAction.java new file mode 100644 index 0000000000..c1f910c656 --- /dev/null +++ b/intelliJ/stackoverflow-plugin/src/com/baeldung/intellij/stackoverflowplugin/SearchAction.java @@ -0,0 +1,58 @@ +package com.baeldung.intellij.stackoverflowplugin; + +import com.intellij.ide.BrowserUtil; +import com.intellij.lang.Language; +import com.intellij.openapi.actionSystem.ActionManager; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.editor.CaretModel; +import com.intellij.openapi.editor.Editor; +import com.intellij.psi.PsiFile; + +public class SearchAction extends AnAction +{ + /** + * Convert selected text to a URL friendly string. + * @param e + */ + @Override + public void actionPerformed(AnActionEvent e) + { + final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR); + CaretModel caretModel = editor.getCaretModel(); + + // For searches from the editor, we should also get file type information + // to help add scope to the search using the Stack overflow search syntax. + // + // https://stackoverflow.com/help/searching + + String languageTag = ""; + PsiFile file = e.getData(CommonDataKeys.PSI_FILE); + if(file != null) + { + Language lang = e.getData(CommonDataKeys.PSI_FILE).getLanguage(); + languageTag = "+[" + lang.getDisplayName().toLowerCase() + "]"; + } + + // The update method below is only called periodically so need + // to be careful to check for selected text + if(caretModel.getCurrentCaret().hasSelection()) + { + String query = caretModel.getCurrentCaret().getSelectedText().replace(' ', '+') + languageTag; + BrowserUtil.browse("https://stackoverflow.com/search?q=" + query); + } + } + + /** + * Only make this action visible when text is selected. + * @param e + */ + @Override + public void update(AnActionEvent e) + { + final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR); + CaretModel caretModel = editor.getCaretModel(); + e.getPresentation().setEnabledAndVisible(caretModel.getCurrentCaret().hasSelection()); + } +} diff --git a/jackson/pom.xml b/jackson/pom.xml index 3fcbca1ebd..e941ababc5 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung jackson 0.1-SNAPSHOT jackson @@ -119,17 +118,16 @@ - 2.9.4 + 2.9.7 - 19.0 - 3.5 - 2.9.6 - 2.8.0 - 4.1 + 3.8 + 2.10 + 2.8.5 + 4.2 - 3.0.1 - 3.6.1 + 3.1.1 + 3.11.0 diff --git a/jackson/src/main/java/com/baeldung/jackson/xmlToJson/Color.java b/jackson/src/main/java/com/baeldung/jackson/xmlToJson/Color.java new file mode 100644 index 0000000000..19dabb30b0 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/xmlToJson/Color.java @@ -0,0 +1,5 @@ +package com.baeldung.jackson.xmlToJson; + +public enum Color { + PINK, BLUE, YELLOW, RED; +} diff --git a/jackson/src/main/java/com/baeldung/jackson/xmlToJson/Flower.java b/jackson/src/main/java/com/baeldung/jackson/xmlToJson/Flower.java new file mode 100644 index 0000000000..0b1ee1b16a --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/xmlToJson/Flower.java @@ -0,0 +1,42 @@ +package com.baeldung.jackson.xmlToJson; + +public class Flower { + + private String name; + + private Color color; + + private Integer petals; + + public Flower() { } + + public Flower(String name, Color color, Integer petals) { + this.name = name; + this.color = color; + this.petals = petals; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Color getColor() { + return color; + } + + public void setColor(Color color) { + this.color = color; + } + + public Integer getPetals() { + return petals; + } + + public void setPetals(Integer petals) { + this.petals = petals; + } +} diff --git a/jackson/src/main/resources/logback.xml b/jackson/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/jackson/src/main/resources/logback.xml +++ b/jackson/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/jackson/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java new file mode 100644 index 0000000000..295bb9d6e8 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.jackson.xmlToJson; + + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import org.junit.Test; + +import static org.junit.Assert.*; + +import java.io.IOException; + +public class XmlToJsonUnitTest { + + @Test + public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() { + String flowerXML = "PoppyRED9"; + + try { + XmlMapper xmlMapper = new XmlMapper(); + Flower poppy = xmlMapper.readValue(flowerXML, Flower.class); + + assertEquals(poppy.getName(), "Poppy"); + assertEquals(poppy.getColor(), Color.RED); + assertEquals(poppy.getPetals(), new Integer(9)); + + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(poppy); + + assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}"); + System.out.println(json); + } catch(IOException e) { + e.printStackTrace(); + } + } + + @Test + public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() { + String flowerXML = "PoppyRED9"; + + try { + XmlMapper xmlMapper = new XmlMapper(); + JsonNode node = xmlMapper.readTree(flowerXML.getBytes()); + + ObjectMapper jsonMapper = new ObjectMapper(); + String json = jsonMapper.writeValueAsString(node); + + System.out.println(json); + + assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}"); + } catch(IOException e) { + e.printStackTrace(); + } + } +} diff --git a/java-dates/.gitignore b/java-dates/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/java-dates/.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-dates/README.md b/java-dates/README.md new file mode 100644 index 0000000000..54843f90ee --- /dev/null +++ b/java-dates/README.md @@ -0,0 +1,24 @@ +========= + +## Java Dates Cookbooks and Examples + +### Relevant Articles: +- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster) +- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) +- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) +- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) +- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions) +- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) +- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) +- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8) +- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time) +- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) +- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime) +- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) +- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day) +- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar) +- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) +- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) +- [Calculate Age in Java](http://www.baeldung.com/java-get-age) +- [Increment Date in Java](http://www.baeldung.com/java-increment-date) +- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date) \ No newline at end of file diff --git a/java-dates/pom.xml b/java-dates/pom.xml new file mode 100644 index 0000000000..2618fad1d4 --- /dev/null +++ b/java-dates/pom.xml @@ -0,0 +1,86 @@ + + 4.0.0 + com.baeldung + java-dates + 0.1.0-SNAPSHOT + jar + java-dates + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj.version} + test + + + joda-time + joda-time + ${joda-time.version} + + + com.darwinsys + hirondelle-date4j + RELEASE + test + + + + + java-dates + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + 3.5 + 1.16.12 + 2.10 + + 3.6.1 + 1.9 + 1.9 + + diff --git a/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java b/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java new file mode 100644 index 0000000000..c031c97dec --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java @@ -0,0 +1,32 @@ +package com.baeldung.date; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.Period; +import java.util.Date; +import org.joda.time.Years; + +public class AgeCalculator { + + public int calculateAge(LocalDate birthDate, LocalDate currentDate) { + // validate inputs ... + return Period.between(birthDate, currentDate) + .getYears(); + } + + public int calculateAgeWithJodaTime(org.joda.time.LocalDate birthDate, org.joda.time.LocalDate currentDate) { + // validate inputs ... + Years age = Years.yearsBetween(birthDate, currentDate); + return age.getYears(); + } + + public int calculateAgeWithJava7(Date birthDate, Date currentDate) { + // validate inputs ... + DateFormat formatter = new SimpleDateFormat("yyyyMMdd"); + int d1 = Integer.parseInt(formatter.format(birthDate)); + int d2 = Integer.parseInt(formatter.format(currentDate)); + int age = (d2 - d1) / 10000; + return age; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/date/DateWithoutTime.java b/java-dates/src/main/java/com/baeldung/date/DateWithoutTime.java similarity index 100% rename from core-java/src/main/java/com/baeldung/date/DateWithoutTime.java rename to java-dates/src/main/java/com/baeldung/date/DateWithoutTime.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/AddHoursToDate.java b/java-dates/src/main/java/com/baeldung/datetime/AddHoursToDate.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/AddHoursToDate.java rename to java-dates/src/main/java/com/baeldung/datetime/AddHoursToDate.java diff --git a/core-java/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java b/java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java rename to java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java diff --git a/core-java/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java b/java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java rename to java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java diff --git a/core-java/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java b/java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java rename to java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java diff --git a/core-java/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java b/java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java rename to java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/README.md b/java-dates/src/main/java/com/baeldung/datetime/README.md similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/README.md rename to java-dates/src/main/java/com/baeldung/datetime/README.md diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java b/java-dates/src/main/java/com/baeldung/datetime/UseDuration.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java rename to java-dates/src/main/java/com/baeldung/datetime/UseDuration.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java rename to java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseLocalTime.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java rename to java-dates/src/main/java/com/baeldung/datetime/UseLocalTime.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java b/java-dates/src/main/java/com/baeldung/datetime/UsePeriod.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java rename to java-dates/src/main/java/com/baeldung/datetime/UsePeriod.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java b/java-dates/src/main/java/com/baeldung/datetime/UseToInstant.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java rename to java-dates/src/main/java/com/baeldung/datetime/UseToInstant.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java rename to java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java diff --git a/core-java/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java b/java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java similarity index 100% rename from core-java/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java rename to java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java b/java-dates/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java rename to java-dates/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java diff --git a/core-java/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java b/java-dates/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java rename to java-dates/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java b/java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java rename to java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java b/java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java rename to java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java b/java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java rename to java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java b/java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java rename to java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/time/TimeApi.java b/java-dates/src/main/java/com/baeldung/java9/time/TimeApi.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/time/TimeApi.java rename to java-dates/src/main/java/com/baeldung/java9/time/TimeApi.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java rename to java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java b/java-dates/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java new file mode 100644 index 0000000000..ccae942dcc --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java @@ -0,0 +1,6 @@ +package com.baeldung.regexp.datepattern.optmization; + +public class OptimizedMatcher { + + +} diff --git a/core-java-8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/java-dates/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java rename to java-dates/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java diff --git a/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java b/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java rename to java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java diff --git a/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java b/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java rename to java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java diff --git a/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java b/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java similarity index 100% rename from core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java rename to java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java diff --git a/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java b/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java similarity index 100% rename from core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java rename to java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java diff --git a/jsonb/src/main/resources/logback.xml b/java-dates/src/main/resources/logback.xml similarity index 100% rename from jsonb/src/main/resources/logback.xml rename to java-dates/src/main/resources/logback.xml diff --git a/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java b/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java new file mode 100644 index 0000000000..dcd261337c --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.date; + +import static org.junit.Assert.assertEquals; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Date; +import org.junit.jupiter.api.Test; + +public class AgeCalculatorUnitTest { + AgeCalculator ageCalculator = new AgeCalculator(); + + @Test + public void givenLocalDate_whenCalculateAge_thenOk() { + assertEquals(10, ageCalculator.calculateAge(LocalDate.of(2008, 5, 20), LocalDate.of(2018, 9, 20))); + } + + @Test + public void givenJodaTime_whenCalculateAge_thenOk() { + assertEquals(10, ageCalculator.calculateAgeWithJodaTime(new org.joda.time.LocalDate(2008, 5, 20), new org.joda.time.LocalDate(2018, 9, 20))); + } + + @Test + public void givenDate_whenCalculateAge_thenOk() throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); + Date birthDate = sdf.parse("2008-05-20"); + Date currentDate = sdf.parse("2018-09-20"); + assertEquals(10, ageCalculator.calculateAgeWithJava7(birthDate, currentDate)); + } + +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java similarity index 74% rename from libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java rename to java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java index 545009a2a9..92da22cc95 100644 --- a/libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java @@ -5,7 +5,9 @@ import org.junit.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Duration; +import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.Period; import java.util.Date; import java.util.Locale; import java.util.TimeZone; @@ -26,6 +28,17 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } + + @Test + public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() { + LocalDate now = LocalDate.now(); + LocalDate sixDaysBehind = now.minusDays(6); + + Period period = Period.between(now, sixDaysBehind); + int diff = period.getDays(); + + assertEquals(diff, 6); + } @Test public void givenTwoDateTimesInJava8_whenDifferentiating_thenWeGetSix() { @@ -38,6 +51,15 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } + @Test + public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() { + LocalDateTime ldt = LocalDateTime.now(); + ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal")); + ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore")).minusDays(6); + long diff = ChronoUnit.DAYS.between(sixDaysBehind, now); + assertEquals(diff, 6); + } + @Test public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() { org.joda.time.LocalDate now = org.joda.time.LocalDate.now(); diff --git a/core-java/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java rename to java-dates/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/date/StringToDateUnitTest.java b/java-dates/src/test/java/com/baeldung/date/StringToDateUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/date/StringToDateUnitTest.java rename to java-dates/src/test/java/com/baeldung/date/StringToDateUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java b/java-dates/src/test/java/com/baeldung/dateapi/ConversionExample.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java rename to java-dates/src/test/java/com/baeldung/dateapi/ConversionExample.java diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java b/java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java rename to java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java b/java-dates/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java rename to java-dates/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java rename to java-dates/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/DateTimeFormatterUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/DateTimeFormatterUnitTest.java new file mode 100644 index 0000000000..f3b2b11893 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/DateTimeFormatterUnitTest.java @@ -0,0 +1,158 @@ +package com.baeldung.datetime; + +import org.junit.Assert; +import org.junit.Test; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.time.format.FormatStyle; +import java.time.temporal.ChronoUnit; +import java.util.Locale; +import java.util.TimeZone; + +public class DateTimeFormatterUnitTest { + + @Test + public void givenDefaultUsLocaleAndDateTimeAndPattern_whenFormatWithDifferentLocales_thenGettingLocalizedDateTimes() { + Locale.setDefault(Locale.US); + LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500); + String pattern = "dd-MMMM-yyyy HH:mm:ss.SSS"; + + DateTimeFormatter defaultTimeFormatter = DateTimeFormatter.ofPattern(pattern); + DateTimeFormatter plTimeFormatter = DateTimeFormatter.ofPattern(pattern, new Locale("pl", "PL")); + DateTimeFormatter deTimeFormatter = DateTimeFormatter.ofPattern(pattern).withLocale(Locale.GERMANY); + + Assert.assertEquals("01-January-2018 10:15:50.000", defaultTimeFormatter.format(localDateTime)); + Assert.assertEquals("01-stycznia-2018 10:15:50.000", plTimeFormatter.format(localDateTime)); + Assert.assertEquals("01-Januar-2018 10:15:50.000", deTimeFormatter.format(localDateTime)); + } + + @Test + public void givenDateTimeAndTimeZone_whenFormatWithDifferentLocales_thenGettingLocalizedZonedDateTimes() { + Locale.setDefault(Locale.US); + LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500); + ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId(); + + DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL); + DateTimeFormatter frLocalizedFormatter = + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE); + String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone)); + String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone)); + + Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime); + Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime); + } + + @Test + public void shouldPrintFormattedDate() { + String europeanDatePattern = "dd.MM.yyyy"; + DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern(europeanDatePattern); + LocalDate summerDay = LocalDate.of(2016, 7, 31); + Assert.assertEquals("31.07.2016", europeanDateFormatter.format(summerDay)); + } + + @Test + public void shouldPrintFormattedTime24() { + String timeColonPattern = "HH:mm:ss"; + DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); + LocalTime colonTime = LocalTime.of(17, 35, 50); + Assert.assertEquals("17:35:50", timeColonFormatter.format(colonTime)); + } + + @Test + public void shouldPrintFormattedTimeWithMillis() { + String timeColonPattern = "HH:mm:ss SSS"; + DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); + LocalTime colonTime = LocalTime.of(17, 35, 50).plus(329, ChronoUnit.MILLIS); + Assert.assertEquals("17:35:50 329", timeColonFormatter.format(colonTime)); + } + + @Test + public void shouldPrintFormattedTimePM() { + String timeColonPattern = "hh:mm:ss a"; + DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); + LocalTime colonTime = LocalTime.of(17, 35, 50); + Assert.assertEquals("05:35:50 PM", timeColonFormatter.format(colonTime)); + } + + @Test + public void shouldPrintFormattedUTCRelatedZonedDateTime() { + String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z"; + DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern); + LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15); + Assert.assertEquals("31.07.2016 14:15 UTC-04:00", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("UTC-4")))); + } + + @Test + public void shouldPrintFormattedNewYorkZonedDateTime() { + String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z"; + DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern); + LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15); + Assert.assertEquals("31.07.2016 14:15 EDT", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("America/New_York")))); + } + + @Test + public void shouldPrintStyledDate() { + LocalDate anotherSummerDay = LocalDate.of(2016, 8, 23); + Assert.assertEquals("Tuesday, August 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).format(anotherSummerDay)); + Assert.assertEquals("August 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).format(anotherSummerDay)); + Assert.assertEquals("Aug 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(anotherSummerDay)); + Assert.assertEquals("8/23/16", DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(anotherSummerDay)); + } + + @Test + public void shouldPrintStyledDateTime() { + LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45); + Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + } + + @Test + public void shouldPrintFormattedDateTimeWithPredefined() { + Assert.assertEquals("2018-03-09", DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.of(2018, 3, 9))); + Assert.assertEquals("2018-03-09-03:00", DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); + Assert.assertEquals("Fri, 9 Mar 2018 00:00:00 -0300", DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); + } + + @Test + public void shouldParseDateTime() { + Assert.assertEquals(LocalDate.of(2018, 3, 12), LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09")).plusDays(3)); + } + + @Test + public void shouldParseFormatStyleFull() { + ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET")); + Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9)); + } + + @Test + public void shouldParseDateWithCustomFormatter() { + DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); + Assert.assertFalse(LocalDate.from(europeanDateFormatter.parse("15.08.2014")).isLeapYear()); + } + + @Test + public void shouldParseTimeWithCustomFormatter() { + DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm:ss a"); + Assert.assertTrue(LocalTime.from(timeFormatter.parse("12:25:30 AM")).isBefore(LocalTime.NOON)); + } + + @Test + public void shouldParseZonedDateTimeWithCustomFormatter() { + DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z"); + Assert.assertEquals(7200, ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15 GMT+02:00")).getOffset().getTotalSeconds()); + } + + @Test(expected = DateTimeParseException.class) + public void shouldExpectAnExceptionIfDateTimeStringNotMatchPattern() { + DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z"); + ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15")); + } +} diff --git a/core-java/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java b/java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java rename to java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java b/java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java rename to java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java b/java-dates/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java similarity index 100% rename from core-java/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java rename to java-dates/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java b/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterUnitTest.java similarity index 98% rename from core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java rename to java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterUnitTest.java index ab69bba359..f7f07500f1 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java +++ b/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterUnitTest.java @@ -20,7 +20,7 @@ import com.baeldung.java9.datetime.DateToLocalDateConverter; * @author abialas * */ -public class DateToLocalDateConverterTest { +public class DateToLocalDateConverterUnitTest { @Test public void shouldReturn10thNovember2010WhenConvertViaInstant() { diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java b/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterUnitTest.java similarity index 98% rename from core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java rename to java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterUnitTest.java index 97c70ee5ac..9ad29ea673 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java +++ b/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterUnitTest.java @@ -20,7 +20,7 @@ import com.baeldung.java9.datetime.DateToLocalDateTimeConverter; * @author abialas * */ -public class DateToLocalDateTimeConverterTest { +public class DateToLocalDateTimeConverterUnitTest { @Test public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java b/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterUnitTest.java similarity index 97% rename from core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java rename to java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterUnitTest.java index 2c6898381f..e5a541c546 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java +++ b/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterUnitTest.java @@ -18,7 +18,7 @@ import org.junit.Test; * @author abialas * */ -public class LocalDateTimeToDateConverterTest { +public class LocalDateTimeToDateConverterUnitTest { @Test public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java b/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterUnitTest.java similarity index 96% rename from core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java rename to java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterUnitTest.java index 7f20d5d2d2..4e4dd20f2f 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java +++ b/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterUnitTest.java @@ -18,7 +18,7 @@ import org.junit.Test; * @author abialas * */ -public class LocalDateToDateConverterTest { +public class LocalDateToDateConverterUnitTest { @Test public void shouldReturn10thNovember2010WhenConvertViaInstant() { diff --git a/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java b/java-dates/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java similarity index 98% rename from core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java rename to java-dates/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java index a024db19a8..8813870c2b 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java +++ b/java-dates/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java @@ -8,7 +8,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; import org.junit.Test; -public class TimeApiTest { +public class TimeApiUnitTest { @Test public void givenGetDatesBetweenWithUsingJava7_WhenStartEndDate_thenDatesList() { diff --git a/libraries/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java rename to java-dates/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java b/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java similarity index 100% rename from core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java rename to java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java diff --git a/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java b/java-dates/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java rename to java-dates/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java b/java-dates/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java rename to java-dates/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java rename to java-dates/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java new file mode 100644 index 0000000000..355fef35c6 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.zoneddatetime; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.logging.Logger; + +import org.junit.Test; + +public class ZonedDateTimeUnitTest { + + private static final Logger log = Logger.getLogger(ZonedDateTimeUnitTest.class.getName()); + + @Test + public void testZonedDateTimeToString() { + + ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(ZoneId.of("UTC")); + ZonedDateTime zonedDateTimeOf = ZonedDateTime.of(2018, 01, 01, 0, 0, 0, 0, ZoneId.of("UTC")); + + LocalDateTime localDateTime = LocalDateTime.now(); + ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("UTC")); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy - hh:mm:ss Z"); + String formattedString = zonedDateTime.format(formatter); + + DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy - hh:mm:ss z"); + String formattedString2 = zonedDateTime.format(formatter2); + + log.info(formattedString); + log.info(formattedString2); + + } + + @Test + public void testZonedDateTimeFromString() { + + ZonedDateTime zonedDateTime = ZonedDateTime.parse("2011-12-03T10:15:30+01:00", DateTimeFormatter.ISO_ZONED_DATE_TIME); + + log.info(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME)); + } + +} diff --git a/out/production/main151/com/baeldung/.gitignore b/java-dates/src/test/resources/.gitignore similarity index 100% rename from out/production/main151/com/baeldung/.gitignore rename to java-dates/src/test/resources/.gitignore diff --git a/java-difference-date/README.md b/java-difference-date/README.md deleted file mode 100644 index 2a024c27a2..0000000000 --- a/java-difference-date/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Relevant articles: - -- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) -- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) -- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) \ No newline at end of file diff --git a/java-difference-date/pom.xml b/java-difference-date/pom.xml deleted file mode 100644 index 8c87afc0a2..0000000000 --- a/java-difference-date/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - 4.0.0 - com.baeldung - java-difference-date - 0.0.1-SNAPSHOT - jar - java-difference-date - Difference between two dates in java - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - joda-time - joda-time - ${joda-time.version} - - - com.darwinsys - hirondelle-date4j - ${hirondelle-date4j.version} - - - - - 2.9.9 - 1.5.1 - - - diff --git a/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java b/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java deleted file mode 100644 index 4203f7ef38..0000000000 --- a/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung; - -import org.joda.time.DateTime; -import org.junit.Test; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.Duration; -import java.time.ZonedDateTime; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertEquals; - -public class DateDiffTest { - @Test - public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException { - SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); - Date firstDate = sdf.parse("06/24/2017"); - Date secondDate = sdf.parse("06/30/2017"); - - long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime()); - long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS); - - assertEquals(diff, 6); - } - - @Test - public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() { - ZonedDateTime now = ZonedDateTime.now(); - ZonedDateTime sixDaysBehind = now.minusDays(6); - - Duration duration = Duration.between(now, sixDaysBehind); - long diff = Math.abs(duration.toDays()); - - assertEquals(diff, 6); - } - - @Test - public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() { - DateTime now = DateTime.now(); - DateTime sixDaysBehind = now.minusDays(6); - - org.joda.time.Duration duration = new org.joda.time.Duration(now, sixDaysBehind); - long diff = Math.abs(duration.getStandardDays()); - - assertEquals(diff, 6); - } - - @Test - public void givenTwoDatesInDate4j_whenDifferentiating_thenWeGetSix() { - hirondelle.date4j.DateTime now = hirondelle.date4j.DateTime.now(TimeZone.getDefault()); - hirondelle.date4j.DateTime sixDaysBehind = now.minusDays(6); - - long diff = Math.abs(now.numDaysFrom(sixDaysBehind)); - - assertEquals(diff, 6); - } -} \ No newline at end of file diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml index 5490cd40f7..3d235e10a8 100644 --- a/java-ee-8-security-api/pom.xml +++ b/java-ee-8-security-api/pom.xml @@ -3,11 +3,16 @@ 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 - com.baeldung java-ee-8-security-api 1.0-SNAPSHOT pom + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + @@ -53,10 +58,6 @@ - 1.8 - 1.8 - UTF-8 - 9080 9443 diff --git a/java-numbers/pom.xml b/java-numbers/pom.xml index a9fb556517..bb63c8cfe1 100644 --- a/java-numbers/pom.xml +++ b/java-numbers/pom.xml @@ -83,23 +83,6 @@
    - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - - org.apache.maven.plugins maven-javadoc-plugin @@ -156,7 +139,7 @@ 1.19 1.19 - 2.19.1 + 2.21.0 3.0.0-M1 3.0.2 diff --git a/java-numbers/src/main/java/com/baeldung/maths/BigDecimalDemo.java b/java-numbers/src/main/java/com/baeldung/maths/BigDecimalDemo.java new file mode 100644 index 0000000000..7de0197769 --- /dev/null +++ b/java-numbers/src/main/java/com/baeldung/maths/BigDecimalDemo.java @@ -0,0 +1,29 @@ +package com.baeldung.maths; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +public class BigDecimalDemo { + + /** Calculate total amount to be paid for an item rounded to cents.. + * @param quantity + * @param unitPrice + * @param discountRate + * @param taxRate + * @return + */ + public static BigDecimal calculateTotalAmount(BigDecimal quantity, + BigDecimal unitPrice, BigDecimal discountRate, BigDecimal taxRate) { + BigDecimal amount = quantity.multiply(unitPrice); + BigDecimal discount = amount.multiply(discountRate); + BigDecimal discountedAmount = amount.subtract(discount); + BigDecimal tax = discountedAmount.multiply(taxRate); + BigDecimal total = discountedAmount.add(tax); + + // round to 2 decimal places using HALF_EVEN + BigDecimal roundedTotal = total.setScale(2, RoundingMode.HALF_EVEN); + + return roundedTotal; + } + +} diff --git a/java-numbers/src/main/java/com/baeldung/percentage/PercentageCalculator.java b/java-numbers/src/main/java/com/baeldung/percentage/PercentageCalculator.java new file mode 100644 index 0000000000..e74de2cc67 --- /dev/null +++ b/java-numbers/src/main/java/com/baeldung/percentage/PercentageCalculator.java @@ -0,0 +1,21 @@ +package com.baeldung.percentage; + +import java.util.Scanner; + +public class PercentageCalculator { + + public double calculatePercentage(double obtained,double total){ + return obtained*100/total; + } + + public static void main(String[] args) { + PercentageCalculator pc = new PercentageCalculator(); + Scanner in = new Scanner(System.in); + System.out.println("Enter obtained marks:"); + double obtained = in.nextDouble(); + System.out.println("Enter total marks:"); + double total =in.nextDouble(); + System.out.println("Percentage obtained :"+pc.calculatePercentage(obtained,total)); + } + +} diff --git a/java-numbers/src/main/resources/logback.xml b/java-numbers/src/main/resources/logback.xml index f8ebaf1ebd..7d900d8ea8 100644 --- a/java-numbers/src/main/resources/logback.xml +++ b/java-numbers/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/java-numbers/src/test/java/com/baeldung/maths/BigDecimalDemoUnitTest.java b/java-numbers/src/test/java/com/baeldung/maths/BigDecimalDemoUnitTest.java new file mode 100644 index 0000000000..2bf9872bec --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/maths/BigDecimalDemoUnitTest.java @@ -0,0 +1,120 @@ +package com.baeldung.maths; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.math.RoundingMode; +import java.util.Random; + +import org.junit.jupiter.api.Test; + +public class BigDecimalDemoUnitTest { + + @Test + public void whenBigDecimalCreated_thenValueMatches() { + BigDecimal bdFromString = new BigDecimal("0.1"); + BigDecimal bdFromCharArray = new BigDecimal( + new char[] { '3', '.', '1', '6', '1', '5' }); + BigDecimal bdlFromInt = new BigDecimal(42); + BigDecimal bdFromLong = new BigDecimal(123412345678901L); + BigInteger bigInteger = BigInteger.probablePrime(100, new Random()); + BigDecimal bdFromBigInteger = new BigDecimal(bigInteger); + + assertEquals("0.1", bdFromString.toString()); + assertEquals("3.1615", bdFromCharArray.toString()); + assertEquals("42", bdlFromInt.toString()); + assertEquals("123412345678901", bdFromLong.toString()); + assertEquals(bigInteger.toString(), bdFromBigInteger.toString()); + } + + @Test + public void whenBigDecimalCreatedFromDouble_thenValueMayNotMatch() { + BigDecimal bdFromDouble = new BigDecimal(0.1d); + assertNotEquals("0.1", bdFromDouble.toString()); + } + + @Test + public void whenBigDecimalCreatedUsingValueOf_thenValueMatches() { + BigDecimal bdFromLong1 = BigDecimal.valueOf(123412345678901L); + BigDecimal bdFromLong2 = BigDecimal.valueOf(123412345678901L, 2); + BigDecimal bdFromDouble = BigDecimal.valueOf(0.1d); + + assertEquals("123412345678901", bdFromLong1.toString()); + assertEquals("1234123456789.01", bdFromLong2.toString()); + assertEquals("0.1", bdFromDouble.toString()); + } + + @Test + public void whenEqualsCalled_thenSizeAndScaleMatched() { + BigDecimal bd1 = new BigDecimal("1.0"); + BigDecimal bd2 = new BigDecimal("1.00"); + + assertFalse(bd1.equals(bd2)); + } + + @Test + public void whenComparingBigDecimals_thenExpectedResult() { + BigDecimal bd1 = new BigDecimal("1.0"); + BigDecimal bd2 = new BigDecimal("1.00"); + BigDecimal bd3 = new BigDecimal("2.0"); + + assertTrue(bd1.compareTo(bd3) < 0); + assertTrue(bd3.compareTo(bd1) > 0); + assertTrue(bd1.compareTo(bd2) == 0); + assertTrue(bd1.compareTo(bd3) <= 0); + assertTrue(bd1.compareTo(bd2) >= 0); + assertTrue(bd1.compareTo(bd3) != 0); + } + + @Test + public void whenPerformingArithmetic_thenExpectedResult() { + BigDecimal bd1 = new BigDecimal("4.0"); + BigDecimal bd2 = new BigDecimal("2.0"); + + BigDecimal sum = bd1.add(bd2); + BigDecimal difference = bd1.subtract(bd2); + BigDecimal quotient = bd1.divide(bd2); + BigDecimal product = bd1.multiply(bd2); + + assertTrue(sum.compareTo(new BigDecimal("6.0")) == 0); + assertTrue(difference.compareTo(new BigDecimal("2.0")) == 0); + assertTrue(quotient.compareTo(new BigDecimal("2.0")) == 0); + assertTrue(product.compareTo(new BigDecimal("8.0")) == 0); + } + + @Test + public void whenGettingAttributes_thenExpectedResult() { + BigDecimal bd = new BigDecimal("-12345.6789"); + + assertEquals(9, bd.precision()); + assertEquals(4, bd.scale()); + assertEquals(-1, bd.signum()); + } + + @Test + public void whenRoundingDecimal_thenExpectedResult() { + BigDecimal bd = new BigDecimal("2.5"); + // Round to 1 digit using HALF_EVEN + BigDecimal rounded = bd + .round(new MathContext(1, RoundingMode.HALF_EVEN)); + + assertEquals("2", rounded.toString()); + } + + @Test + public void givenPurchaseTxn_whenCalculatingTotalAmount_thenExpectedResult() { + BigDecimal quantity = new BigDecimal("4.5"); + BigDecimal unitPrice = new BigDecimal("2.69"); + BigDecimal discountRate = new BigDecimal("0.10"); + BigDecimal taxRate = new BigDecimal("0.0725"); + + BigDecimal amountToBePaid = BigDecimalDemo + .calculateTotalAmount(quantity, unitPrice, discountRate, taxRate); + assertEquals("11.68", amountToBePaid.toString()); + } +} diff --git a/java-numbers/src/test/java/com/baeldung/maths/BigIntegerDemoUnitTest.java b/java-numbers/src/test/java/com/baeldung/maths/BigIntegerDemoUnitTest.java new file mode 100644 index 0000000000..3537ccb3a3 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/maths/BigIntegerDemoUnitTest.java @@ -0,0 +1,128 @@ +package com.baeldung.maths; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.math.BigInteger; +import java.util.Random; + +import org.junit.jupiter.api.Test; + +public class BigIntegerDemoUnitTest { + + @Test + public void whenBigIntegerCreatedFromConstructor_thenExpectedResult() { + BigInteger biFromString = new BigInteger("1234567890987654321"); + BigInteger biFromByteArray = new BigInteger( + new byte[] { 64, 64, 64, 64, 64, 64 }); + BigInteger biFromSignMagnitude = new BigInteger(-1, + new byte[] { 64, 64, 64, 64, 64, 64 }); + + assertEquals("1234567890987654321", biFromString.toString()); + assertEquals("70644700037184", biFromByteArray.toString()); + assertEquals("-70644700037184", biFromSignMagnitude.toString()); + } + + @Test + public void whenLongConvertedToBigInteger_thenValueMatches() { + BigInteger bi = BigInteger.valueOf(2305843009213693951L); + + assertEquals("2305843009213693951", bi.toString()); + } + + @Test + public void givenBigIntegers_whentCompared_thenExpectedResult() { + BigInteger i = new BigInteger("123456789012345678901234567890"); + BigInteger j = new BigInteger("123456789012345678901234567891"); + BigInteger k = new BigInteger("123456789012345678901234567892"); + + assertTrue(i.compareTo(i) == 0); + assertTrue(j.compareTo(i) > 0); + assertTrue(j.compareTo(k) < 0); + } + + @Test + public void givenBigIntegers_whenPerformingArithmetic_thenExpectedResult() { + BigInteger i = new BigInteger("4"); + BigInteger j = new BigInteger("2"); + + BigInteger sum = i.add(j); + BigInteger difference = i.subtract(j); + BigInteger quotient = i.divide(j); + BigInteger product = i.multiply(j); + + assertEquals(new BigInteger("6"), sum); + assertEquals(new BigInteger("2"), difference); + assertEquals(new BigInteger("2"), quotient); + assertEquals(new BigInteger("8"), product); + } + + @Test + public void givenBigIntegers_whenPerformingBitOperations_thenExpectedResult() { + BigInteger i = new BigInteger("17"); + BigInteger j = new BigInteger("7"); + + BigInteger and = i.and(j); + BigInteger or = i.or(j); + BigInteger not = j.not(); + BigInteger xor = i.xor(j); + BigInteger andNot = i.andNot(j); + BigInteger shiftLeft = i.shiftLeft(1); + BigInteger shiftRight = i.shiftRight(1); + + assertEquals(new BigInteger("1"), and); + assertEquals(new BigInteger("23"), or); + assertEquals(new BigInteger("-8"), not); + assertEquals(new BigInteger("22"), xor); + assertEquals(new BigInteger("16"), andNot); + assertEquals(new BigInteger("34"), shiftLeft); + assertEquals(new BigInteger("8"), shiftRight); + } + + @Test + public void givenBigIntegers_whenPerformingBitManipulations_thenExpectedResult() { + BigInteger i = new BigInteger("1018"); + + int bitCount = i.bitCount(); + int bitLength = i.bitLength(); + int getLowestSetBit = i.getLowestSetBit(); + boolean testBit3 = i.testBit(3); + BigInteger setBit12 = i.setBit(12); + BigInteger flipBit0 = i.flipBit(0); + BigInteger clearBit3 = i.clearBit(3); + + assertEquals(8, bitCount); + assertEquals(10, bitLength); + assertEquals(1, getLowestSetBit); + assertEquals(true, testBit3); + assertEquals(new BigInteger("5114"), setBit12); + assertEquals(new BigInteger("1019"), flipBit0); + assertEquals(new BigInteger("1010"), clearBit3); + } + + @Test + public void givenBigIntegers_whenModularCalculation_thenExpectedResult() { + BigInteger i = new BigInteger("31"); + BigInteger j = new BigInteger("24"); + BigInteger k = new BigInteger("16"); + + BigInteger gcd = j.gcd(k); + BigInteger multiplyAndmod = j.multiply(k) + .mod(i); + BigInteger modInverse = j.modInverse(i); + BigInteger modPow = j.modPow(k, i); + + assertEquals(new BigInteger("8"), gcd); + assertEquals(new BigInteger("12"), multiplyAndmod); + assertEquals(new BigInteger("22"), modInverse); + assertEquals(new BigInteger("7"), modPow); + } + + @Test + public void givenBigIntegers_whenPrimeOperations_thenExpectedResult() { + BigInteger i = BigInteger.probablePrime(100, new Random()); + + boolean isProbablePrime = i.isProbablePrime(1000); + assertEquals(true, isProbablePrime); + } +} diff --git a/java-numbers/src/test/java/com/baeldung/maths/MathSinUnitTest.java b/java-numbers/src/test/java/com/baeldung/maths/MathSinUnitTest.java new file mode 100644 index 0000000000..111b2f4465 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/maths/MathSinUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.maths; + +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Test; + +public class MathSinUnitTest { + + @Test + public void givenAnAngleInDegrees_whenUsingToRadians_thenResultIsInRadians() { + double angleInDegrees = 30; + double sinForDegrees = Math.sin(Math.toRadians(angleInDegrees)); // 0.5 + + double thirtyDegreesInRadians = 1/6 * Math.PI; + double sinForRadians = Math.sin(thirtyDegreesInRadians); // 0.5 + + assertTrue(sinForDegrees == sinForRadians); + } + +} diff --git a/java-numbers/src/test/java/com/baeldung/percentage/PercentageCalculatorUnitTest.java b/java-numbers/src/test/java/com/baeldung/percentage/PercentageCalculatorUnitTest.java new file mode 100644 index 0000000000..202d4f8112 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/percentage/PercentageCalculatorUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.percentage; + +import org.junit.Assert; +import org.junit.Test; + +public class PercentageCalculatorUnitTest { + private PercentageCalculator pc = new PercentageCalculator(); + + @Test + public void whenPass2Integers_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected", + 50.0,pc.calculatePercentage(50,100),0.1); + } + + @Test + public void whenPassObtainedMarksAsDouble_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected",5.05, + pc.calculatePercentage(50.5,1000),0.1); + } + + @Test + public void whenPassTotalMarksAsDouble_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected",19.6, + pc.calculatePercentage(5,25.5),0.1); + } + + @Test + public void whenPass2DoubleNumbers_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected",20, + pc.calculatePercentage(5.5,27.5),0.1); + } + +} diff --git a/java-streams/.gitignore b/java-streams/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/java-streams/.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-streams/README.md b/java-streams/README.md new file mode 100644 index 0000000000..2550f08650 --- /dev/null +++ b/java-streams/README.md @@ -0,0 +1,16 @@ +========= + +## Java Streams Cookbooks and Examples + +### Relevant Articles: +- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) +- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) +- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams) +- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany) +- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element) +- [”Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception) +- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream) +- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices) +- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) +- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) +- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) diff --git a/java-streams/pom.xml b/java-streams/pom.xml new file mode 100644 index 0000000000..e4670c268d --- /dev/null +++ b/java-streams/pom.xml @@ -0,0 +1,115 @@ + + 4.0.0 + java-streams + 0.1.0-SNAPSHOT + jar + java-streams + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + provided + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.codepoetics + protonpack + ${protonpack.version} + + + io.vavr + vavr + ${vavr.version} + + + one.util + streamex + ${streamex.version} + + + org.aspectj + aspectjrt + ${asspectj.version} + + + org.aspectj + aspectjweaver + ${asspectj.version} + + + + + java-streams + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + -parameters + + + + + + + + 1.21 + 3.5 + 1.16.12 + 0.9.0 + 1.15 + 0.6.5 + 2.10 + + 3.6.1 + 1.8.9 + + diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java b/java-streams/src/main/java/com/baeldung/java_8_features/Detail.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java rename to java-streams/src/main/java/com/baeldung/java_8_features/Detail.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/InfiniteStreams.java b/java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/InfiniteStreams.java rename to java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/PrimitiveStreams.java b/java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/PrimitiveStreams.java rename to java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/Product.java b/java-streams/src/main/java/com/baeldung/stream/Product.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/Product.java rename to java-streams/src/main/java/com/baeldung/stream/Product.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/StreamApi.java b/java-streams/src/main/java/com/baeldung/stream/StreamApi.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/StreamApi.java rename to java-streams/src/main/java/com/baeldung/stream/StreamApi.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/StreamIndices.java b/java-streams/src/main/java/com/baeldung/stream/StreamIndices.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/StreamIndices.java rename to java-streams/src/main/java/com/baeldung/stream/StreamIndices.java diff --git a/meecrowave/src/main/resources/logback.xml b/java-streams/src/main/resources/logback.xml similarity index 100% rename from meecrowave/src/main/resources/logback.xml rename to java-streams/src/main/resources/logback.xml diff --git a/core-java-8/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java b/java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java rename to java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java b/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java new file mode 100644 index 0000000000..1b64c8924a --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java @@ -0,0 +1,209 @@ +package com.baeldung.protonpack; + +import com.codepoetics.protonpack.Indexed; +import com.codepoetics.protonpack.StreamUtils; +import com.codepoetics.protonpack.collectors.CollectorUtils; +import com.codepoetics.protonpack.collectors.NonUniqueValueException; +import com.codepoetics.protonpack.selectors.Selector; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static java.util.Arrays.stream; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +@SuppressWarnings("unchecked") +public class ProtonpackUnitTest { + @Test + public void whenTakeWhile_thenTakenWhile() { + Stream streamOfInt = Stream.iterate(1, i -> i + 1); + List result = StreamUtils.takeWhile(streamOfInt, i -> i < 5).collect(Collectors.toList()); + assertThat(result).contains(1, 2, 3, 4); + } + + @Test + public void whenTakeUntil_thenTakenUntil() { + Stream streamOfInt = Stream.iterate(1, i -> i + 1); + List result = StreamUtils.takeUntil(streamOfInt, i -> i > 50).collect(Collectors.toList()); + assertThat(result).contains(10, 20, 30, 40); + } + + @Test + public void givenMultipleStream_whenZipped_thenZipped() { + String[] clubs = { "Juventus", "Barcelona", "Liverpool", "PSG" }; + String[] players = { "Ronaldo", "Messi", "Salah" }; + Set zippedFrom2Sources = StreamUtils.zip(stream(clubs), stream(players), (club, player) -> club + " " + player) + .collect(Collectors.toSet()); + assertThat(zippedFrom2Sources).contains("Juventus Ronaldo", "Barcelona Messi", "Liverpool Salah"); + + String[] leagues = { "Serie A", "La Liga", "Premier League" }; + Set zippedFrom3Sources = StreamUtils.zip(stream(clubs), stream(players), stream(leagues), + (club, player, league) -> club + " " + player + " " + league).collect(Collectors.toSet()); + assertThat(zippedFrom3Sources).contains("Juventus Ronaldo Serie A", "Barcelona Messi La Liga", + "Liverpool Salah Premier League"); + } + + @Test + public void whenZippedWithIndex_thenZippedWithIndex() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool"); + Set> zipsWithIndex = StreamUtils.zipWithIndex(streamOfClubs).collect(Collectors.toSet()); + assertThat(zipsWithIndex).contains(Indexed.index(0, "Juventus"), Indexed.index(1, "Barcelona"), + Indexed.index(2, "Liverpool")); + } + + @Test + public void givenMultipleStream_whenMerged_thenMerged() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool", "PSG"); + Stream streamOfPlayers = Stream.of("Ronaldo", "Messi", "Salah"); + Stream streamOfLeagues = Stream.of("Serie A", "La Liga", "Premier League"); + + Set merged = StreamUtils.merge(() -> "", (valOne, valTwo) -> valOne + " " + valTwo, streamOfClubs, + streamOfPlayers, streamOfLeagues).collect(Collectors.toSet()); + + assertThat(merged).contains(" Juventus Ronaldo Serie A", " Barcelona Messi La Liga", " Liverpool Salah Premier League", + " PSG"); + } + + @Test + public void givenMultipleStream_whenMergedToList_thenMergedToList() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "PSG"); + Stream streamOfPlayers = Stream.of("Ronaldo", "Messi"); + + List> mergedListOfList = StreamUtils.mergeToList(streamOfClubs, streamOfPlayers) + .collect(Collectors.toList()); + assertThat(mergedListOfList.get(0)).isInstanceOf(List.class); + assertThat(mergedListOfList.get(0)).containsExactly("Juventus", "Ronaldo"); + assertThat(mergedListOfList.get(1)).containsExactly("Barcelona", "Messi"); + assertThat(mergedListOfList.get(2)).containsExactly("PSG"); + } + + @Test + public void givenMultipleStream_whenInterleaved_thenInterleaved() { + Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool"); + Stream streamOfPlayers = Stream.of("Ronaldo", "Messi"); + Stream streamOfLeagues = Stream.of("Serie A", "La Liga"); + + AtomicInteger counter = new AtomicInteger(0); + Selector roundRobinSelector = (o) -> { + Object[] vals = (Object[]) o; + while (counter.get() >= vals.length || vals[counter.get()] == null) { + if (counter.incrementAndGet() >= vals.length) + counter.set(0); + } + return counter.getAndIncrement(); + }; + Stream interleavedStream = StreamUtils.interleave(roundRobinSelector, streamOfClubs, streamOfPlayers, + streamOfLeagues); + List interleavedList = interleavedStream.collect(Collectors.toList()); + assertThat(interleavedList).containsExactly("Juventus", "Ronaldo", "Serie A", "Barcelona", "Messi", "La Liga", + "Liverpool"); + } + + @Test + public void whenSkippedUntil_thenSkippedUntil() { + Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + List skippedUntilGreaterThan5 = StreamUtils.skipUntil(stream(numbers), i -> i > 5).collect(Collectors.toList()); + assertThat(skippedUntilGreaterThan5).containsExactly(6, 7, 8, 9, 10); + + List skippedUntilLessThanEquals5 = StreamUtils.skipUntil(stream(numbers), i -> i <= 5) + .collect(Collectors.toList()); + assertThat(skippedUntilLessThanEquals5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + + @Test + public void whenSkippedWhile_thenSkippedWhile() { + Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + List skippedWhileLessThanEquals5 = StreamUtils.skipWhile(stream(numbers), i -> i <= 5) + .collect(Collectors.toList()); + assertThat(skippedWhileLessThanEquals5).containsExactly(6, 7, 8, 9, 10); + + List skippedWhileGreaterThan5 = StreamUtils.skipWhile(stream(numbers), i -> i > 5).collect(Collectors.toList()); + assertThat(skippedWhileGreaterThan5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + } + + @Test + public void givenFibonacciGenerator_whenUnfolded_thenUnfolded() { + AtomicInteger lastValue = new AtomicInteger(0); + Function> fibonacciGenerator = (i) -> (i < 10) ? + Optional.of(i + lastValue.getAndSet(i)) : + Optional.empty(); + + List fib = StreamUtils.unfold(1, fibonacciGenerator).collect(Collectors.toList()); + assertThat(fib).containsExactly(1, 1, 2, 3, 5, 8, 13); + } + + @Test + public void whenWindowed_thenWindowed() { + Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7 }; + + List> windowedWithSkip1 = StreamUtils.windowed(stream(numbers), 3, 1).collect(Collectors.toList()); + assertThat(windowedWithSkip1).containsExactly(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5, 6), + asList(5, 6, 7)); + + List> windowedWithSkip2 = StreamUtils.windowed(stream(numbers), 3, 2).collect(Collectors.toList()); + assertThat(windowedWithSkip2).containsExactly(asList(1, 2, 3), asList(3, 4, 5), asList(5, 6, 7)); + } + + @Test + public void whenAggregated_thenAggregated() { + Integer[] numbers = { 1, 2, 2, 3, 4, 4, 4, 5 }; + List> aggregated = StreamUtils.aggregate(stream(numbers), (int1, int2) -> int1.compareTo(int2) == 0) + .collect(Collectors.toList()); + assertThat(aggregated).containsExactly(asList(1), asList(2, 2), asList(3), asList(4, 4, 4), asList(5)); + + List> aggregatedFixSize = StreamUtils.aggregate(stream(numbers), 5).collect(Collectors.toList()); + assertThat(aggregatedFixSize).containsExactly(asList(1, 2, 2, 3, 4), asList(4, 4, 5)); + } + + @Test + public void whenGroupedRun_thenGroupedRun() { + Integer[] numbers = { 1, 1, 2, 3, 4, 4, 5 }; + List> grouped = StreamUtils.groupRuns(stream(numbers)).collect(Collectors.toList()); + assertThat(grouped).containsExactly(asList(1, 1), asList(2), asList(3), asList(4, 4), asList(5)); + + Integer[] numbers2 = { 1, 2, 3, 1 }; + List> grouped2 = StreamUtils.groupRuns(stream(numbers2)).collect(Collectors.toList()); + assertThat(grouped2).containsExactly(asList(1), asList(2), asList(3), asList(1)); + } + + @Test + public void whenAggregatedOnListCondition_thenAggregatedOnListCondition() { + Integer[] numbers = { 1, 1, 2, 3, 4, 4, 5 }; + Stream> aggregated = StreamUtils.aggregateOnListCondition(stream(numbers), + (currentList, nextInt) -> currentList.stream().mapToInt(Integer::intValue).sum() + nextInt <= 5); + assertThat(aggregated).containsExactly(asList(1, 1, 2), asList(3), asList(4), asList(4), asList(5)); + } + + @Test + public void givenProjectionFunction_whenMaxedBy_thenMaxedBy() { + Stream clubs = Stream.of("Juventus", "Barcelona", "PSG"); + Optional longestName = clubs.collect(CollectorUtils.maxBy(String::length)); + assertThat(longestName.get()).isEqualTo("Barcelona"); + } + + @Test + public void givenStreamOfMultipleElem_whenUniqueCollector_thenValueReturned() { + Stream singleElement = Stream.of(1); + Optional unique = singleElement.collect(CollectorUtils.unique()); + assertThat(unique.get()).isEqualTo(1); + + } + + @Test + public void givenStreamOfMultipleElem_whenUniqueCollector_thenExceptionThrown() { + Stream multipleElement = Stream.of(1, 2, 3); + assertThatExceptionOfType(NonUniqueValueException.class).isThrownBy(() -> { + multipleElement.collect(CollectorUtils.unique()); + }); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java similarity index 87% rename from core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java index 2c88dc5ec7..67954f0bba 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java @@ -1,15 +1,14 @@ package com.baeldung.stream; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; public class PrimitiveStreamsUnitTest { @@ -17,7 +16,7 @@ public class PrimitiveStreamsUnitTest { @Test public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() { - int[] integers = new int[] {20, 98, 12, 7, 35}; + int[] integers = new int[] { 20, 98, 12, 7, 35 }; int min = streams.min(integers); // returns 7 assertEquals(7, min); @@ -66,19 +65,14 @@ public class PrimitiveStreamsUnitTest { @Test public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() { - int sum = Stream.of(33,45) - .mapToInt(i -> i) - .sum(); + int sum = Stream.of(33, 45).mapToInt(i -> i).sum(); assertEquals(78, sum); } @Test public void givenAnIntStreamThenGetTheEvenIntegers() { - List evenInts = IntStream.rangeClosed(1, 10) - .filter(i -> i % 2 == 0) - .boxed() - .collect(Collectors.toList()); + List evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList()); List expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList()); diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamAddUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/StreamAddUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamApiUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/StreamApiUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java new file mode 100644 index 0000000000..c5aa9a1651 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.stream; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StreamOperateAndRemoveUnitTest { + + private List itemList; + + @Before + public void setup() { + + itemList = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + itemList.add(new Item(i)); + } + } + + @Test + public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() { + + final List filteredList = itemList.stream().filter(item -> item.isQualified()) + .collect(Collectors.toList()); + + Assert.assertEquals(5, filteredList.size()); + } + + @Test + public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() { + + final Predicate isQualified = item -> item.isQualified(); + itemList.stream().filter(isQualified).forEach(item -> item.operate()); + itemList.removeIf(isQualified); + + Assert.assertEquals(5, itemList.size()); + } + + @Test + public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() { + + final List operatedList = new ArrayList<>(); + itemList.stream().filter(item -> item.isQualified()).forEach(item -> { + item.operate(); + operatedList.add(item); + }); + itemList.removeAll(operatedList); + + Assert.assertEquals(5, itemList.size()); + } + + class Item { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + private final int value; + + public Item(final int value) { + + this.value = value; + } + + public boolean isQualified() { + + return value % 2 == 0; + } + + public void operate() { + + logger.info("Even Number: " + this.value); + } + } +} \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java b/java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java rename to java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java diff --git a/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java b/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java new file mode 100644 index 0000000000..656a6d95f9 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java @@ -0,0 +1,96 @@ +package com.baeldung.streamordering; + +import org.junit.Test; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; +import org.openjdk.jmh.runner.options.TimeValue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + + +public class BenchmarkManualTest +{ + + public void + launchBenchmark() throws Exception { + + Options opt = new OptionsBuilder() + // Specify which benchmarks to run. + // You can be more specific if you'd like to run only one benchmark per test. + .include(this.getClass().getName() + ".*") + // Set the following options as needed + .mode (Mode.AverageTime) + .timeUnit(TimeUnit.MICROSECONDS) + .warmupTime(TimeValue.seconds(1)) + .warmupIterations(2) + .measurementTime(TimeValue.seconds(1)) + .measurementIterations(2) + .threads(2) + .forks(1) + .shouldFailOnError(true) + .shouldDoGC(true) + //.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining") + //.addProfiler(WinPerfAsmProfiler.class) + .build(); + + new Runner(opt).run(); + + + } + + @Benchmark + public void givenOrderedStreamInput_whenStreamFiltered_showOpsPerMS(){ + IntStream.range(1, 100_000_000).parallel().filter(i -> i % 10 == 0).toArray(); + } + + @Benchmark + public void givenUnorderedStreamInput_whenStreamFiltered_showOpsPerMS(){ + IntStream.range(1,100_000_000).unordered().parallel().filter(i -> i % 10 == 0).toArray(); + } + + @Benchmark + public void givenUnorderedStreamInput_whenStreamDistinct_showOpsPerMS(){ + IntStream.range(1, 1_000_000).unordered().parallel().distinct().toArray(); + } + + @Benchmark + public void givenOrderedStreamInput_whenStreamDistinct_showOpsPerMS() { + //section 5.1. + IntStream.range(1, 1_000_000).parallel().distinct().toArray(); + } + + + // The JMH samples are the best documentation for how to use it + // http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/ + @State(Scope.Thread) + public static class BenchmarkState + { + List list; + + @Setup(Level.Trial) public void + initialize() { + + Random rand = new Random(); + + list = new ArrayList<>(); + for (int i = 0; i < 1000; i++) + list.add (rand.nextInt()); + } + } + + @Benchmark public void + benchmark1 (BenchmarkState state, Blackhole bh) { + + List list = state.list; + + for (int i = 0; i < 1000; i++) + bh.consume (list.get (i)); + } +} diff --git a/java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java b/java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java new file mode 100644 index 0000000000..43a233d353 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java @@ -0,0 +1,149 @@ +package com.baeldung.streamordering; + +import org.junit.Before; +import org.junit.Test; + +import java.util.*; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; + +public class StreamsOrderingUnitTest { + + Logger logger = Logger.getLogger( StreamsOrderingUnitTest.class.getName()); + + @Before + public void setUp() throws Exception { + logger.setLevel(Level.ALL); + } + + @Test + public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){ + + List list = Arrays.asList("B", "A", "C", "D", "F"); + Set set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F")); + + Object[] listOutput = list.stream().toArray(); + Object[] setOutput = set.stream().toArray(); + + assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput)); + assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput)); + + } + + @Test + public void givenTwoCollections_whenStreamedInParallel_thenCheckOutputDifferent(){ + + List list = Arrays.asList("B", "A", "C", "D", "F"); + Set set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F")); + + Object[] listOutput = list.stream().parallel().toArray(); + Object[] setOutput = set.stream().parallel().toArray(); + + assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput)); + assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput)); + + } + + + + @Test + public void givenOrderedInput_whenUnorderedAndOrderedCompared_thenCheckUnorderedOutputChanges(){ + Set set = new TreeSet<>( + Arrays.asList(-9, -5, -4, -2, 1, 2, 4, 5, 7, 9, 12, 13, 16, 29, 23, 34, 57, 68, 90, 102, 230)); + + Object[] orderedArray = set.stream() + .parallel() + .limit(5) + .toArray(); + Object[] unorderedArray = set.stream() + .unordered() + .parallel() + .limit(5) + .toArray(); + + logger.info(Arrays.toString(orderedArray)); + logger.info(Arrays.toString(unorderedArray)); + } + + + @Test + public void givenUnsortedStreamInput_whenStreamSorted_thenCheckOrderChanged(){ + + List list = Arrays.asList(-3,10,-4,1,3); + + Object[] listOutput = list.stream().toArray(); + Object[] listOutputSorted = list.stream().sorted().toArray(); + + assertEquals("[-3, 10, -4, 1, 3]", Arrays.toString(listOutput)); + assertEquals("[-4, -3, 1, 3, 10]", Arrays.toString(listOutputSorted)); + + } + + @Test + public void givenUnsortedStreamInput_whenStreamDistinct_thenShowTimeTaken(){ + long start, end; + start = System.currentTimeMillis(); + IntStream.range(1,1_000_000).unordered().parallel().distinct().toArray(); + end = System.currentTimeMillis(); + System.out.println(String.format("Time taken when unordered: %d ms", (end - start))); + } + + + @Test + public void givenSameCollection_whenStreamTerminated_thenCheckEachVsEachOrdered(){ + + List list = Arrays.asList("B", "A", "C", "D", "F"); + + list.stream().parallel().forEach(e -> logger.log(Level.INFO, e)); + list.stream().parallel().forEachOrdered(e -> logger.log(Level.INFO, e)); + + } + + @Test + public void givenSameCollection_whenStreamCollected_thenCheckOutput(){ + + List list = Arrays.asList("B", "A", "C", "D", "F"); + + List collectionList = list.stream().parallel().collect(Collectors.toList()); + Set collectionSet = list.stream().parallel().collect(Collectors.toCollection(TreeSet::new)); + + assertEquals("[B, A, C, D, F]", collectionList.toString()); + assertEquals("[A, B, C, D, F]", collectionSet.toString()); + + } + + + @Test + public void givenListIterationOrder_whenStreamCollectedToMap_thenCeckOrderChanged() { + List list = Arrays.asList("A", "BB", "CCC"); + + Map hashMap = list.stream().collect(Collectors.toMap(Function.identity(), String::length)); + + Object[] keySet = hashMap.keySet().toArray(); + + assertEquals("[BB, A, CCC]", Arrays.toString(keySet)); + + } + + @Test + public void givenListIteration_whenStreamCollectedtoHashMap_thenCheckOrderMaintained() { + List list = Arrays.asList("A", "BB", "CCC", "CCC"); + + Map linkedHashMap = list.stream().collect(Collectors.toMap( + Function.identity(), + String::length, + (u, v) -> u, + LinkedHashMap::new + )); + + Object[] keySet = linkedHashMap.keySet().toArray(); + + assertEquals("[A, BB, CCC]", Arrays.toString(keySet)); + } + +} diff --git a/out/production/main330/com/baeldung/.gitignore b/java-streams/src/test/resources/.gitignore similarity index 100% rename from out/production/main330/com/baeldung/.gitignore rename to java-streams/src/test/resources/.gitignore diff --git a/java-strings/README.md b/java-strings/README.md new file mode 100644 index 0000000000..ff833a5cda --- /dev/null +++ b/java-strings/README.md @@ -0,0 +1,35 @@ +========= + +## Java Strings Cookbooks and Examples + +### Relevant Articles: +- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) +- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream) +- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner) +- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) +- [Java – Generate Random String](http://www.baeldung.com/java-random-string) +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions) +- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum) +- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer) +- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) +- [Split a String in Java](http://www.baeldung.com/java-split-string) +- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) +- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) +- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) +- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) +- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) +- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) +- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) +- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords) +- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case) +- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) +- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) +- [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string) +- [Get Substring from String in Java](https://www.baeldung.com/java-substring) +- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string) +- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) +- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) +- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) +- [String Performance Hints](https://www.baeldung.com/java-string-performance) diff --git a/java-strings/pom.xml b/java-strings/pom.xml new file mode 100644 index 0000000000..b1ba49b33a --- /dev/null +++ b/java-strings/pom.xml @@ -0,0 +1,108 @@ + + 4.0.0 + com.baeldung + java-strings + 0.1.0-SNAPSHOT + jar + java-strings + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-core.version} + + + com.ibm.icu + icu4j + ${icu4j.version} + + + com.google.guava + guava + ${guava.version} + + + + com.vdurmont + emoji-java + 4.0.0 + + + + + + java-strings + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + -parameters + + + + + + + + 3.5 + 1.10 + + 3.6.1 + 1.19 + 61.1 + 26.0-jre + + + \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 100% rename from core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java diff --git a/java-strings/src/main/java/com/baeldung/enums/PizzaStatusEnum.java b/java-strings/src/main/java/com/baeldung/enums/PizzaStatusEnum.java new file mode 100644 index 0000000000..a84829c38d --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/enums/PizzaStatusEnum.java @@ -0,0 +1,44 @@ +package com.baeldung.enums; + +public enum PizzaStatusEnum { + ORDERED(5) { + @Override + public boolean isOrdered() { + return true; + } + }, + READY(2) { + @Override + public boolean isReady() { + return true; + } + }, + DELIVERED(0) { + @Override + public boolean isDelivered() { + return true; + } + }; + + private int timeToDelivery; + + public boolean isOrdered() { + return false; + } + + public boolean isReady() { + return false; + } + + public boolean isDelivered() { + return false; + } + + public int getTimeToDelivery() { + return timeToDelivery; + } + + PizzaStatusEnum(int timeToDelivery) { + this.timeToDelivery = timeToDelivery; + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java b/java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java rename to java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java diff --git a/core-java-8/src/main/java/com/baeldung/string/JoinerSplitter.java b/java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java similarity index 76% rename from core-java-8/src/main/java/com/baeldung/string/JoinerSplitter.java rename to java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java index 085be66801..cdbba1ef53 100644 --- a/core-java-8/src/main/java/com/baeldung/string/JoinerSplitter.java +++ b/java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java @@ -2,6 +2,7 @@ package com.baeldung.string; import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -32,5 +33,12 @@ public class JoinerSplitter { .mapToObj(item -> (char) item) .collect(Collectors.toList()); } + + public static Map arrayToMap(String[] arrayOfString) { + return Arrays.asList(arrayOfString) + .stream() + .map(str -> str.split(":")) + .collect(Collectors.toMap(str -> str[0], str -> str[1])); + } } diff --git a/core-java/src/main/java/com/baeldung/string/Palindrome.java b/java-strings/src/main/java/com/baeldung/string/Palindrome.java similarity index 100% rename from core-java/src/main/java/com/baeldung/string/Palindrome.java rename to java-strings/src/main/java/com/baeldung/string/Palindrome.java diff --git a/core-java/src/main/java/com/baeldung/string/StringBufferStringBuilder.java b/java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java similarity index 96% rename from core-java/src/main/java/com/baeldung/string/StringBufferStringBuilder.java rename to java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java index 74f489d57f..72af4a9aee 100644 --- a/core-java/src/main/java/com/baeldung/string/StringBufferStringBuilder.java +++ b/java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java @@ -1,46 +1,46 @@ -package com.baeldung.string; - -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.runner.Runner; -import org.openjdk.jmh.runner.RunnerException; -import org.openjdk.jmh.runner.options.Options; -import org.openjdk.jmh.runner.options.OptionsBuilder; - -public class StringBufferStringBuilder { - - public static void main(String[] args) throws RunnerException { - - Options opt = new OptionsBuilder() - .include(StringBufferStringBuilder.class.getSimpleName()) - .build(); - - new Runner(opt).run(); - } - - @State(Scope.Benchmark) - public static class MyState { - int iterations = 1000; - String initial = "abc"; - String suffix = "def"; - } - - @Benchmark - public StringBuffer benchmarkStringBuffer(MyState state) { - StringBuffer stringBuffer = new StringBuffer(state.initial); - for (int i = 0; i < state.iterations; i++) { - stringBuffer.append(state.suffix); - } - return stringBuffer; - } - - @Benchmark - public StringBuilder benchmarkStringBuilder(MyState state) { - StringBuilder stringBuilder = new StringBuilder(state.initial); - for (int i = 0; i < state.iterations; i++) { - stringBuilder.append(state.suffix); - } - return stringBuilder; - } +package com.baeldung.string; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +public class StringBufferStringBuilder { + + public static void main(String[] args) throws RunnerException { + + Options opt = new OptionsBuilder() + .include(StringBufferStringBuilder.class.getSimpleName()) + .build(); + + new Runner(opt).run(); + } + + @State(Scope.Benchmark) + public static class MyState { + int iterations = 1000; + String initial = "abc"; + String suffix = "def"; + } + + @Benchmark + public StringBuffer benchmarkStringBuffer(MyState state) { + StringBuffer stringBuffer = new StringBuffer(state.initial); + for (int i = 0; i < state.iterations; i++) { + stringBuffer.append(state.suffix); + } + return stringBuffer; + } + + @Benchmark + public StringBuilder benchmarkStringBuilder(MyState state) { + StringBuilder stringBuilder = new StringBuilder(state.initial); + for (int i = 0; i < state.iterations; i++) { + stringBuilder.append(state.suffix); + } + return stringBuilder; + } } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/string/StringHelper.java b/java-strings/src/main/java/com/baeldung/string/StringHelper.java similarity index 100% rename from core-java/src/main/java/com/baeldung/string/StringHelper.java rename to java-strings/src/main/java/com/baeldung/string/StringHelper.java diff --git a/java-strings/src/main/java/com/baeldung/string/StringPerformance.java b/java-strings/src/main/java/com/baeldung/string/StringPerformance.java new file mode 100644 index 0000000000..3b0c32991c --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/StringPerformance.java @@ -0,0 +1,196 @@ +package com.baeldung.string; + +import com.google.common.base.Splitter; +import org.apache.commons.lang3.StringUtils; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Measurement(batchSize = 100000, iterations = 10) +@Warmup(batchSize = 100000, iterations = 10) +@State(Scope.Thread) +public class StringPerformance { + + protected String baeldung = "baeldung"; + protected String longString = "Hello baeldung, I am a bit longer than other Strings"; + protected String formatString = "hello %s, nice to meet you"; + protected String formatDigit = "%d"; + protected String emptyString = " "; + protected String result = ""; + + protected int sampleNumber = 100; + + protected Pattern spacePattern = Pattern.compile(emptyString); + protected Pattern longPattern = Pattern.compile(longString); + protected List stringSplit = new ArrayList<>(); + protected List stringTokenizer = new ArrayList<>(); + + @Benchmark + public String benchmarkStringDynamicConcat() { + result += baeldung; + return result; + } + + @Benchmark + public StringBuilder benchmarkStringBuilder() { + StringBuilder stringBuilder = new StringBuilder(result); + stringBuilder.append(baeldung); + return stringBuilder; + } + + @Benchmark + public StringBuffer benchmarkStringBuffer() { + StringBuffer stringBuffer = new StringBuffer(result); + stringBuffer.append(baeldung); + return stringBuffer; + } + + @Benchmark + public String benchmarkStringConstructor() { + String result = new String("baeldung"); + return result; + } + + @Benchmark + public String benchmarkStringLiteral() { + String result = "baeldung"; + return result; + } + + @Benchmark + public String benchmarkStringFormat_s() { + return String.format(formatString, baeldung); + } + + @Benchmark + public String benchmarkStringConcat() { + result = result.concat(baeldung); + return result; + } + + @Benchmark + public String benchmarkStringIntern() { + return baeldung.intern(); + } + + @Benchmark + public String benchmarkStringReplace() { + return longString.replace("average", " average !!!"); + } + + @Benchmark + public String benchmarkStringUtilsReplace() { + return StringUtils.replace(longString, "average", " average !!!"); + } + + @Benchmark + public List benchmarkGuavaSplitter() { + return Splitter.on(" ").trimResults() + .omitEmptyStrings() + .splitToList(longString); + } + + @Benchmark + public String [] benchmarkStringSplit() { + return longString.split(emptyString); + } + + @Benchmark + public String [] benchmarkStringSplitPattern() { + return spacePattern.split(longString, 0); + } + + @Benchmark + public List benchmarkStringTokenizer() { + StringTokenizer st = new StringTokenizer(longString); + while (st.hasMoreTokens()) { + stringTokenizer.add(st.nextToken()); + } + return stringTokenizer; + } + + @Benchmark + public List benchmarkStringIndexOf() { + int pos = 0, end; + while ((end = longString.indexOf(' ', pos)) >= 0) { + stringSplit.add(longString.substring(pos, end)); + pos = end + 1; + } + return stringSplit; + } + + @Benchmark + public String benchmarkIntegerToString() { + return Integer.toString(sampleNumber); + } + + @Benchmark + public String benchmarkStringValueOf() { + return String.valueOf(sampleNumber); + } + + + @Benchmark + public String benchmarkStringConvertPlus() { + return sampleNumber + ""; + } + + @Benchmark + public String benchmarkStringFormat_d() { + return String.format(formatDigit, sampleNumber); + } + + @Benchmark + public boolean benchmarkStringEquals() { + return longString.equals(baeldung); + } + + + @Benchmark + public boolean benchmarkStringEqualsIgnoreCase() { + return longString.equalsIgnoreCase(baeldung); + } + + @Benchmark + public boolean benchmarkStringMatches() { + return longString.matches(baeldung); + } + + @Benchmark + public boolean benchmarkPrecompiledMatches() { + return longPattern.matcher(baeldung).matches(); + } + + @Benchmark + public int benchmarkStringCompareTo() { + return longString.compareTo(baeldung); + } + + @Benchmark + public boolean benchmarkStringIsEmpty() { + return longString.isEmpty(); + } + + @Benchmark + public boolean benchmarkStringLengthZero() { + return longString.length() == 0; + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(StringPerformance.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java/src/main/java/com/baeldung/string/TitleCaseConverter.java b/java-strings/src/main/java/com/baeldung/string/TitleCaseConverter.java similarity index 97% rename from core-java/src/main/java/com/baeldung/string/TitleCaseConverter.java rename to java-strings/src/main/java/com/baeldung/string/TitleCaseConverter.java index 0fdda86f2a..81043f6dac 100644 --- a/core-java/src/main/java/com/baeldung/string/TitleCaseConverter.java +++ b/java-strings/src/main/java/com/baeldung/string/TitleCaseConverter.java @@ -1,12 +1,13 @@ package com.baeldung.string; -import com.ibm.icu.lang.UCharacter; -import com.ibm.icu.text.BreakIterator; -import org.apache.commons.lang.WordUtils; - import java.util.Arrays; import java.util.stream.Collectors; +import org.apache.commons.lang3.text.WordUtils; + +import com.ibm.icu.lang.UCharacter; +import com.ibm.icu.text.BreakIterator; + public class TitleCaseConverter { private static final String WORD_SEPARATOR = " "; diff --git a/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java b/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java new file mode 100644 index 0000000000..c4f684383d --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java @@ -0,0 +1,29 @@ +package com.baeldung.string.sorting; + +import java.util.Arrays; + +public class AnagramValidator { + + public static boolean isValid(String text, String anagram) { + text = prepare(text); + anagram = prepare(anagram); + + String sortedText = sort(text); + String sortedAnagram = sort(anagram); + + return sortedText.equals(sortedAnagram); + } + + private static String sort(String text) { + char[] chars = prepare(text).toCharArray(); + + Arrays.sort(chars); + return new String(chars); + } + + private static String prepare(String text) { + return text.toLowerCase() + .trim() + .replaceAll("\\s+", ""); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java b/java-strings/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java similarity index 100% rename from core-java/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java rename to java-strings/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java diff --git a/core-java/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java b/java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java similarity index 100% rename from core-java/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java rename to java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java diff --git a/core-java/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java b/java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java similarity index 100% rename from core-java/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java rename to java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java diff --git a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java b/java-strings/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java rename to java-strings/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java diff --git a/core-java/src/main/resources/data.csv b/java-strings/src/main/resources/data.csv similarity index 100% rename from core-java/src/main/resources/data.csv rename to java-strings/src/main/resources/data.csv diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/resources/logback.xml b/java-strings/src/main/resources/logback.xml similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/resources/logback.xml rename to java-strings/src/main/resources/logback.xml diff --git a/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/CharArrayToStringUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java rename to java-strings/src/test/java/com/baeldung/CharArrayToStringUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/CharToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/CharToStringUnitTest.java rename to java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/StringToCharArrayUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java rename to java-strings/src/test/java/com/baeldung/StringToCharArrayUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java b/java-strings/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java rename to java-strings/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java b/java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java rename to java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/java-strings/src/test/java/com/baeldung/enums/PizzaUnitTest.java new file mode 100644 index 0000000000..3e52a89bad --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/enums/PizzaUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.enums; + +import static junit.framework.TestCase.assertTrue; + +import org.junit.Test; + +public class PizzaUnitTest { + + @Test + public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() { + String pizzaEnumValue = "READY"; + PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); + assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY); + } + + @Test(expected = IllegalArgumentException.class) + public void whenConvertedIntoEnum_thenThrowsException() { + String pizzaEnumValue = "rEAdY"; + PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); + } + + @Test(expected = IllegalArgumentException.class) + public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() { + String pizzaEnumValue = "invalid"; + PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue); + } +} \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java b/java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java rename to java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/java/conversion/README.md b/java-strings/src/test/java/com/baeldung/java/conversion/README.md similarity index 100% rename from core-java/src/test/java/com/baeldung/java/conversion/README.md rename to java-strings/src/test/java/com/baeldung/java/conversion/README.md diff --git a/core-java/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java b/java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java rename to java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java b/java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java rename to java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java index aeb33fe875..e2dd0ac1db 100644 --- a/core-java/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java @@ -1,13 +1,14 @@ package com.baeldung.java.countingChars; -import com.google.common.base.CharMatcher; -import org.apache.commons.lang.StringUtils; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static org.junit.Assert.assertEquals; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import com.google.common.base.CharMatcher; /*** diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java b/java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java rename to java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java b/java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java rename to java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java b/java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java similarity index 76% rename from core-java-8/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java index 8901bcf9db..a9488e27a4 100644 --- a/core-java-8/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java @@ -3,7 +3,9 @@ package com.baeldung.string; import org.junit.Test; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; @@ -62,5 +64,20 @@ public class JoinerSplitterUnitTest { assertEquals(result, expectation); } + + @Test + public void givenStringArray_transformedToStream_convertToMap() { + + String[] programming_languages = new String[] {"language:java","os:linux","editor:emacs"}; + + Map expectation=new HashMap<>(); + expectation.put("language", "java"); + expectation.put("os", "linux"); + expectation.put("editor", "emacs"); + + Map result = JoinerSplitter.arrayToMap(programming_languages); + assertEquals(result, expectation); + + } } diff --git a/core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java b/java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java new file mode 100644 index 0000000000..8688f9dcf5 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.string; + +import static org.junit.Assert.assertEquals; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +import com.vdurmont.emoji.EmojiParser; + +public class RemovingEmojiFromStringUnitTest { + String text = "la conférence, commencera à 10 heures 😅"; + String regex = "[^\\p{L}\\p{N}\\p{P}\\p{Z}]"; + + @Test + public void whenRemoveEmojiUsingLibrary_thenSuccess() { + String result = EmojiParser.removeAllEmojis(text); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures "); + } + + @Test + public void whenReplaceEmojiUsingLibrary_thenSuccess() { + String result = EmojiParser.parseToAliases(text); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures :sweat_smile:"); + } + + @Test + public void whenRemoveEmojiUsingRegex_thenSuccess() { + String result = text.replaceAll(regex, ""); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures "); + } + + @Test + public void whenRemoveEmojiUsingMatcher_thenSuccess() { + Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CHARACTER_CLASS); + Matcher matcher = pattern.matcher(text); + + String result = matcher.replaceAll(""); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures "); + } + + @Test + public void whenRemoveEmojiUsingCodepoints_thenSuccess() { + String result = text.replaceAll("[\\x{0001f300}-\\x{0001f64f}]|[\\x{0001f680}-\\x{0001f6ff}]", ""); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures "); + } + + @Test + public void whenRemoveEmojiUsingUnicode_thenSuccess() { + String result = text.replaceAll("[\ud83c\udf00-\ud83d\ude4f]|[\ud83d\ude80-\ud83d\udeff]", ""); + System.out.println(result); + assertEquals(result, "la conférence, commencera à 10 heures "); + } +} diff --git a/core-java/src/test/java/com/baeldung/string/SplitUnitTest.java b/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java similarity index 73% rename from core-java/src/test/java/com/baeldung/string/SplitUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java index 83fd253b97..6157640a4a 100644 --- a/core-java/src/test/java/com/baeldung/string/SplitUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java @@ -1,12 +1,14 @@ package com.baeldung.string; -import com.google.common.base.Splitter; -import org.apache.commons.lang.StringUtils; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import java.util.Arrays; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; +import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.Test; + +import com.google.common.base.Splitter; public class SplitUnitTest { @@ -53,4 +55,18 @@ public class SplitUnitTest { assertThat(resultList) .containsExactly("car", "jeep", "scooter"); } + + @Test + public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_Regex() { + assertThat(" car , jeep, scooter ".trim() + .split("\\s*,\\s*")).containsExactly("car", "jeep", "scooter"); + + } + + @Test + public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_java_8() { + assertThat(Arrays.stream(" car , jeep, scooter ".split(",")) + .map(String::trim) + .toArray(String[]::new)).containsExactly("car", "jeep", "scooter"); + } } diff --git a/core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringContainingCharactersUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringContainingCharactersUnitTest.java new file mode 100644 index 0000000000..be79103e6b --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/StringContainingCharactersUnitTest.java @@ -0,0 +1,136 @@ +package com.baeldung.string; + +import org.junit.Test; + +import java.util.regex.Pattern; + +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertTrue; + +public class StringContainingCharactersUnitTest { + + private static final Pattern[] inputRegexes = new Pattern[4]; + + private static final String regex = "^(?=.*?\\p{Lu})(?=.*?\\p{Ll})(?=.*?\\d)(?=.*?[`~!@#$%^&*()\\-_=+\\\\|\\[{\\]};:'\",<.>/?]).*$"; + + static { + inputRegexes[0] = Pattern.compile(".*[A-Z].*"); + inputRegexes[1] = Pattern.compile(".*[a-z].*"); + inputRegexes[2] = Pattern.compile(".*\\d.*"); + inputRegexes[3] = Pattern.compile(".*[`~!@#$%^&*()\\-_=+\\\\|\\[{\\]};:'\",<.>/?].*"); + } + + private static boolean isMatchingRegex(String input) { + boolean inputMatches = true; + for (Pattern inputRegex : inputRegexes) { + if (!inputRegex + .matcher(input) + .matches()) { + inputMatches = false; + } + } + return inputMatches; + } + + private static boolean checkString(String input) { + String specialChars = "~`!@#$%^&*()-_=+\\|[{]};:'\",<.>/?"; + char currentCharacter; + boolean numberPresent = false; + boolean upperCasePresent = false; + boolean lowerCasePresent = false; + boolean specialCharacterPresent = false; + + for (int i = 0; i < input.length(); i++) { + currentCharacter = input.charAt(i); + if (Character.isDigit(currentCharacter)) { + numberPresent = true; + } else if (Character.isUpperCase(currentCharacter)) { + upperCasePresent = true; + } else if (Character.isLowerCase(currentCharacter)) { + lowerCasePresent = true; + } else if (specialChars.contains(String.valueOf(currentCharacter))) { + specialCharacterPresent = true; + } + } + + return numberPresent && upperCasePresent && lowerCasePresent && specialCharacterPresent; + } + + @Test + public void givenRegexes_whenMatchingCorrectString_thenMatches() { + String validInput = "Ab3;"; + assertTrue(isMatchingRegex(validInput)); + } + + @Test + public void givenRegexes_whenMatchingWrongStrings_thenNotMatching() { + String invalidInput = "Ab3"; + assertFalse(isMatchingRegex(invalidInput)); + + invalidInput = "Ab;"; + assertFalse(isMatchingRegex(invalidInput)); + + invalidInput = "A3;"; + assertFalse(isMatchingRegex(invalidInput)); + + invalidInput = "b3;"; + assertFalse(isMatchingRegex(invalidInput)); + } + + @Test + public void givenValidString_whenChecking_thenCorrect() { + String validInput = "Ab3;"; + assertTrue(checkString(validInput)); + } + + @Test + public void givenInvalidStrings_whenChecking_thenNotCorrect() { + String invalidInput = "Ab3"; + assertFalse(checkString(invalidInput)); + + invalidInput = "Ab;"; + assertFalse(checkString(invalidInput)); + + invalidInput = "A3;"; + assertFalse(checkString(invalidInput)); + + invalidInput = "b3;"; + assertFalse(checkString(invalidInput)); + } + + @Test + public void givenSingleRegex_whenMatchingCorrectString_thenMatches() { + String validInput = "Ab3;"; + assertTrue(Pattern + .compile(regex) + .matcher(validInput) + .matches()); + } + + @Test + public void givenSingleRegex_whenMatchingWrongStrings_thenNotMatching() { + String invalidInput = "Ab3"; + assertFalse(Pattern + .compile(regex) + .matcher(invalidInput) + .matches()); + + invalidInput = "Ab;"; + assertFalse(Pattern + .compile(regex) + .matcher(invalidInput) + .matches()); + + invalidInput = "A3;"; + assertFalse(Pattern + .compile(regex) + .matcher(invalidInput) + .matches()); + + invalidInput = "b3;"; + assertFalse(Pattern + .compile(regex) + .matcher(invalidInput) + .matches()); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java new file mode 100644 index 0000000000..17b13f89de --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.string; + +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; +import static org.hamcrest.text.IsEmptyString.isEmptyString; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.lang3.StringUtils; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +import com.google.common.base.Strings; + +public class StringEmptyUnitTest { + + private String text = "baeldung"; + + @Test + public void givenAString_whenCheckedForEmptyUsingJunit_shouldAssertSuccessfully() { + assertTrue(!text.isEmpty()); + assertFalse(text.isEmpty()); + assertNotEquals("", text); + assertNotSame("", text); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingHamcrest_shouldAssertSuccessfully() { + assertThat(text, not(isEmptyString())); + assertThat(text, not(isEmptyOrNullString())); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingCommonsLang_shouldAssertSuccessfully() { + assertTrue(StringUtils.isNotBlank(text)); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingAssertJ_shouldAssertSuccessfully() { + Assertions.assertThat(text).isNotEmpty(); + } + + @Test + public void givenAString_whenCheckedForEmptyUsingGuava_shouldAssertSuccessfully() { + assertFalse(Strings.isNullOrEmpty(text)); + } + +} diff --git a/core-java/src/test/java/com/baeldung/string/StringHelperUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/StringHelperUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/string/StringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/StringUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/StringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java new file mode 100644 index 0000000000..3a4e231828 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.string; + +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.Test; + +public class SubstringUnitTest { + + String text = "Julia Evans was born on 25-09-1984. She is currently living in the USA (United States of America)."; + + @Test + public void givenAString_whenUsedStringUtils_ShouldReturnProperSubstring() { + Assert.assertEquals("United States of America", StringUtils.substringBetween(text, "(", ")")); + Assert.assertEquals("the USA (United States of America).", StringUtils.substringAfter(text, "living in ")); + Assert.assertEquals("Julia Evans", StringUtils.substringBefore(text, " was born")); + } + + @Test + public void givenAString_whenUsedScanner_ShouldReturnProperSubstring() { + try (Scanner scanner = new Scanner(text)) { + scanner.useDelimiter("\\."); + Assert.assertEquals("Julia Evans was born on 25-09-1984", scanner.next()); + } + } + + @Test + public void givenAString_whenUsedSplit_ShouldReturnProperSubstring() { + String[] sentences = text.split("\\."); + Assert.assertEquals("Julia Evans was born on 25-09-1984", sentences[0]); + } + + @Test + public void givenAString_whenUsedRegex_ShouldReturnProperSubstring() { + Pattern pattern = Pattern.compile("\\d{2}\\-\\d{2}-\\d{4}"); + Matcher matcher = pattern.matcher(text); + + if (matcher.find()) { + Assert.assertEquals("25-09-1984", matcher.group()); + } + } + + @Test + public void givenAString_whenUsedSubSequence_ShouldReturnProperSubstring() { + Assert.assertEquals("USA (United States of America)", text.subSequence(67, text.length() - 1)); + } + + @Test + public void givenAString_whenUsedSubstring_ShouldReturnProperSubstring() { + Assert.assertEquals("USA (United States of America).", text.substring(67)); + Assert.assertEquals("USA (United States of America)", text.substring(67, text.length() - 1)); + } + + @Test + public void givenAString_whenUsedSubstringWithIndexOf_ShouldReturnProperSubstring() { + Assert.assertEquals("United States of America", text.substring(text.indexOf('(') + 1, text.indexOf(')'))); + } + +} diff --git a/core-java/src/test/java/com/baeldung/string/TitleCaseConverterUnitTest.java b/java-strings/src/test/java/com/baeldung/string/TitleCaseConverterUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/TitleCaseConverterUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/TitleCaseConverterUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java b/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java new file mode 100644 index 0000000000..f236c641c3 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.string.formatter; + +import org.junit.BeforeClass; +import org.junit.Test; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import static org.junit.Assert.assertEquals; + +public class DateToStringFormatterUnitTest { + + private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a"; + private static final String EXPECTED_STRING_DATE = "Aug 1, 2018 12:00 PM"; + private static Date date; + + @BeforeClass + public static void setUp() { + TimeZone.setDefault(TimeZone.getTimeZone("CET")); + Calendar calendar = Calendar.getInstance(); + calendar.set(2018, Calendar.AUGUST, 1, 12, 0); + date = calendar.getTime(); + } + + @Test + public void whenDateConvertedUsingSimpleDateFormatToString_thenCorrect() { + DateFormat formatter = new SimpleDateFormat(DATE_FORMAT); + String formattedDate = formatter.format(date); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } + + @Test + public void whenDateConvertedUsingDateFormatToString_thenCorrect() { + String formattedDate = DateFormat + .getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT) + .format(date); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } + + @Test + public void whenDateConvertedUsingFormatterToString_thenCorrect() { + String formattedDate = String.format("%1$tb %1$te, %1$tY %1$tI:%1$tM %1$Tp", date); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } + + @Test + public void whenDateConvertedUsingDateTimeApiToString_thenCorrect() { + DateTimeFormatter fmt = DateTimeFormatter.ofPattern(DATE_FORMAT); + Instant instant = date.toInstant(); + LocalDateTime ldt = instant + .atZone(ZoneId.of("CET")) + .toLocalDateTime(); + String formattedDate = ldt.format(fmt); + + assertEquals(EXPECTED_STRING_DATE, formattedDate); + } +} diff --git a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java b/java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java b/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java new file mode 100644 index 0000000000..07d31c7187 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.string.sorting; + + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.Test; + +import com.baeldung.string.sorting.AnagramValidator; + +class AnagramValidatorUnitTest { + + @Test + void givenValidAnagrams_whenSorted_thenEqual() { + boolean isValidAnagram = AnagramValidator.isValid("Avida Dollars", "Salvador Dali"); + + assertTrue(isValidAnagram); + } + + @Test + void givenNotValidAnagrams_whenSorted_thenNotEqual() { + boolean isValidAnagram = AnagramValidator.isValid("abc", "def"); + + assertFalse(isValidAnagram); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java new file mode 100644 index 0000000000..90d1dad554 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.string.sorting; + +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SortStringUnitTest { + + @Test + void givenString_whenSort_thenSorted() { + String abcd = "bdca"; + char[] chars = abcd.toCharArray(); + + Arrays.sort(chars); + String sorted = new String(chars); + + assertThat(sorted).isEqualTo("abcd"); + } + + @Test + void givenString_whenSortJava8_thenSorted() { + String sorted = "bdca".chars() + .sorted() + .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) + .toString(); + + assertThat(sorted).isEqualTo("abcd"); + } +} diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java b/java-strings/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java rename to java-strings/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsCreatableUnitTest.java b/java-strings/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsCreatableUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsCreatableUnitTest.java rename to java-strings/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsCreatableUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsParsableUnitTest.java b/java-strings/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsParsableUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsParsableUnitTest.java rename to java-strings/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsParsableUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/RegularExpressionsUnitTest.java b/java-strings/src/test/java/com/baeldung/stringisnumeric/RegularExpressionsUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/stringisnumeric/RegularExpressionsUnitTest.java rename to java-strings/src/test/java/com/baeldung/stringisnumeric/RegularExpressionsUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericSpaceUnitTest.java b/java-strings/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericSpaceUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericSpaceUnitTest.java rename to java-strings/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericSpaceUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericUnitTest.java b/java-strings/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericUnitTest.java rename to java-strings/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java b/java-strings/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java rename to java-strings/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java b/java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java rename to java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/stringtokenizer/TokenizerUnitTest.java b/java-strings/src/test/java/com/baeldung/stringtokenizer/TokenizerUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/stringtokenizer/TokenizerUnitTest.java rename to java-strings/src/test/java/com/baeldung/stringtokenizer/TokenizerUnitTest.java diff --git a/java-strings/src/test/resources/.gitignore b/java-strings/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/java-strings/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/core-java-8/src/test/resources/test_image.jpg b/java-strings/src/test/resources/test_image.jpg similarity index 100% rename from core-java-8/src/test/resources/test_image.jpg rename to java-strings/src/test/resources/test_image.jpg diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml index afee807428..7b4eecd880 100644 --- a/javax-servlets/pom.xml +++ b/javax-servlets/pom.xml @@ -84,7 +84,7 @@ 5.0.5.RELEASE 2.8.2 3.9.1 - 2.18.3 + 2.21.0 1.3.3 2.6 4.0.1 diff --git a/javaxval/bin/pom.xml b/javaxval/bin/pom.xml deleted file mode 100644 index a16072bb1a..0000000000 --- a/javaxval/bin/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - 4.0.0 - com.baeldung - javaxval - 0.1-SNAPSHOT - - - - - - javax.validation - validation-api - 1.1.0.Final - - - - org.hibernate - hibernate-validator - 5.2.1.Final - - - - org.hibernate - hibernate-validator-annotation-processor - 5.2.1.Final - - - - javax.el - javax.el-api - 2.2.4 - - - - org.glassfish.web - javax.el - 2.2.4 - - - - - - \ No newline at end of file diff --git a/javaxval/pom.xml b/javaxval/pom.xml index 7af766261b..0263fb68af 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -1,55 +1,73 @@ - - 4.0.0 - com.baeldung - javaxval - 0.1-SNAPSHOT - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - org.hibernate - hibernate-validator-annotation-processor - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - org.glassfish.web - javax.el - ${javax.el.version} - - - org.springframework - spring-context - ${org.springframework.version} - - - org.springframework - spring-test - ${org.springframework.version} - - - - - 2.0.1.Final - 6.0.7.Final - 3.0.0 - 2.2.6 - 5.0.2.RELEASE - - - \ No newline at end of file + + 4.0.0 + com.baeldung + javaxval + 0.1-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + javax.validation + validation-api + ${validation-api.version} + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + org.hibernate + hibernate-validator-annotation-processor + ${hibernate-validator.version} + + + javax.el + javax.el-api + ${javax.el-api.version} + + + org.glassfish + javax.el + ${javax.el.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-test + ${org.springframework.version} + + + junit + junit + ${junit.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 2.0.1.Final + 6.0.13.Final + 3.0.0 + 3.0.0 + 5.0.2.RELEASE + 4.12 + 3.11.1 + + diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/appplication/Application.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/appplication/Application.java new file mode 100644 index 0000000000..c9f2ab6f98 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/appplication/Application.java @@ -0,0 +1,14 @@ +package org.baeldung.javabeanconstraints.appplication; + +import javax.validation.Validation; +import javax.validation.Validator; +import org.baeldung.javabeanconstraints.entities.UserNotBlank; + +public class Application { + + public static void main(String[] args) throws Exception { + Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); + UserNotBlank user = new UserNotBlank(" "); + validator.validate(user).stream().forEach(violation -> System.out.println(violation.getMessage())); + } +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotBlank.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotBlank.java new file mode 100644 index 0000000000..2ea6a3af56 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotBlank.java @@ -0,0 +1,22 @@ +package org.baeldung.javabeanconstraints.entities; + +import javax.validation.constraints.NotBlank; + +public class UserNotBlank { + + @NotBlank(message = "Name is mandatory") + private final String name; + + public UserNotBlank(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "User{" + "name=" + name + "}"; + } +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotEmpty.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotEmpty.java new file mode 100644 index 0000000000..39e34b63d3 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotEmpty.java @@ -0,0 +1,22 @@ +package org.baeldung.javabeanconstraints.entities; + +import javax.validation.constraints.NotEmpty; + +public class UserNotEmpty { + + @NotEmpty(message = "Name is mandatory") + private final String name; + + public UserNotEmpty(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "User{" + "name=" + name + "}"; + } +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotNull.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotNull.java new file mode 100644 index 0000000000..598c9ba9f9 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotNull.java @@ -0,0 +1,22 @@ +package org.baeldung.javabeanconstraints.entities; + +import javax.validation.constraints.NotNull; + +public class UserNotNull { + + @NotNull(message = "Name is mandatory") + private final String name; + + public UserNotNull(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "User{" + "name=" + name + "}"; + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotBlankUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotBlankUnitTest.java new file mode 100644 index 0000000000..954833fef1 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotBlankUnitTest.java @@ -0,0 +1,63 @@ +package org.baeldung.javabeanconstraints.test; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import static org.assertj.core.api.Assertions.assertThat; +import org.baeldung.javabeanconstraints.entities.UserNotBlank; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserNotBlankUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenNotBlankName_thenNoConstraintViolations() { + UserNotBlank user = new UserNotBlank("John"); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenBlankName_thenOneConstraintViolation() { + UserNotBlank user = new UserNotBlank(" "); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenEmptyName_thenOneConstraintViolation() { + UserNotBlank user = new UserNotBlank(""); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenNullName_thenOneConstraintViolation() { + UserNotBlank user = new UserNotBlank(null); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenToString_thenCorrect() { + UserNotBlank user = new UserNotBlank("John"); + + assertThat(user.toString()).isEqualTo("User{name=John}"); + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotEmptyUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotEmptyUnitTest.java new file mode 100644 index 0000000000..c2675ed8b6 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotEmptyUnitTest.java @@ -0,0 +1,54 @@ +package org.baeldung.javabeanconstraints.test; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import static org.assertj.core.api.Assertions.assertThat; +import org.baeldung.javabeanconstraints.entities.UserNotEmpty; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserNotEmptyUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenNotEmptyName_thenNoConstraintViolations() { + UserNotEmpty user = new UserNotEmpty("John"); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenEmptyName_thenOneConstraintViolation() { + UserNotEmpty user = new UserNotEmpty(""); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenNullName_thenOneConstraintViolation() { + UserNotEmpty user = new UserNotEmpty(null); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenToString_thenCorrect() { + UserNotEmpty user = new UserNotEmpty("John"); + + assertThat(user.toString()).isEqualTo("User{name=John}"); + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotNullUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotNullUnitTest.java new file mode 100644 index 0000000000..3dd1811947 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotNullUnitTest.java @@ -0,0 +1,54 @@ +package org.baeldung.javabeanconstraints.test; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import static org.assertj.core.api.Assertions.assertThat; +import org.baeldung.javabeanconstraints.entities.UserNotNull; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserNotNullUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenNotNullName_thenNoConstraintViolations() { + UserNotNull user = new UserNotNull("John"); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenNullName_thenOneConstraintViolation() { + UserNotNull user = new UserNotNull(null); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenEmptyName_thenNoConstraintViolations() { + UserNotNull user = new UserNotNull(""); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenToString_thenCorrect() { + UserNotNull user = new UserNotNull("John"); + + assertThat(user.toString()).isEqualTo("User{name=John}"); + } +} diff --git a/jaxb/src/main/resources/logback.xml b/jaxb/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/jaxb/src/main/resources/logback.xml +++ b/jaxb/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/jee-7-security/README.md b/jee-7-security/README.md new file mode 100644 index 0000000000..314de6d957 --- /dev/null +++ b/jee-7-security/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Securing Java EE with Spring Security](http://www.baeldung.com/java-ee-spring-security) diff --git a/jee-7-security/pom.xml b/jee-7-security/pom.xml new file mode 100644 index 0000000000..622ca19903 --- /dev/null +++ b/jee-7-security/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + jee-7-security + 1.0-SNAPSHOT + war + jee-7-security + JavaEE 7 Spring Security Application + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + javax + javaee-api + ${javaee_api.version} + provided + + + com.sun.faces + jsf-api + ${com.sun.faces.jsf.version} + + + com.sun.faces + jsf-impl + ${com.sun.faces.jsf.version} + + + javax.servlet + jstl + ${jstl.version} + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + javax.servlet.jsp + jsp-api + ${jsp-api.version} + provided + + + taglibs + standard + ${taglibs.standard.version} + + + + javax.mvc + javax.mvc-api + 1.0-pr + + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + + + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + false + + + + + + + 7.0 + 2.2.14 + 2.2 + 1.1.2 + 4.2.3.RELEASE + + + diff --git a/jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java b/jee-7-security/src/main/java/com/baeldung/springsecurity/SecurityWebApplicationInitializer.java similarity index 88% rename from jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java rename to jee-7-security/src/main/java/com/baeldung/springsecurity/SecurityWebApplicationInitializer.java index e6a05f7b71..e3e2ed80e6 100644 --- a/jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java +++ b/jee-7-security/src/main/java/com/baeldung/springsecurity/SecurityWebApplicationInitializer.java @@ -1,4 +1,4 @@ -package com.baeldung.springSecurity; +package com.baeldung.springsecurity; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; diff --git a/jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java b/jee-7-security/src/main/java/com/baeldung/springsecurity/SpringSecurityConfig.java similarity index 97% rename from jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java rename to jee-7-security/src/main/java/com/baeldung/springsecurity/SpringSecurityConfig.java index bda8930f36..70be1f91ce 100644 --- a/jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java +++ b/jee-7-security/src/main/java/com/baeldung/springsecurity/SpringSecurityConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.springSecurity; +package com.baeldung.springsecurity; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; diff --git a/jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java b/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/HomeController.java similarity index 89% rename from jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java rename to jee-7-security/src/main/java/com/baeldung/springsecurity/controller/HomeController.java index 53fd9f4b81..1662f38609 100644 --- a/jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java +++ b/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/HomeController.java @@ -1,4 +1,4 @@ -package com.baeldung.springSecurity.controller; +package com.baeldung.springsecurity.controller; import javax.mvc.annotation.Controller; import javax.ws.rs.GET; diff --git a/jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java b/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java similarity index 82% rename from jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java rename to jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java index a7e7bb471d..45d7ff3d2c 100644 --- a/jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java +++ b/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java @@ -1,4 +1,4 @@ -package com.baeldung.springSecurity.controller; +package com.baeldung.springsecurity.controller; import javax.mvc.annotation.Controller; import javax.ws.rs.GET; diff --git a/jee-7-security/src/main/resources/logback.xml b/jee-7-security/src/main/resources/logback.xml new file mode 100644 index 0000000000..c8c077ba1d --- /dev/null +++ b/jee-7-security/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/src/main/resources/application.properties b/jee-7-security/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from spring-boot-logging-log4j2/src/main/resources/application.properties rename to jee-7-security/src/main/webapp/WEB-INF/beans.xml diff --git a/jee-7-security/src/main/webapp/WEB-INF/faces-config.xml b/jee-7-security/src/main/webapp/WEB-INF/faces-config.xml new file mode 100644 index 0000000000..1f4085458f --- /dev/null +++ b/jee-7-security/src/main/webapp/WEB-INF/faces-config.xml @@ -0,0 +1,8 @@ + + + \ No newline at end of file diff --git a/jee-7/src/main/webapp/WEB-INF/spring/security.xml b/jee-7-security/src/main/webapp/WEB-INF/spring/security.xml similarity index 100% rename from jee-7/src/main/webapp/WEB-INF/spring/security.xml rename to jee-7-security/src/main/webapp/WEB-INF/spring/security.xml diff --git a/jee-7/src/main/webapp/WEB-INF/views/admin.jsp b/jee-7-security/src/main/webapp/WEB-INF/views/admin.jsp similarity index 100% rename from jee-7/src/main/webapp/WEB-INF/views/admin.jsp rename to jee-7-security/src/main/webapp/WEB-INF/views/admin.jsp diff --git a/jee-7/src/main/webapp/WEB-INF/views/home.jsp b/jee-7-security/src/main/webapp/WEB-INF/views/home.jsp similarity index 100% rename from jee-7/src/main/webapp/WEB-INF/views/home.jsp rename to jee-7-security/src/main/webapp/WEB-INF/views/home.jsp diff --git a/jee-7/src/main/webapp/WEB-INF/views/login.jsp b/jee-7-security/src/main/webapp/WEB-INF/views/login.jsp similarity index 100% rename from jee-7/src/main/webapp/WEB-INF/views/login.jsp rename to jee-7-security/src/main/webapp/WEB-INF/views/login.jsp diff --git a/jee-7/src/main/webapp/WEB-INF/views/user.jsp b/jee-7-security/src/main/webapp/WEB-INF/views/user.jsp similarity index 100% rename from jee-7/src/main/webapp/WEB-INF/views/user.jsp rename to jee-7-security/src/main/webapp/WEB-INF/views/user.jsp diff --git a/jee-7-security/src/main/webapp/WEB-INF/web.xml b/jee-7-security/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..e656ffc5be --- /dev/null +++ b/jee-7-security/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,71 @@ + + + + + Faces Servlet + javax.faces.webapp.FacesServlet + + + Faces Servlet + *.jsf + + + javax.faces.PROJECT_STAGE + Development + + + State saving method: 'client' or 'server' (default). See JSF Specification section 2.5.2 + javax.faces.STATE_SAVING_METHOD + client + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + index.jsf + welcome.jsf + index.html + index.jsp + + \ No newline at end of file diff --git a/jee-7/src/main/webapp/index.jsp b/jee-7-security/src/main/webapp/index.jsp similarity index 100% rename from jee-7/src/main/webapp/index.jsp rename to jee-7-security/src/main/webapp/index.jsp diff --git a/jee-7/src/main/webapp/secure.jsp b/jee-7-security/src/main/webapp/secure.jsp similarity index 100% rename from jee-7/src/main/webapp/secure.jsp rename to jee-7-security/src/main/webapp/secure.jsp diff --git a/jee-7/README.md b/jee-7/README.md index 08a180cfa3..a2493e561b 100644 --- a/jee-7/README.md +++ b/jee-7/README.md @@ -5,4 +5,3 @@ - [Introduction to JAX-WS](http://www.baeldung.com/jax-ws) - [A Guide to Java EE Web-Related Annotations](http://www.baeldung.com/javaee-web-annotations) - [Introduction to Testing with Arquillian](http://www.baeldung.com/arquillian) -- [Securing Java EE with Spring Security](http://www.baeldung.com/java-ee-spring-security) diff --git a/jee-7/pom.xml b/jee-7/pom.xml index d0246f650a..4f6e6a20fb 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - com.baeldung jee-7 1.0-SNAPSHOT war @@ -131,7 +130,7 @@ maven-war-plugin ${maven-war-plugin.version} - webapp + src/main/webapp false @@ -384,10 +383,6 @@ - - ${maven.min.version} - - bintray-mvc-spec-maven @@ -418,7 +413,7 @@ 1.0.0.Final 2.6 4.2.3.RELEASE - 2.17 + 2.21.0 1.1.2 2.4 2.2.14 diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java similarity index 94% rename from jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java index a487d4c3b1..30dc82aa58 100644 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java +++ b/jee-7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java @@ -1,4 +1,4 @@ -package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations; +package com.baeldung.javaeeannotations; import java.io.IOException; import java.io.PrintWriter; diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java similarity index 82% rename from jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java index dc9a91d059..ee1b624cd1 100644 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java +++ b/jee-7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java @@ -1,4 +1,4 @@ -package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations; +package com.baeldung.javaeeannotations; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt deleted file mode 100644 index 0f95e588b8..0000000000 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt +++ /dev/null @@ -1,76 +0,0 @@ -About the application ---------------------- -This application demonstrates the usage of JavaEE Web Annotations. - - -Contents of the application ---------------------------- -1. AccountServlet.java - Demonstrates the @WebServlet and @ServletSecurity annotation. - -NOTES: @WebServlet annotation designates the AccountServlet class as a Servlet component. - The usage of its parameters 'urlPatterns' & 'initParams' can be observed. - An initialization parameter 'type' is being set to denote the type of the bank account. - - @ServletSecurity annotation imposes security constraints on the AccountServlet based on - the tomcat-users.xml. -   - This code assumes that your tomcat-users.xml looks as follows: - - - - - - - -   -N.B : To see @ServletSecurity annotation in action, please uncomment the annotation code - for @ServletSecurity. - - -2. BankAppServletContextListener.java - Demonstrates the @WebListener annotation for denoting a class as a ServletContextListener. - -NOTES: Sets a Servlet context attribute ATTR_DEFAULT_LANGUAGE to 'english' on web application start up, - which can then be used throughout the application. - - -3. LogInFilter.java - Demonstrates the @WebFilter annotation. - -NOTES: @WebFilter annotation designates the LogInFilter class as a Filter component. - It filters all requests to the bank account servlet and redirects them to - the login page. - -N.B : To see @WebFilter annotation in action, please uncomment the annotation code for @WebFilter. - - -4. UploadCustomerDocumentsServlet.java - Demonstrates the @MultipartConfig annotation. - -NOTES: @MultipartConfig anotation designates the UploadCustomerDocumentsServlet Servlet component, - to handle multipart/form-data requests. - To see it in action, deploy the web application an access the url: http://:/JavaEEAnnotationsSample/upload.jsp - Once you upload a file from here, it will get uploaded to D:/custDocs (assuming such a folder exists). - - -5. index.jsp - This is the welcome page. - -NOTES: You can enter a deposit amount here and click on the 'Deposit' button to see the AccountServlet in action. - -6. login.jsp - All requests to the AccountServlet are redirected to this page, if the LogInFilter is imposed. - -7. upload.jsp - Demonstrates the usage of handling multipart/form-data requests by the UploadCustomerDocumentsServlet. - - -Building and Running the application ------------------------------------- -To build the application: - -1. Open the project in eclipse -2. Right click on it in eclispe and choose Run As > Maven build -3. Give 'clean install' under Goals -4. This should build the WAR file of the application - -To run the application: - -1. Right click on the project -2. Run as > Run on Server -3. This will start you Tomcat server and deploy the application (Provided that you have configured Tomcat in your eclipse) -4. You should now be able to access the url : http://:/JavaEEAnnotationsSample diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml deleted file mode 100644 index 6a0dd05180..0000000000 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - 4.0.0 - com.baeldung.javaeeannotations - JavaEEAnnotationsSample - 0.0.1-SNAPSHOT - war - JavaEEAnnotationsSample - JavaEEAnnotationsSample - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - javax.annotation - javax.annotation-api - 1.3 - - - - javax.servlet - javax.servlet-api - 3.1.0 - - - - javax.servlet.jsp - jsp-api - 2.1 - - - - - - - - org.apache.maven.plugins - maven-war-plugin - 2.4 - - src/main/webapp - SpringFieldConstructorInjection - false - - - - - JavaEEAnnotationsSample - - \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index a92885ec11..0000000000 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - BASIC - default - - diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp deleted file mode 100644 index 6892cb0420..0000000000 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp +++ /dev/null @@ -1,12 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Login - - -Login Here... - - \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java similarity index 90% rename from jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java index bfe1a39377..5ee420f6a2 100644 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java +++ b/jee-7/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations; +package com.baeldung.javaeeannotations; import java.io.IOException; diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java similarity index 90% rename from jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java index 6945f663bb..28922dba46 100644 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java +++ b/jee-7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java @@ -1,4 +1,4 @@ -package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations; +package com.baeldung.javaeeannotations; import java.io.IOException; import java.io.PrintWriter; diff --git a/jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java b/jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java deleted file mode 100755 index f8e7982253..0000000000 --- a/jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.springSecurity; - -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; - -/** - * Application class required by JAX-RS. If you don't want to have any - * prefix in the URL, you can set the application path to "/". - */ -@ApplicationPath("/") -public class ApplicationConfig extends Application { - -} diff --git a/jee-7/src/main/webapp/WEB-INF/web.xml b/jee-7/src/main/webapp/WEB-INF/web.xml index 1bcbb96e24..e656ffc5be 100644 --- a/jee-7/src/main/webapp/WEB-INF/web.xml +++ b/jee-7/src/main/webapp/WEB-INF/web.xml @@ -1,5 +1,8 @@ - + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + - - io.github.jhipster - jhipster - ${jhipster.server.version} - - - io.dropwizard.metrics - metrics-core - - - io.dropwizard.metrics - metrics-annotation - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-json - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-jvm - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-servlet - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-servlets - com.fasterxml.jackson.datatype jackson-datatype-hibernate5 @@ -59,11 +118,11 @@ com.fasterxml.jackson.datatype - jackson-datatype-jsr310 + jackson-datatype-json-org com.fasterxml.jackson.datatype - jackson-datatype-json-org + jackson-datatype-jsr310 com.h2database @@ -82,34 +141,12 @@ com.hazelcast hazelcast-spring - - org.awaitility - awaitility - ${awaitility.version} - test - com.jayway.jsonpath json-path test - - io.springfox - springfox-swagger2 - ${springfox.version} - - - org.mapstruct - mapstruct - - - - - io.springfox - springfox-bean-validators - ${springfox.version} - com.mattbertolini liquibase-slf4j @@ -121,16 +158,16 @@ ${metrics-spring.version} - com.codahale.metrics metrics-annotation + com.codahale.metrics - com.codahale.metrics metrics-core + com.codahale.metrics - com.codahale.metrics metrics-healthchecks + com.codahale.metrics @@ -148,12 +185,56 @@ commons-io commons-io - ${commons-io.version} - org.apache.commons - commons-lang3 - ${commons-lang.version} + io.dropwizard.metrics + metrics-annotation + + + io.dropwizard.metrics + metrics-core + + + io.dropwizard.metrics + metrics-json + + + io.dropwizard.metrics + metrics-jvm + + + io.dropwizard.metrics + metrics-servlet + + + io.dropwizard.metrics + metrics-servlets + + + io.github.jhipster + jhipster + ${jhipster.server.version} + + + io.jsonwebtoken + jjwt + ${jjwt.version} + + + io.springfox + springfox-bean-validators + ${springfox.version} + + + io.springfox + springfox-swagger2 + ${springfox.version} + + + mapstruct + org.mapstruct + + javax.cache @@ -163,11 +244,41 @@ mysql mysql-connector-java + + net.logstash.logback + logstash-logback-encoder + ${logstash-logback-encoder.version} + + + logback-core + ch.qos.logback + + + logback-classic + ch.qos.logback + + + logback-access + ch.qos.logback + + + + + org.apache.commons + commons-lang3 + ${commons-lang.version} + org.assertj assertj-core test + + org.awaitility + awaitility + ${awaitility.version} + test + org.hibernate hibernate-envers @@ -216,6 +327,10 @@ org.springframework.boot spring-boot-starter-aop + + org.springframework.boot + spring-boot-starter-cloud-connectors + org.springframework.boot spring-boot-starter-data-jpa @@ -232,16 +347,6 @@ org.springframework.boot spring-boot-starter-security - - org.springframework.security - spring-security-test - test - - - org.springframework.boot - spring-boot-test - test - org.springframework.boot spring-boot-starter-thymeleaf @@ -251,15 +356,15 @@ spring-boot-starter-web - org.springframework.boot spring-boot-starter-tomcat + org.springframework.boot - io.jsonwebtoken - jjwt - ${jjwt.version} + org.springframework.boot + spring-boot-test + test @@ -268,19 +373,31 @@ org.springframework.cloud - spring-cloud-starter-ribbon - - - - io.netty - netty-transport-native-epoll - - + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.cloud + spring-cloud-starter-feign org.springframework.cloud spring-cloud-starter-hystrix + + org.springframework.cloud + spring-cloud-starter-ribbon + + + + netty-transport-native-epoll + io.netty + + + org.springframework.cloud spring-cloud-starter-spectator @@ -289,51 +406,51 @@ org.springframework.retry spring-retry - - org.springframework.cloud - spring-cloud-starter-eureka - - - org.springframework.cloud - spring-cloud-starter-config - - - org.springframework.cloud - spring-cloud-starter-feign - - - net.logstash.logback - logstash-logback-encoder - ${logstash-logback-encoder.version} - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-access - - - - - org.springframework.boot - spring-boot-starter-cloud-connectors - org.springframework.security spring-security-data + + org.springframework.security + spring-security-test + test + spring-boot:run + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + prepare-agent + + + + + + + + + + + + com.github.ekryd.sortpom @@ -356,6 +473,22 @@ false + + com.spotify + docker-maven-plugin + ${docker-maven-plugin.version} + + dealerapp + src/main/docker + + + / + ${project.build.directory} + ${project.build.finalName}.war + + + + org.apache.maven.plugins maven-compiler-plugin @@ -373,6 +506,7 @@ org.apache.maven.plugins maven-eclipse-plugin + ${maven-eclipse-plugin.version} true true @@ -479,28 +613,16 @@ - - org.sonarsource.scanner.maven - sonar-maven-plugin - ${sonar-maven-plugin.version} - org.liquibase liquibase-maven-plugin ${liquibase.version} - - src/main/resources/config/liquibase/master.xml - src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml - org.h2.Driver - jdbc:h2:file:./target/h2db/db/dealerapp - - dealerapp - - hibernate:spring:com.dealer.app.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy - true - debug - + + javax.validation + validation-api + ${validation-api.version} + org.javassist javassist @@ -516,12 +638,24 @@ spring-boot-starter-data-jpa ${project.parent.version} - - javax.validation - validation-api - ${validation-api.version} - + + src/main/resources/config/liquibase/master.xml + src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml + org.h2.Driver + jdbc:h2:file:./target/h2db/db/dealerapp + + dealerapp + + hibernate:spring:com.dealer.app.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy + true + debug + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + ${sonar-maven-plugin.version} org.springframework.boot @@ -532,58 +666,8 @@ - - com.spotify - docker-maven-plugin - ${docker-maven-plugin.version} - - dealerapp - src/main/docker - - - / - ${project.build.directory} - ${project.build.finalName}.war - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.jacoco - - jacoco-maven-plugin - - - ${jacoco-maven-plugin.version} - - - prepare-agent - - - - - - - - - - - - @@ -604,24 +688,12 @@ true - - - org.springframework.boot - spring-boot-starter-undertow - - - org.springframework.boot - spring-boot-devtools - true - - org.apache.maven.plugins maven-war-plugin - - + @@ -631,15 +703,20 @@ dev${profile.no-liquibase} - - - prod + + org.springframework.boot + spring-boot-devtools + true + org.springframework.boot spring-boot-starter-undertow + + + prod @@ -655,15 +732,11 @@ org.apache.maven.plugins maven-war-plugin - - + org.springframework.boot spring-boot-maven-plugin - - true - @@ -671,6 +744,9 @@ + + true + @@ -680,56 +756,20 @@ prod${profile.swagger}${profile.no-liquibase} + + + org.springframework.boot + spring-boot-starter-undertow + + cc - - - org.springframework.boot - spring-boot-starter-undertow - - - org.springframework.boot - spring-boot-devtools - true - - - - org.apache.maven.plugins - maven-war-plugin - - src/main/webapp/ - - - - org.springframework.boot - spring-boot-maven-plugin - - true - true - true - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - default-compile - none - - - default-testCompile - none - - - net.alchim31.maven scala-maven-plugin @@ -758,6 +798,37 @@ ${scala.version} + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + none + + + default-testCompile + none + + + + + org.apache.maven.plugins + maven-war-plugin + + src/main/webapp/ + + + + org.springframework.boot + spring-boot-maven-plugin + + true + true + true + + + @@ -766,6 +837,17 @@ dev,swagger + + + org.springframework.boot + spring-boot-devtools + true + + + org.springframework.boot + spring-boot-starter-undertow + + @@ -788,12 +870,12 @@ io.prometheus - simpleclient_servlet + simpleclient_dropwizard ${prometheus-simpleclient.version} io.prometheus - simpleclient_dropwizard + simpleclient_servlet ${prometheus-simpleclient.version} @@ -811,96 +893,4 @@ - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - ${maven.version} - - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 2.5 - 3.5 - 0.4.13 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 4.8 - jdt_apt - 1.1.0.Final - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - 0.0.20 - - ${project.build.directory}/test-results - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - diff --git a/jhipster/jhipster-microservice/gateway-app/package.json b/jhipster/jhipster-microservice/gateway-app/package.json index ece70314ab..abdff9ffe3 100644 --- a/jhipster/jhipster-microservice/gateway-app/package.json +++ b/jhipster/jhipster-microservice/gateway-app/package.json @@ -49,7 +49,7 @@ "karma-phantomjs-launcher": "1.0.2", "karma-script-launcher": "1.0.0", "lazypipe": "1.0.1", - "lodash": "4.15.0", + "lodash": "4.17.10", "main-bower-files": "2.13.1", "map-stream": "0.0.6", "phantomjs-prebuilt": "2.1.12", diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index 85b3688efa..ed0c929027 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -1,53 +1,136 @@ - + 4.0.0 - com.gateway - gateway - 0.0.1-SNAPSHOT - war - Gateway - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + jhipster-microservice + com.baeldung.jhipster + 1.0.0-SNAPSHOT + com.gateway + gateway-app + war + gateway-app + + + ${maven.version} + + + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 3.6.0 + 1.10 + 2.5 + 3.5 + 0.4.13 + 1.3 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + 1.3.0 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + - io.github.jhipster - jhipster - ${jhipster.server.version} + com.datastax.cassandra + cassandra-driver-core + + + metrics-core + com.codahale.metrics + + - io.dropwizard.metrics - metrics-core + com.datastax.cassandra + cassandra-driver-extras + ${cassandra-driver.version} - io.dropwizard.metrics - metrics-annotation - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-json - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-jvm - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-servlet - ${dropwizard-metrics.version} - - - io.dropwizard.metrics - metrics-servlets + com.datastax.cassandra + cassandra-driver-mapping com.fasterxml.jackson.datatype @@ -59,11 +142,11 @@ com.fasterxml.jackson.datatype - jackson-datatype-jsr310 + jackson-datatype-json-org com.fasterxml.jackson.datatype - jackson-datatype-json-org + jackson-datatype-jsr310 com.h2database @@ -82,34 +165,12 @@ com.hazelcast hazelcast-spring - - org.awaitility - awaitility - ${awaitility.version} - test - com.jayway.jsonpath json-path test - - io.springfox - springfox-swagger2 - ${springfox.version} - - - org.mapstruct - mapstruct - - - - - io.springfox - springfox-bean-validators - ${springfox.version} - com.mattbertolini liquibase-slf4j @@ -121,16 +182,16 @@ ${metrics-spring.version} - com.codahale.metrics metrics-annotation + com.codahale.metrics - com.codahale.metrics metrics-core + com.codahale.metrics - com.codahale.metrics metrics-healthchecks + com.codahale.metrics @@ -148,17 +209,60 @@ commons-codec commons-codec - ${commons-codec.version} commons-io commons-io - ${commons-io.version} - org.apache.commons - commons-lang3 - ${commons-lang.version} + io.dropwizard.metrics + metrics-annotation + + + io.dropwizard.metrics + metrics-core + + + io.dropwizard.metrics + metrics-json + + + io.dropwizard.metrics + metrics-jvm + + + io.dropwizard.metrics + metrics-servlet + + + io.dropwizard.metrics + metrics-servlets + + + io.github.jhipster + jhipster + ${jhipster.server.version} + + + io.jsonwebtoken + jjwt + ${jjwt.version} + + + io.springfox + springfox-bean-validators + ${springfox.version} + + + io.springfox + springfox-swagger2 + ${springfox.version} + + + mapstruct + org.mapstruct + + javax.cache @@ -173,11 +277,41 @@ lz4 ${lz4.version} + + net.logstash.logback + logstash-logback-encoder + ${logstash-logback-encoder.version} + + + logback-core + ch.qos.logback + + + logback-classic + ch.qos.logback + + + logback-access + ch.qos.logback + + + + + org.apache.commons + commons-lang3 + ${commons-lang.version} + org.assertj assertj-core test + + org.awaitility + awaitility + ${awaitility.version} + test + org.hibernate hibernate-envers @@ -226,6 +360,10 @@ org.springframework.boot spring-boot-starter-aop + + org.springframework.boot + spring-boot-starter-cloud-connectors + org.springframework.boot spring-boot-starter-data-jpa @@ -247,16 +385,6 @@ spring-boot-starter-test test - - org.springframework.security - spring-security-test - test - - - org.springframework.boot - spring-boot-test - test - org.springframework.boot spring-boot-starter-thymeleaf @@ -266,40 +394,15 @@ spring-boot-starter-web - org.springframework.boot spring-boot-starter-tomcat + org.springframework.boot - io.jsonwebtoken - jjwt - ${jjwt.version} - - - - com.datastax.cassandra - cassandra-driver-core - - - com.codahale.metrics - metrics-core - - - - - com.datastax.cassandra - cassandra-driver-extras - ${cassandra-driver.version} - - - com.datastax.cassandra - cassandra-driver-mapping - - - - org.springframework.cloud - spring-cloud-starter-zuul + org.springframework.boot + spring-boot-test + test org.springframework.cloud @@ -307,72 +410,105 @@ org.springframework.cloud - spring-cloud-starter-ribbon - - - - io.netty - netty-transport-native-epoll - - - - - org.springframework.cloud - spring-cloud-starter-hystrix - - - org.springframework.cloud - spring-cloud-starter-spectator - - - org.springframework.retry - spring-retry + spring-cloud-starter-config org.springframework.cloud spring-cloud-starter-eureka - - org.springframework.cloud - spring-cloud-starter-config - org.springframework.cloud spring-cloud-starter-feign - net.logstash.logback - logstash-logback-encoder - ${logstash-logback-encoder.version} + org.springframework.cloud + spring-cloud-starter-hystrix + + + org.springframework.cloud + spring-cloud-starter-ribbon + - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-access + netty-transport-native-epoll + io.netty - org.springframework.boot - spring-boot-starter-cloud-connectors + org.springframework.cloud + spring-cloud-starter-spectator + + + + org.springframework.cloud + spring-cloud-starter-zuul + + + org.springframework.retry + spring-retry org.springframework.security spring-security-data + + org.springframework.security + spring-security-test + test + spring-boot:run + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + prepare-agent + + + + + + + + + com.github.eirslett + frontend-maven-plugin + ${frontend-maven-plugin.version} + + install-node-and-yarn + yarn + bower + gulp + + + + + + + + + + + + com.github.ekryd.sortpom @@ -395,6 +531,22 @@ false + + com.spotify + docker-maven-plugin + ${docker-maven-plugin.version} + + gateway + src/main/docker + + + / + ${project.build.directory} + ${project.build.finalName}.war + + + + org.apache.maven.plugins maven-compiler-plugin @@ -412,6 +564,7 @@ org.apache.maven.plugins maven-eclipse-plugin + ${maven-eclipse-plugin.version} true true @@ -518,28 +671,16 @@ - - org.sonarsource.scanner.maven - sonar-maven-plugin - ${sonar-maven-plugin.version} - org.liquibase liquibase-maven-plugin ${liquibase.version} - - src/main/resources/config/liquibase/master.xml - src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml - org.h2.Driver - jdbc:h2:file:./target/h2db/db/gateway - - gateway - - hibernate:spring:com.gateway.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy - true - debug - + + javax.validation + validation-api + ${validation-api.version} + org.javassist javassist @@ -555,12 +696,24 @@ spring-boot-starter-data-jpa ${project.parent.version} - - javax.validation - validation-api - ${validation-api.version} - + + src/main/resources/config/liquibase/master.xml + src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml + org.h2.Driver + jdbc:h2:file:./target/h2db/db/gateway + + gateway + + hibernate:spring:com.gateway.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy + true + debug + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + ${sonar-maven-plugin.version} org.springframework.boot @@ -571,74 +724,8 @@ - - com.spotify - docker-maven-plugin - ${docker-maven-plugin.version} - - gateway - src/main/docker - - - / - ${project.build.directory} - ${project.build.finalName}.war - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.jacoco - - jacoco-maven-plugin - - - ${jacoco-maven-plugin.version} - - - prepare-agent - - - - - - - - - com.github.eirslett - frontend-maven-plugin - ${frontend-maven-plugin.version} - - install-node-and-yarn - yarn - bower - gulp - - - - - - - - - - - - @@ -659,17 +746,6 @@ true - - - org.springframework.boot - spring-boot-starter-undertow - - - org.springframework.boot - spring-boot-devtools - true - - @@ -687,48 +763,22 @@ dev${profile.no-liquibase} - - - prod + + org.springframework.boot + spring-boot-devtools + true + org.springframework.boot spring-boot-starter-undertow + + + prod - - maven-clean-plugin - - - - target/www/ - - - - - - org.apache.maven.plugins - maven-war-plugin - - target/www/ - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - - build-info - - - - com.github.eirslett frontend-maven-plugin @@ -773,16 +823,47 @@ gulp test + test gulp - test test --no-notification + + maven-clean-plugin + + + + target/www/ + + + + + + org.apache.maven.plugins + maven-war-plugin + + target/www/ + + + + org.springframework.boot + spring-boot-maven-plugin + + + + build-info + + + + + true + + @@ -791,56 +872,20 @@ prod${profile.swagger}${profile.no-liquibase} + + + org.springframework.boot + spring-boot-starter-undertow + + cc - - - org.springframework.boot - spring-boot-starter-undertow - - - org.springframework.boot - spring-boot-devtools - true - - - - org.apache.maven.plugins - maven-war-plugin - - src/main/webapp/ - - - - org.springframework.boot - spring-boot-maven-plugin - - true - true - true - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - default-compile - none - - - default-testCompile - none - - - net.alchim31.maven scala-maven-plugin @@ -869,6 +914,37 @@ ${scala.version} + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + none + + + default-testCompile + none + + + + + org.apache.maven.plugins + maven-war-plugin + + src/main/webapp/ + + + + org.springframework.boot + spring-boot-maven-plugin + + true + true + true + + + @@ -877,6 +953,17 @@ dev,swagger + + + org.springframework.boot + spring-boot-devtools + true + + + org.springframework.boot + spring-boot-starter-undertow + + @@ -899,12 +986,12 @@ io.prometheus - simpleclient_servlet + simpleclient_dropwizard ${prometheus-simpleclient.version} io.prometheus - simpleclient_dropwizard + simpleclient_servlet ${prometheus-simpleclient.version} @@ -922,99 +1009,4 @@ - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - ${maven.version} - - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 1.10 - 2.5 - 3.5 - 0.4.13 - 1.3 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 4.8 - 1.3.0 - jdt_apt - 1.1.0.Final - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - 0.0.20 - - ${project.build.directory}/test-results - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - diff --git a/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/service/UserServiceIntIntegrationTest.java b/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/service/UserServiceIntegrationTest.java similarity index 100% rename from jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/service/UserServiceIntIntegrationTest.java rename to jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/service/UserServiceIntegrationTest.java diff --git a/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/UserResourceIntIntegrationTest.java b/jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/UserResourceIntegrationTest.java similarity index 100% rename from jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/UserResourceIntIntegrationTest.java rename to jhipster/jhipster-microservice/gateway-app/src/test/java/com/gateway/web/rest/UserResourceIntegrationTest.java diff --git a/jhipster/jhipster-microservice/pom.xml b/jhipster/jhipster-microservice/pom.xml new file mode 100644 index 0000000000..4a60e47f87 --- /dev/null +++ b/jhipster/jhipster-microservice/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + jhipster-microservice + pom + JHipster Microservice + + + jhipster + com.baeldung.jhipster + 1.0.0-SNAPSHOT + + + + car-app + dealer-app + gateway-app + + diff --git a/jhipster/jhipster-monolithic/package.json b/jhipster/jhipster-monolithic/package.json index 40bbd28799..5f72047fb3 100644 --- a/jhipster/jhipster-monolithic/package.json +++ b/jhipster/jhipster-monolithic/package.json @@ -64,7 +64,7 @@ "karma-sourcemap-loader": "0.3.7", "karma-webpack": "2.0.2", "lazypipe": "1.0.1", - "lodash": "4.17.4", + "lodash": "4.17.10", "map-stream": "0.0.6", "phantomjs-prebuilt": "2.1.14", "protractor": "5.1.1", diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index 8b753f6f93..e242668759 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -1,18 +1,14 @@ - 4.0.0 - com.baeldung jhipster-monolithic - 0.0.1-SNAPSHOT war JHipster Monolithic Application - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 + jhipster + com.baeldung.jhipster + 1.0.0-SNAPSHOT @@ -90,8 +86,7 @@ io.dropwizard.metrics metrics-annotation - ${dropwizard-metrics.version} - + io.dropwizard.metrics metrics-core @@ -99,18 +94,15 @@ io.dropwizard.metrics metrics-json - ${dropwizard-metrics.version} - + io.dropwizard.metrics metrics-jvm - ${dropwizard-metrics.version} - + io.dropwizard.metrics metrics-servlet - ${dropwizard-metrics.version} - + io.dropwizard.metrics metrics-servlets @@ -419,6 +411,7 @@ org.apache.maven.plugins maven-eclipse-plugin + ${maven-eclipse-plugin.version} true true @@ -494,18 +487,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - - alphabetical - - **/*IntTest.java - - - - org.jacoco jacoco-maven-plugin @@ -538,7 +519,7 @@ org.liquibase liquibase-maven-plugin - ${liquibase.version} + ${liquibase-maven-plugin.version} javax.validation @@ -898,10 +879,6 @@ - - ${maven.version} - - -Djava.security.egd=file:/dev/./urandom -Xmx256m 3.6.2 @@ -922,11 +899,13 @@ 1.1.3 3.6 2.0.0 + 3.6.2 4.8 jdt_apt 1.1.0.Final 1.4.1 3.0.1 + 2.10 yyyyMMddHHmmss 3.0.0 3.1.3 diff --git a/jhipster/pom.xml b/jhipster/pom.xml new file mode 100644 index 0000000000..2bf7bcb233 --- /dev/null +++ b/jhipster/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + com.baeldung.jhipster + jhipster + 1.0.0-SNAPSHOT + pom + JHipster + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 + + + + jhipster-monolithic + jhipster-microservice + + + diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 189e957e42..6bf9f4426a 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -3,10 +3,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 io.jsonwebtoken - jjwtfun + jjwt 0.0.1-SNAPSHOT jar - jjwtfun + jjwt Exercising the JJWT diff --git a/jni/pom.xml b/jni/pom.xml index 274b9b58c3..d4cc409d33 100644 --- a/jni/pom.xml +++ b/jni/pom.xml @@ -1,21 +1,12 @@ 4.0.0 - com.baeldung jni - 0.0.1-SNAPSHOT - - - junit - junit - ${junit.version} - test - - - - - 4.8.1 - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + \ No newline at end of file diff --git a/jni/src/test/java/com/baeldung/jni/JNINativeTests.java b/jni/src/test/java/com/baeldung/jni/JNINativeManualTest.java similarity index 98% rename from jni/src/test/java/com/baeldung/jni/JNINativeTests.java rename to jni/src/test/java/com/baeldung/jni/JNINativeManualTest.java index 42e572d41b..8201945644 100644 --- a/jni/src/test/java/com/baeldung/jni/JNINativeTests.java +++ b/jni/src/test/java/com/baeldung/jni/JNINativeManualTest.java @@ -7,7 +7,7 @@ import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; -public class JNINativeTests { +public class JNINativeManualTest { @Before public void setup() { diff --git a/jnosql/jnosql-artemis/pom.xml b/jnosql/jnosql-artemis/pom.xml index 6186b3510c..9c2bfd1ba0 100644 --- a/jnosql/jnosql-artemis/pom.xml +++ b/jnosql/jnosql-artemis/pom.xml @@ -19,7 +19,7 @@ - ${artifactId} + ${project.artifactId} net.wasdev.wlp.maven.plugins diff --git a/jooby/pom.xml b/jooby/pom.xml index 2867b7f4b6..83dd650701 100644 --- a/jooby/pom.xml +++ b/jooby/pom.xml @@ -1,60 +1,63 @@ - 4.0.0 - jooby - com.baeldung.jooby - 1.0 - jooby + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + jooby + com.baeldung.jooby + 1.0 + jooby - - org.jooby - modules - 1.1.3 - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - org.jooby - jooby-netty - - - org.jooby - jooby-jedis - ${jooby-jedis.version} - - - ch.qos.logback - logback-classic - - - junit - junit - test - - - io.rest-assured - rest-assured - test - - + + + + org.jooby + modules + ${jooby.version} + pom + + + - - - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - - + + + org.jooby + jooby-netty + ${jooby.version} + + + org.jooby + jooby-jedis + ${jooby.version} + + + io.rest-assured + rest-assured + test + ${rest-assured.version} + + - - 1.1.3 - com.baeldung.jooby.App - 1.1.3 - - 2.4.3 - + + + + org.apache.maven.plugins + maven-shade-plugin + ${maven-shade-plugin.version} + + + + + + 1.1.3 + 3.1.1 + com.baeldung.jooby.App + 2.4.3 + diff --git a/jooby/src/test/java/com/baeldung/jooby/AppTest.java b/jooby/src/test/java/com/baeldung/jooby/AppUnitTest.java similarity index 96% rename from jooby/src/test/java/com/baeldung/jooby/AppTest.java rename to jooby/src/test/java/com/baeldung/jooby/AppUnitTest.java index af2626c046..ab7388f5f4 100644 --- a/jooby/src/test/java/com/baeldung/jooby/AppTest.java +++ b/jooby/src/test/java/com/baeldung/jooby/AppUnitTest.java @@ -9,7 +9,7 @@ import org.jooby.test.MockRouter; import org.junit.ClassRule; import org.junit.Test; -public class AppTest { +public class AppUnitTest { @ClassRule public static JoobyRule app = new JoobyRule(new App()); diff --git a/jpa-storedprocedure/README.md b/jpa-storedprocedure/README.md deleted file mode 100644 index 39d6784d8b..0000000000 --- a/jpa-storedprocedure/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) diff --git a/jpa-storedprocedure/pom.xml b/jpa-storedprocedure/pom.xml deleted file mode 100644 index 79fa637cb6..0000000000 --- a/jpa-storedprocedure/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - 4.0.0 - com.baeldung - jpa-storedprocedure - 1.0 - jar - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - javax - javaee-api - ${jee.version} - provided - - - org.hibernate - hibernate-entitymanager - ${hibernate.version} - - - - mysql - mysql-connector-java - ${mysql.version} - - - commons-io - commons-io - ${commons-io.version} - - - - - JpaStoredProcedure - - - maven-assembly-plugin - - ${project.basedir} - - - jar-with-dependencies - - - - - - - - 7.0 - 5.2.5.Final - 6.0.5 - 2.5 - - - \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml b/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index 4c443cb7cf..0000000000 --- a/jpa-storedprocedure/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.model.Car - - - - - - - - - - \ No newline at end of file diff --git a/jsf/pom.xml b/jsf/pom.xml index 19ea4b569f..2ac8a9f7c2 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -36,11 +36,6 @@ ${jstl.version} - - org.springframework - spring-web - ${org.springframework.version} - org.springframework spring-webmvc diff --git a/jsf/src/main/resources/logback.xml b/jsf/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/jsf/src/main/resources/logback.xml +++ b/jsf/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/json-path/src/test/resources/logback.xml b/json-path/src/test/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/json-path/src/test/resources/logback.xml +++ b/json-path/src/test/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/json/README.md b/json/README.md index 1317ada8be..e0679bc60b 100644 --- a/json/README.md +++ b/json/README.md @@ -8,3 +8,5 @@ - [Introduction to JSONForms](http://www.baeldung.com/introduction-to-jsonforms) - [Introduction to JsonPath](http://www.baeldung.com/guide-to-jayway-jsonpath) - [Introduction to JSON-Java (org.json)](http://www.baeldung.com/java-org-json) +- [Overview of JSON Pointer](https://www.baeldung.com/json-pointer) +- [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api) \ No newline at end of file diff --git a/json/pom.xml b/json/pom.xml index c55e833b40..b688baec06 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -32,12 +32,44 @@ org.json json 20171018 + + + javax.json.bind + javax.json.bind-api + ${jsonb-api.version} + + + junit + junit + 4.12 + test + + + + org.glassfish + javax.json + 1.1.2 + + + org.eclipse + yasson + ${yasson.version} + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + test 1.4.1 1.2.21 + 1.0 + 4.1 + 1.0.1 diff --git a/jsonb/src/main/java/com/baeldung/adapter/PersonAdapter.java b/json/src/main/java/com/baeldung/adapter/PersonAdapter.java similarity index 100% rename from jsonb/src/main/java/com/baeldung/adapter/PersonAdapter.java rename to json/src/main/java/com/baeldung/adapter/PersonAdapter.java diff --git a/jsonb/src/main/java/com/baeldung/jsonb/Person.java b/json/src/main/java/com/baeldung/jsonb/Person.java similarity index 100% rename from jsonb/src/main/java/com/baeldung/jsonb/Person.java rename to json/src/main/java/com/baeldung/jsonb/Person.java diff --git a/json/src/main/java/com/baeldung/jsonpointer/JsonPointerCrud.java b/json/src/main/java/com/baeldung/jsonpointer/JsonPointerCrud.java new file mode 100644 index 0000000000..4398aa7867 --- /dev/null +++ b/json/src/main/java/com/baeldung/jsonpointer/JsonPointerCrud.java @@ -0,0 +1,95 @@ +package com.baeldung.jsonpointer; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonPointer; +import javax.json.JsonReader; +import javax.json.JsonString; +import javax.json.JsonStructure; + +public class JsonPointerCrud { + + private JsonStructure jsonStructure = null; + + public JsonPointerCrud(String fileName) throws IOException { + + try (JsonReader reader = Json.createReader(Files.newBufferedReader(Paths.get(fileName)))) { + jsonStructure = reader.read(); + } catch (FileNotFoundException e) { + System.out.println("Error to open json file: " + e.getMessage()); + } + + } + + public JsonPointerCrud(InputStream stream) { + + JsonReader reader = Json.createReader(stream); + jsonStructure = reader.read(); + reader.close(); + + } + + public JsonStructure insert(String key, String value) { + + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonString jsonValue = Json.createValue(value); + jsonStructure = jsonPointer.add(jsonStructure, jsonValue); + + return jsonStructure; + + } + + public JsonStructure update(String key, String newValue) { + + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonString jsonNewValue = Json.createValue(newValue); + jsonStructure = jsonPointer.replace(jsonStructure, jsonNewValue); + + return jsonStructure; + } + + public JsonStructure delete(String key) { + + JsonPointer jsonPointer = Json.createPointer("/" + key); + jsonPointer.getValue(jsonStructure); + jsonStructure = jsonPointer.remove(jsonStructure); + + return jsonStructure; + + } + + public String fetchValueFromKey(String key) { + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonString jsonString = (JsonString) jsonPointer.getValue(jsonStructure); + + return jsonString.getString(); + } + + public String fetchListValues(String key) { + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure); + + return jsonObject.toString(); + } + + public String fetchFullJSON() { + JsonPointer jsonPointer = Json.createPointer(""); + JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure); + + return jsonObject.toString(); + + } + + public boolean check(String key) { + JsonPointer jsonPointer = Json.createPointer("/" + key); + boolean found = jsonPointer.containsValue(jsonStructure); + + return found; + } +} diff --git a/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java b/json/src/test/java/com/baeldung/jsonb/JsonbUnitTest.java similarity index 99% rename from jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java rename to json/src/test/java/com/baeldung/jsonb/JsonbUnitTest.java index 67beda77e1..f258700c6b 100644 --- a/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java +++ b/json/src/test/java/com/baeldung/jsonb/JsonbUnitTest.java @@ -18,8 +18,9 @@ import org.apache.commons.collections4.ListUtils; import org.junit.Test; import com.baeldung.adapter.PersonAdapter; +import com.baeldung.jsonb.Person; -public class JsonbTest { +public class JsonbUnitTest { @Test public void givenPersonList_whenSerializeWithJsonb_thenGetPersonJsonArray() { diff --git a/json/src/test/java/com/baeldung/jsonpointer/JsonPointerCrudUnitTest.java b/json/src/test/java/com/baeldung/jsonpointer/JsonPointerCrudUnitTest.java new file mode 100644 index 0000000000..c1553db325 --- /dev/null +++ b/json/src/test/java/com/baeldung/jsonpointer/JsonPointerCrudUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.jsonpointer; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class JsonPointerCrudUnitTest { + + @Test + public void testJsonPointerCrudForAddress() { + + JsonPointerCrud jsonPointerCrud = new JsonPointerCrud(JsonPointerCrudUnitTest.class.getResourceAsStream("/address.json")); + + assertFalse(jsonPointerCrud.check("city")); + + // insert a value + jsonPointerCrud.insert("city", "Rio de Janeiro"); + + assertTrue(jsonPointerCrud.check("city")); + + // fetch full json + String fullJSON = jsonPointerCrud.fetchFullJSON(); + + assertTrue(fullJSON.contains("name")); + + assertTrue(fullJSON.contains("city")); + + // fetch value + String cityName = jsonPointerCrud.fetchValueFromKey("city"); + + assertEquals(cityName, "Rio de Janeiro"); + + // update value + jsonPointerCrud.update("city", "Sao Paulo"); + + // fetch value + cityName = jsonPointerCrud.fetchValueFromKey("city"); + + assertEquals(cityName, "Sao Paulo"); + + // delete + jsonPointerCrud.delete("city"); + + assertFalse(jsonPointerCrud.check("city")); + + } + + @Test + public void testJsonPointerCrudForBooks() { + + JsonPointerCrud jsonPointerCrud = new JsonPointerCrud(JsonPointerCrudUnitTest.class.getResourceAsStream("/books.json")); + + // fetch value + String book = jsonPointerCrud.fetchListValues("books/1"); + + assertEquals(book, "{\"title\":\"Title 2\",\"author\":\"John Doe\"}"); + + } +} \ No newline at end of file diff --git a/json/src/test/resources/address.json b/json/src/test/resources/address.json new file mode 100644 index 0000000000..599fcae12b --- /dev/null +++ b/json/src/test/resources/address.json @@ -0,0 +1,4 @@ +{ + "name": "Customer 01", + "street name": "Street 01" +} \ No newline at end of file diff --git a/json/src/test/resources/books.json b/json/src/test/resources/books.json new file mode 100644 index 0000000000..0defc3de98 --- /dev/null +++ b/json/src/test/resources/books.json @@ -0,0 +1,7 @@ +{ + "library": "My Personal Library", + "books": [ + { "title":"Title 1", "author":"Jane Doe" }, + { "title":"Title 2", "author":"John Doe" } + ] +} \ No newline at end of file diff --git a/jsonb/README.md b/jsonb/README.md deleted file mode 100644 index 9293a44808..0000000000 --- a/jsonb/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## JSON B - -## Relevant articles: -- [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api) diff --git a/jsonb/pom.xml b/jsonb/pom.xml deleted file mode 100644 index 160b9d5df7..0000000000 --- a/jsonb/pom.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - 4.0.0 - com.baeldung - json-b - 0.0.1-SNAPSHOT - jar - json-b - json-b sample project - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - javax.json.bind - javax.json.bind-api - ${jsonb-api.version} - - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - test - - - - org.junit.jupiter - junit-jupiter-api - ${junit.jupiter.version} - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - - - yasson - - true - - - - - org.eclipse - yasson - ${yasson.version} - - - org.glassfish - javax.json - ${javax.json.version} - - - - - johnzon - - - - org.apache.geronimo.specs - geronimo-json_1.1_spec - ${geronimo-json_1.1_spec.version} - - - org.apache.johnzon - johnzon-jsonb - ${johnzon.version} - - - - - - - 1.8 - 1.8 - 1.0.0 - 1.0 - 1.1.3 - 1.0 - 1.0.1 - 1.1.2 - 4.1 - - - \ No newline at end of file diff --git a/jta/README.md b/jta/README.md new file mode 100644 index 0000000000..445a291c8f --- /dev/null +++ b/jta/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Guide to Java EE JTA](https://www.baeldung.com/jee-jta) diff --git a/jta/pom.xml b/jta/pom.xml new file mode 100644 index 0000000000..89bdccf25e --- /dev/null +++ b/jta/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + com.baeldung + jta-demo + 1.0-SNAPSHOT + jar + + JEE JTA demo + + + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-jta-bitronix + + + org.springframework.boot + spring-boot-starter-jdbc + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.hsqldb + hsqldb + 2.4.1 + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + diff --git a/jta/src/main/java/com/baeldung/jtademo/JtaDemoApplication.java b/jta/src/main/java/com/baeldung/jtademo/JtaDemoApplication.java new file mode 100644 index 0000000000..4d8779efe5 --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/JtaDemoApplication.java @@ -0,0 +1,48 @@ +package com.baeldung.jtademo; + +import org.hsqldb.jdbc.pool.JDBCXADataSource; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.jta.bitronix.BitronixXADataSourceWrapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; + +@EnableAutoConfiguration +@EnableTransactionManagement +@Configuration +@ComponentScan +public class JtaDemoApplication { + + @Bean("dataSourceAccount") + public DataSource dataSource() throws Exception { + return createHsqlXADatasource("jdbc:hsqldb:mem:accountDb"); + } + + @Bean("dataSourceAudit") + public DataSource dataSourceAudit() throws Exception { + return createHsqlXADatasource("jdbc:hsqldb:mem:auditDb"); + } + + private DataSource createHsqlXADatasource(String connectionUrl) throws Exception { + JDBCXADataSource dataSource = new JDBCXADataSource(); + dataSource.setUrl(connectionUrl); + dataSource.setUser("sa"); + BitronixXADataSourceWrapper wrapper = new BitronixXADataSourceWrapper(); + return wrapper.wrapDataSource(dataSource); + } + + @Bean("jdbcTemplateAccount") + public JdbcTemplate jdbcTemplate(@Qualifier("dataSourceAccount") DataSource dataSource) { + return new JdbcTemplate(dataSource); + } + + @Bean("jdbcTemplateAudit") + public JdbcTemplate jdbcTemplateAudit(@Qualifier("dataSourceAudit") DataSource dataSource) { + return new JdbcTemplate(dataSource); + } +} diff --git a/jta/src/main/java/com/baeldung/jtademo/dto/TransferLog.java b/jta/src/main/java/com/baeldung/jtademo/dto/TransferLog.java new file mode 100644 index 0000000000..cc1474ce81 --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/dto/TransferLog.java @@ -0,0 +1,27 @@ +package com.baeldung.jtademo.dto; + +import java.math.BigDecimal; + +public class TransferLog { + private String fromAccountId; + private String toAccountId; + private BigDecimal amount; + + public TransferLog(String fromAccountId, String toAccountId, BigDecimal amount) { + this.fromAccountId = fromAccountId; + this.toAccountId = toAccountId; + this.amount = amount; + } + + public String getFromAccountId() { + return fromAccountId; + } + + public String getToAccountId() { + return toAccountId; + } + + public BigDecimal getAmount() { + return amount; + } +} diff --git a/jta/src/main/java/com/baeldung/jtademo/services/AuditService.java b/jta/src/main/java/com/baeldung/jtademo/services/AuditService.java new file mode 100644 index 0000000000..f6810e15c8 --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/services/AuditService.java @@ -0,0 +1,33 @@ +package com.baeldung.jtademo.services; + +import com.baeldung.jtademo.dto.TransferLog; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.ResultSetExtractor; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; + +@Service +public class AuditService { + + final JdbcTemplate jdbcTemplate; + + @Autowired + public AuditService(@Qualifier("jdbcTemplateAudit") JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + public void log(String fromAccount, String toAccount, BigDecimal amount) { + jdbcTemplate.update("insert into AUDIT_LOG(FROM_ACCOUNT, TO_ACCOUNT, AMOUNT) values ?,?,?", fromAccount, toAccount, amount); + } + + public TransferLog lastTransferLog() { + return jdbcTemplate.query("select FROM_ACCOUNT,TO_ACCOUNT,AMOUNT from AUDIT_LOG order by ID desc", (ResultSetExtractor) (rs) -> { + if (!rs.next()) + return null; + return new TransferLog(rs.getString(1), rs.getString(2), BigDecimal.valueOf(rs.getDouble(3))); + }); + } +} diff --git a/jta/src/main/java/com/baeldung/jtademo/services/BankAccountService.java b/jta/src/main/java/com/baeldung/jtademo/services/BankAccountService.java new file mode 100644 index 0000000000..0c881edbaa --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/services/BankAccountService.java @@ -0,0 +1,32 @@ +package com.baeldung.jtademo.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.ResultSetExtractor; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; + +@Service +public class BankAccountService { + + final JdbcTemplate jdbcTemplate; + + @Autowired + public BankAccountService(@Qualifier("jdbcTemplateAccount") JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + public void transfer(String fromAccountId, String toAccountId, BigDecimal amount) { + jdbcTemplate.update("update ACCOUNT set BALANCE=BALANCE-? where ID=?", amount, fromAccountId); + jdbcTemplate.update("update ACCOUNT set BALANCE=BALANCE+? where ID=?", amount, toAccountId); + } + + public BigDecimal balanceOf(String accountId) { + return jdbcTemplate.query("select BALANCE from ACCOUNT where ID=?", new Object[] { accountId }, (ResultSetExtractor) (rs) -> { + rs.next(); + return new BigDecimal(rs.getDouble(1)); + }); + } +} diff --git a/jta/src/main/java/com/baeldung/jtademo/services/TellerService.java b/jta/src/main/java/com/baeldung/jtademo/services/TellerService.java new file mode 100644 index 0000000000..d3bd80a2ee --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/services/TellerService.java @@ -0,0 +1,45 @@ +package com.baeldung.jtademo.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import javax.transaction.UserTransaction; +import java.math.BigDecimal; + +@Service +public class TellerService { + private final BankAccountService bankAccountService; + private final AuditService auditService; + private final UserTransaction userTransaction; + + @Autowired + public TellerService(BankAccountService bankAccountService, AuditService auditService, UserTransaction userTransaction) { + this.bankAccountService = bankAccountService; + this.auditService = auditService; + this.userTransaction = userTransaction; + } + + @Transactional + public void executeTransfer(String fromAccontId, String toAccountId, BigDecimal amount) { + bankAccountService.transfer(fromAccontId, toAccountId, amount); + auditService.log(fromAccontId, toAccountId, amount); + BigDecimal balance = bankAccountService.balanceOf(fromAccontId); + if (balance.compareTo(BigDecimal.ZERO) <= 0) { + throw new RuntimeException("Insufficient fund."); + } + } + + public void executeTransferProgrammaticTx(String fromAccontId, String toAccountId, BigDecimal amount) throws Exception { + userTransaction.begin(); + bankAccountService.transfer(fromAccontId, toAccountId, amount); + auditService.log(fromAccontId, toAccountId, amount); + BigDecimal balance = bankAccountService.balanceOf(fromAccontId); + if (balance.compareTo(BigDecimal.ZERO) <= 0) { + userTransaction.rollback(); + throw new RuntimeException("Insufficient fund."); + } else { + userTransaction.commit(); + } + } +} diff --git a/jta/src/main/java/com/baeldung/jtademo/services/TestHelper.java b/jta/src/main/java/com/baeldung/jtademo/services/TestHelper.java new file mode 100644 index 0000000000..c1e8e355ec --- /dev/null +++ b/jta/src/main/java/com/baeldung/jtademo/services/TestHelper.java @@ -0,0 +1,43 @@ +package com.baeldung.jtademo.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.init.ScriptUtils; +import org.springframework.stereotype.Component; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +@Component +public class TestHelper { + final JdbcTemplate jdbcTemplateAccount; + + final JdbcTemplate jdbcTemplateAudit; + + @Autowired + public TestHelper(@Qualifier("jdbcTemplateAccount") JdbcTemplate jdbcTemplateAccount, @Qualifier("jdbcTemplateAudit") JdbcTemplate jdbcTemplateAudit) { + this.jdbcTemplateAccount = jdbcTemplateAccount; + this.jdbcTemplateAudit = jdbcTemplateAudit; + } + + public void runAccountDbInit() throws SQLException { + runScript("account.sql", jdbcTemplateAccount.getDataSource()); + } + + public void runAuditDbInit() throws SQLException { + runScript("audit.sql", jdbcTemplateAudit.getDataSource()); + } + + private void runScript(String scriptName, DataSource dataSouorce) throws SQLException { + DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); + Resource script = resourceLoader.getResource(scriptName); + try (Connection con = dataSouorce.getConnection()) { + ScriptUtils.executeSqlScript(con, script); + } + } + +} diff --git a/jta/src/main/resources/account.sql b/jta/src/main/resources/account.sql new file mode 100644 index 0000000000..af14f89b01 --- /dev/null +++ b/jta/src/main/resources/account.sql @@ -0,0 +1,9 @@ +DROP SCHEMA PUBLIC CASCADE; + +create table ACCOUNT ( +ID char(8) PRIMARY KEY, +BALANCE NUMERIC(28,10) +); + +insert into ACCOUNT(ID, BALANCE) values ('a0000001', 1000); +insert into ACCOUNT(ID, BALANCE) values ('a0000002', 2000); \ No newline at end of file diff --git a/spring-data-spring-security/src/main/resources/application.properties b/jta/src/main/resources/application.properties similarity index 100% rename from spring-data-spring-security/src/main/resources/application.properties rename to jta/src/main/resources/application.properties diff --git a/jta/src/main/resources/audit.sql b/jta/src/main/resources/audit.sql new file mode 100644 index 0000000000..aa5845f402 --- /dev/null +++ b/jta/src/main/resources/audit.sql @@ -0,0 +1,8 @@ +DROP SCHEMA PUBLIC CASCADE; + +create table AUDIT_LOG ( +ID INTEGER IDENTITY PRIMARY KEY, +FROM_ACCOUNT varchar(8), +TO_ACCOUNT varchar(8), +AMOUNT numeric(28,10) +); \ No newline at end of file diff --git a/jta/src/test/java/com/baeldung/jtademo/JtaDemoUnitTest.java b/jta/src/test/java/com/baeldung/jtademo/JtaDemoUnitTest.java new file mode 100644 index 0000000000..3f6004262b --- /dev/null +++ b/jta/src/test/java/com/baeldung/jtademo/JtaDemoUnitTest.java @@ -0,0 +1,91 @@ +package com.baeldung.jtademo; + +import com.baeldung.jtademo.dto.TransferLog; +import com.baeldung.jtademo.services.AuditService; +import com.baeldung.jtademo.services.BankAccountService; +import com.baeldung.jtademo.services.TellerService; +import com.baeldung.jtademo.services.TestHelper; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.math.BigDecimal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = JtaDemoApplication.class) +public class JtaDemoUnitTest { + @Autowired + TestHelper testHelper; + + @Autowired + TellerService tellerService; + + @Autowired + BankAccountService accountService; + + @Autowired + AuditService auditService; + + @Before + public void beforeTest() throws Exception { + testHelper.runAuditDbInit(); + testHelper.runAccountDbInit(); + } + + @Test + public void givenAnnotationTx_whenNoException_thenAllCommitted() throws Exception { + tellerService.executeTransfer("a0000001", "a0000002", BigDecimal.valueOf(500)); + + assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(500)); + assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2500)); + + TransferLog lastTransferLog = auditService.lastTransferLog(); + assertThat(lastTransferLog).isNotNull(); + assertThat(lastTransferLog.getFromAccountId()).isEqualTo("a0000001"); + assertThat(lastTransferLog.getToAccountId()).isEqualTo("a0000002"); + assertThat(lastTransferLog.getAmount()).isEqualByComparingTo(BigDecimal.valueOf(500)); + } + + @Test + public void givenAnnotationTx_whenException_thenAllRolledBack() throws Exception { + assertThatThrownBy(() -> { + tellerService.executeTransfer("a0000002", "a0000001", BigDecimal.valueOf(100000)); + }).hasMessage("Insufficient fund."); + + assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(1000)); + assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2000)); + assertThat(auditService.lastTransferLog()).isNull(); + } + + @Test + public void givenProgrammaticTx_whenCommit_thenAllCommitted() throws Exception { + tellerService.executeTransferProgrammaticTx("a0000001", "a0000002", BigDecimal.valueOf(500)); + + BigDecimal result = accountService.balanceOf("a0000001"); + assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(500)); + assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2500)); + + TransferLog lastTransferLog = auditService.lastTransferLog(); + assertThat(lastTransferLog).isNotNull(); + assertThat(lastTransferLog.getFromAccountId()).isEqualTo("a0000001"); + assertThat(lastTransferLog.getToAccountId()).isEqualTo("a0000002"); + assertThat(lastTransferLog.getAmount()).isEqualByComparingTo(BigDecimal.valueOf(500)); + } + + @Test + public void givenProgrammaticTx_whenRollback_thenAllRolledBack() throws Exception { + assertThatThrownBy(() -> { + tellerService.executeTransferProgrammaticTx("a0000002", "a0000001", BigDecimal.valueOf(100000)); + }).hasMessage("Insufficient fund."); + + assertThat(accountService.balanceOf("a0000001")).isEqualByComparingTo(BigDecimal.valueOf(1000)); + assertThat(accountService.balanceOf("a0000002")).isEqualByComparingTo(BigDecimal.valueOf(2000)); + assertThat(auditService.lastTransferLog()).isNull(); + } +} diff --git a/jws/pom.xml b/jws/pom.xml index 01d9820b42..1970ab9921 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -13,20 +13,23 @@ 1.0.0-SNAPSHOT + + + OpenNMS Repository + http://repo.opennms.org/maven2/ + + + - javax.jnlp + javax.samples.jnlp jnlp-servlet ${jnlp-servlet.version} - system - ${project.basedir}/java-core-samples-lib/jnlp-servlet.jar - javax.jnlp - jardiff - ${jardiff.version} - system - ${project.basedir}/java-core-samples-lib/jardiff.jar + javax.samples.jnlp + jnlp-jardiff + ${jnlp-jardiff.version} @@ -81,8 +84,8 @@ 3.0.2 3.0.0 - 7.0 - 7.0 + 1.6.0 + 1.6.0 diff --git a/kotlin-libraries/.gitignore b/kotlin-libraries/.gitignore new file mode 100644 index 0000000000..0c017e8f8c --- /dev/null +++ b/kotlin-libraries/.gitignore @@ -0,0 +1,14 @@ +/bin/ + +#ignore gradle +.gradle/ + + +#ignore build and generated files +build/ +node/ +out/ + +#ignore installed node modules and package lock file +node_modules/ +package-lock.json diff --git a/kotlin-libraries/README.md b/kotlin-libraries/README.md new file mode 100644 index 0000000000..30c4d03ded --- /dev/null +++ b/kotlin-libraries/README.md @@ -0,0 +1,9 @@ +## Relevant articles: + +- [Kotlin with Mockito](http://www.baeldung.com/kotlin-mockito) +- [HTTP Requests with Kotlin and khttp](http://www.baeldung.com/kotlin-khttp) +- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection) +- [Writing Specifications with Kotlin and Spek](http://www.baeldung.com/kotlin-spek) +- [Processing JSON with Kotlin and Klaxson](http://www.baeldung.com/kotlin-json-klaxson) +- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor) +- [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence) diff --git a/core-kotlin/kotlin-ktor/build.gradle b/kotlin-libraries/build.gradle old mode 100755 new mode 100644 similarity index 83% rename from core-kotlin/kotlin-ktor/build.gradle rename to kotlin-libraries/build.gradle index 5c8f523cf1..b244df34b0 --- a/core-kotlin/kotlin-ktor/build.gradle +++ b/kotlin-libraries/build.gradle @@ -1,47 +1,57 @@ - - -group 'com.baeldung.ktor' -version '1.0-SNAPSHOT' - - -buildscript { - ext.kotlin_version = '1.2.41' - ext.ktor_version = '0.9.2' - - repositories { - mavenCentral() - } - dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -apply plugin: 'java' -apply plugin: 'kotlin' -apply plugin: 'application' - -mainClassName = 'APIServer.kt' - -sourceCompatibility = 1.8 -compileKotlin { kotlinOptions.jvmTarget = "1.8" } -compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } - -kotlin { experimental { coroutines "enable" } } - -repositories { - mavenCentral() - jcenter() - maven { url "https://dl.bintray.com/kotlin/ktor" } -} - -dependencies { - compile "io.ktor:ktor-server-netty:$ktor_version" - compile "ch.qos.logback:logback-classic:1.2.1" - compile "io.ktor:ktor-gson:$ktor_version" - testCompile group: 'junit', name: 'junit', version: '4.12' - -} -task runServer(type: JavaExec) { - main = 'APIServer' - classpath = sourceSets.main.runtimeClasspath + + +group 'com.baeldung.ktor' +version '1.0-SNAPSHOT' + + +buildscript { + ext.kotlin_version = '1.2.41' + ext.ktor_version = '0.9.2' + + repositories { + mavenCentral() + } + dependencies { + + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'java' +apply plugin: 'kotlin' +apply plugin: 'application' + +mainClassName = 'APIServer.kt' + +sourceCompatibility = 1.8 +compileKotlin { kotlinOptions.jvmTarget = "1.8" } +compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } + +kotlin { experimental { coroutines "enable" } } + +repositories { + mavenCentral() + jcenter() + maven { url "https://dl.bintray.com/kotlin/ktor" } +} +sourceSets { + main{ + kotlin{ + srcDirs 'com/baeldung/ktor' + } + } + +} + +dependencies { + compile "io.ktor:ktor-server-netty:$ktor_version" + compile "ch.qos.logback:logback-classic:1.2.1" + compile "io.ktor:ktor-gson:$ktor_version" + testCompile group: 'junit', name: 'junit', version: '4.12' + implementation 'com.beust:klaxon:3.0.1' + +} +task runServer(type: JavaExec) { + main = 'APIServer' + classpath = sourceSets.main.runtimeClasspath } \ No newline at end of file diff --git a/core-kotlin/kotlin-ktor/gradle/wrapper/gradle-wrapper.jar b/kotlin-libraries/gradle/wrapper/gradle-wrapper.jar old mode 100755 new mode 100644 similarity index 100% rename from core-kotlin/kotlin-ktor/gradle/wrapper/gradle-wrapper.jar rename to kotlin-libraries/gradle/wrapper/gradle-wrapper.jar diff --git a/core-kotlin/kotlin-ktor/gradle/wrapper/gradle-wrapper.properties b/kotlin-libraries/gradle/wrapper/gradle-wrapper.properties old mode 100755 new mode 100644 similarity index 97% rename from core-kotlin/kotlin-ktor/gradle/wrapper/gradle-wrapper.properties rename to kotlin-libraries/gradle/wrapper/gradle-wrapper.properties index 0b83b5a3e3..933b6473ce --- a/core-kotlin/kotlin-ktor/gradle/wrapper/gradle-wrapper.properties +++ b/kotlin-libraries/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip diff --git a/core-kotlin/kotlin-ktor/gradlew b/kotlin-libraries/gradlew old mode 100755 new mode 100644 similarity index 100% rename from core-kotlin/kotlin-ktor/gradlew rename to kotlin-libraries/gradlew diff --git a/core-kotlin/kotlin-ktor/gradlew.bat b/kotlin-libraries/gradlew.bat old mode 100755 new mode 100644 similarity index 96% rename from core-kotlin/kotlin-ktor/gradlew.bat rename to kotlin-libraries/gradlew.bat index e95643d6a2..f9553162f1 --- a/core-kotlin/kotlin-ktor/gradlew.bat +++ b/kotlin-libraries/gradlew.bat @@ -1,84 +1,84 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml new file mode 100644 index 0000000000..c5b7fed951 --- /dev/null +++ b/kotlin-libraries/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + kotlin-libraries + jar + + + com.baeldung + parent-kotlin + 1.0.0-SNAPSHOT + ../parent-kotlin + + + + + exposed + exposed + https://dl.bintray.com/kotlin/exposed + + + + + + org.jetbrains.spek + spek-api + 1.1.5 + test + + + org.jetbrains.spek + spek-subject-extension + 1.1.5 + test + + + org.jetbrains.spek + spek-junit-platform-engine + 1.1.5 + test + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + khttp + khttp + ${khttp.version} + + + com.nhaarman + mockito-kotlin + ${mockito-kotlin.version} + test + + + com.github.salomonbrys.kodein + kodein + ${kodein.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.beust + klaxon + ${klaxon.version} + + + org.jetbrains.exposed + exposed + ${exposed.version} + + + com.h2database + h2 + ${h2database.version} + + + + + 1.5.0 + 4.1.0 + 3.0.4 + 0.1.0 + 3.6.1 + 1.1.1 + 5.2.0 + 3.10.0 + 1.4.197 + 0.10.4 + + + \ No newline at end of file diff --git a/core-kotlin/kotlin-ktor/resources/logback.xml b/kotlin-libraries/resources/logback.xml old mode 100755 new mode 100644 similarity index 96% rename from core-kotlin/kotlin-ktor/resources/logback.xml rename to kotlin-libraries/resources/logback.xml index 274cdcdb02..9452207268 --- a/core-kotlin/kotlin-ktor/resources/logback.xml +++ b/kotlin-libraries/resources/logback.xml @@ -1,11 +1,11 @@ - - - - %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - + + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + \ No newline at end of file diff --git a/core-kotlin/kotlin-ktor/settings.gradle b/kotlin-libraries/settings.gradle old mode 100755 new mode 100644 similarity index 94% rename from core-kotlin/kotlin-ktor/settings.gradle rename to kotlin-libraries/settings.gradle index 13bbce9583..c91c993971 --- a/core-kotlin/kotlin-ktor/settings.gradle +++ b/kotlin-libraries/settings.gradle @@ -1,2 +1,2 @@ -rootProject.name = 'KtorWithKotlin' - +rootProject.name = 'KtorWithKotlin' + diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/Product.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/Product.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/ProductData.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/ProductData.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt diff --git a/core-kotlin/kotlin-ktor/src/main/kotlin/APIServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/ktor/APIServer.kt similarity index 100% rename from core-kotlin/kotlin-ktor/src/main/kotlin/APIServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/ktor/APIServer.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt new file mode 100644 index 0000000000..29fa18ef7a --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt @@ -0,0 +1,333 @@ +package com.baeldung.kotlin.exposed + +import org.jetbrains.exposed.dao.* +import org.jetbrains.exposed.sql.* +import org.jetbrains.exposed.sql.transactions.TransactionManager +import org.jetbrains.exposed.sql.transactions.transaction +import org.junit.Test +import java.sql.DriverManager +import kotlin.test.* + +class ExposedTest { + + @Test + fun whenH2Database_thenConnectionSuccessful() { + val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + transaction { + assertEquals(1.4.toBigDecimal(), database.version) + assertEquals("h2", database.vendor) + } + } + + @Test + fun whenH2DatabaseWithCredentials_thenConnectionSuccessful() { + Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver", user = "myself", password = "secret") + } + + @Test + fun whenH2DatabaseWithManualConnection_thenConnectionSuccessful() { + var connected = false + Database.connect({ connected = true; DriverManager.getConnection("jdbc:h2:mem:test;MODE=MySQL") }) + assertEquals(false, connected) + transaction { + addLogger(StdOutSqlLogger) + assertEquals(false, connected) + SchemaUtils.create(Cities) + assertEquals(true, connected) + } + } + + @Test + fun whenManualCommit_thenOk() { + Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + transaction { + assertTrue(this is Transaction) + commit() + commit() + commit() + } + } + + @Test + fun whenInsert_thenGeneratedKeys() { + Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + transaction { + SchemaUtils.create(StarWarsFilms) + val id = StarWarsFilms.insertAndGetId { + it[name] = "The Last Jedi" + it[sequelId] = 8 + it[director] = "Rian Johnson" + } + assertEquals(1, id.value) + val insert = StarWarsFilms.insert { + it[name] = "The Force Awakens" + it[sequelId] = 7 + it[director] = "J.J. Abrams" + } + assertEquals(2, insert[StarWarsFilms.id]?.value) + val selectAll = StarWarsFilms.selectAll() + selectAll.forEach { + assertTrue { it[StarWarsFilms.sequelId] >= 7 } + } + StarWarsFilms.slice(StarWarsFilms.name, StarWarsFilms.director).selectAll() + .forEach { + assertTrue { it[StarWarsFilms.name].startsWith("The") } + } + val select = StarWarsFilms.select { (StarWarsFilms.director like "J.J.%") and (StarWarsFilms.sequelId eq 7) } + assertEquals(1, select.count()) + StarWarsFilms.update ({ StarWarsFilms.sequelId eq 8 }) { + it[name] = "Episode VIII – The Last Jedi" + with(SqlExpressionBuilder) { + it.update(StarWarsFilms.sequelId, StarWarsFilms.sequelId + 1) + } + } + } + } + + @Test + fun whenForeignKey_thenAutoJoin() { + Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + transaction { + addLogger(StdOutSqlLogger) + SchemaUtils.create(StarWarsFilms, Players) + StarWarsFilms.insert { + it[name] = "The Last Jedi" + it[sequelId] = 8 + it[director] = "Rian Johnson" + } + StarWarsFilms.insert { + it[name] = "The Force Awakens" + it[sequelId] = 7 + it[director] = "J.J. Abrams" + } + Players.insert { + it[name] = "Mark Hamill" + it[sequelId] = 7 + } + Players.insert { + it[name] = "Mark Hamill" + it[sequelId] = 8 + } + val simpleInnerJoin = (StarWarsFilms innerJoin Players).selectAll() + assertEquals(2, simpleInnerJoin.count()) + simpleInnerJoin.forEach { + assertNotNull(it[StarWarsFilms.name]) + assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId]) + assertEquals("Mark Hamill", it[Players.name]) + } + val innerJoinWithCondition = (StarWarsFilms innerJoin Players) + .select { StarWarsFilms.sequelId eq Players.sequelId } + assertEquals(2, innerJoinWithCondition.count()) + innerJoinWithCondition.forEach { + assertNotNull(it[StarWarsFilms.name]) + assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId]) + assertEquals("Mark Hamill", it[Players.name]) + } + val complexInnerJoin = Join(StarWarsFilms, Players, joinType = JoinType.INNER, onColumn = StarWarsFilms.sequelId, otherColumn = Players.sequelId, additionalConstraint = { + StarWarsFilms.sequelId eq 8 + }).selectAll() + assertEquals(1, complexInnerJoin.count()) + complexInnerJoin.forEach { + assertNotNull(it[StarWarsFilms.name]) + assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId]) + assertEquals("Mark Hamill", it[Players.name]) + } + + } + } + + @Test + fun whenJoinWithAlias_thenFun() { + Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + transaction { + addLogger(StdOutSqlLogger) + SchemaUtils.create(StarWarsFilms, Players) + StarWarsFilms.insert { + it[name] = "The Last Jedi" + it[sequelId] = 8 + it[director] = "Rian Johnson" + } + StarWarsFilms.insert { + it[name] = "The Force Awakens" + it[sequelId] = 7 + it[director] = "J.J. Abrams" + } + val sequel = StarWarsFilms.alias("sequel") + Join(StarWarsFilms, sequel, + additionalConstraint = { sequel[StarWarsFilms.sequelId] eq StarWarsFilms.sequelId + 1 }) + .selectAll().forEach { + assertEquals(it[sequel[StarWarsFilms.sequelId]], it[StarWarsFilms.sequelId] + 1) + } + } + } + + @Test + fun whenEntity_thenDAO() { + val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + val connection = database.connector.invoke() //Keep a connection open so the DB is not destroyed after the first transaction + val inserted = transaction { + addLogger(StdOutSqlLogger) + SchemaUtils.create(StarWarsFilms, Players) + val theLastJedi = StarWarsFilm.new { + name = "The Last Jedi" + sequelId = 8 + director = "Rian Johnson" + } + assertFalse(TransactionManager.current().entityCache.inserts.isEmpty()) + assertEquals(1, theLastJedi.id.value) //Reading this causes a flush + assertTrue(TransactionManager.current().entityCache.inserts.isEmpty()) + theLastJedi + } + transaction { + val theLastJedi = StarWarsFilm.findById(1) + assertNotNull(theLastJedi) + assertEquals(inserted.id, theLastJedi?.id) + } + connection.close() + } + + @Test + fun whenManyToOne_thenNavigation() { + val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + val connection = database.connector.invoke() + transaction { + addLogger(StdOutSqlLogger) + SchemaUtils.create(StarWarsFilms, Players, Users, UserRatings) + val theLastJedi = StarWarsFilm.new { + name = "The Last Jedi" + sequelId = 8 + director = "Rian Johnson" + } + val someUser = User.new { + name = "Some User" + } + val rating = UserRating.new { + value = 9 + user = someUser + film = theLastJedi + } + assertEquals(theLastJedi, rating.film) + assertEquals(someUser, rating.user) + assertEquals(rating, theLastJedi.ratings.first()) + } + transaction { + val theLastJedi = StarWarsFilm.find { StarWarsFilms.sequelId eq 8 }.first() + val ratings = UserRating.find { UserRatings.film eq theLastJedi.id } + assertEquals(1, ratings.count()) + val rating = ratings.first() + assertEquals("Some User", rating.user.name) + assertEquals(rating, theLastJedi.ratings.first()) + UserRating.new { + value = 8 + user = rating.user + film = theLastJedi + } + assertEquals(2, theLastJedi.ratings.count()) + } + connection.close() + } + + @Test + fun whenManyToMany_thenAssociation() { + val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") + val connection = database.connector.invoke() + val film = transaction { + SchemaUtils.create(StarWarsFilms) + StarWarsFilm.new { + name = "The Last Jedi" + sequelId = 8 + director = "Rian Johnson" + } + } + + val actor = transaction { + SchemaUtils.create(Actors) + Actor.new { + firstname = "Daisy" + lastname = "Ridley" + } + } + + transaction { + SchemaUtils.create(StarWarsFilmActors) + film.actors = SizedCollection(listOf(actor)) + } + connection.close() + } + +} + +object Cities: IntIdTable() { + val name = varchar("name", 50) +} + +object StarWarsFilms_Simple : Table() { + val id = integer("id").autoIncrement().primaryKey() + val sequelId = integer("sequel_id").uniqueIndex() + val name = varchar("name", 50) + val director = varchar("director", 50) +} + +object StarWarsFilms : IntIdTable() { + val sequelId = integer("sequel_id").uniqueIndex() + val name = varchar("name", 50) + val director = varchar("director", 50) +} + +object Players : Table() { + //val sequelId = integer("sequel_id").uniqueIndex().references(StarWarsFilms.sequelId) + val sequelId = reference("sequel_id", StarWarsFilms.sequelId).uniqueIndex() + //val filmId = reference("film_id", StarWarsFilms).nullable() + val name = varchar("name", 50) +} + +class StarWarsFilm(id: EntityID) : Entity(id) { + companion object : EntityClass(StarWarsFilms) + + var sequelId by StarWarsFilms.sequelId + var name by StarWarsFilms.name + var director by StarWarsFilms.director + var actors by Actor via StarWarsFilmActors + val ratings by UserRating referrersOn UserRatings.film +} + +object Users: IntIdTable() { + val name = varchar("name", 50) +} + +object UserRatings: IntIdTable() { + val value = long("value") + val film = reference("film", StarWarsFilms) + val user = reference("user", Users) +} + +class User(id: EntityID): IntEntity(id) { + companion object : IntEntityClass(Users) + + var name by Users.name +} + +class UserRating(id: EntityID): IntEntity(id) { + companion object : IntEntityClass(UserRatings) + + var value by UserRatings.value + var film by StarWarsFilm referencedOn UserRatings.film + var user by User referencedOn UserRatings.user +} + +object Actors: IntIdTable() { + val firstname = varchar("firstname", 50) + val lastname = varchar("lastname", 50) +} + +class Actor(id: EntityID): IntEntity(id) { + companion object : IntEntityClass(Actors) + + var firstname by Actors.firstname + var lastname by Actors.lastname +} + +object StarWarsFilmActors : Table() { + val starWarsFilm = reference("starWarsFilm", StarWarsFilms).primaryKey(0) + val actor = reference("actor", Actors).primaryKey(1) +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt new file mode 100644 index 0000000000..1b61c05887 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt @@ -0,0 +1,17 @@ +package com.baeldung.kotlin.junit5 + +class Calculator { + fun add(a: Int, b: Int) = a + b + + fun divide(a: Int, b: Int) = if (b == 0) { + throw DivideByZeroException(a) + } else { + a / b + } + + fun square(a: Int) = a * a + + fun squareRoot(a: Int) = Math.sqrt(a.toDouble()) + + fun log(base: Int, value: Int) = Math.log(value.toDouble()) / Math.log(base.toDouble()) +} diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt new file mode 100644 index 0000000000..60bc4e2944 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt @@ -0,0 +1,3 @@ +package com.baeldung.kotlin.junit5 + +class DivideByZeroException(val numerator: Int) : Exception() diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpLiveTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpLiveTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpLiveTest.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpLiveTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt similarity index 100% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt rename to kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt diff --git a/libraries-data/README.md b/libraries-data/README.md index fbe49e9f74..63ee5f9947 100644 --- a/libraries-data/README.md +++ b/libraries-data/README.md @@ -9,4 +9,6 @@ - [Introduction to JCache](http://www.baeldung.com/jcache) - [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite) - [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data) -- [Guide to JMapper](https://github.com/eugenp/tutorials/tree/master/libraries-data) +- [Guide to JMapper](https://www.baeldung.com/jmapper) +- [A Guide to Apache Crunch](https://www.baeldung.com/apache-crunch) +- [Building a Data Pipeline with Flink and Kafka](https://www.baeldung.com/kafka-flink-data-pipeline) diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index e5e8fd5551..bbf0c7832f 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -147,7 +147,134 @@ jmapper-core ${jmapper.version} - + + + org.apache.crunch + crunch-core + ${org.apache.crunch.crunch-core.version} + + + org.apache.hadoop + hadoop-client + ${org.apache.hadoop.hadoop-client} + provided + + + + commons-cli + commons-cli + 1.2 + provided + + + commons-io + commons-io + 2.1 + provided + + + commons-httpclient + commons-httpclient + 3.0.1 + provided + + + commons-codec + commons-codec + + + + + org.apache.flink + flink-connector-kafka-0.11_2.11 + ${flink.version} + + + org.apache.flink + flink-streaming-java_2.11 + ${flink.version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + org.apache.flink + flink-core + ${flink.version} + + + commons-logging + commons-logging + + + + + org.apache.flink + flink-java + ${flink.version} + + + commons-logging + commons-logging + + + + + org.apache.flink + flink-test-utils_2.11 + ${flink.version} + test + + + org.assertj + assertj-core + ${assertj.version} + + + org.awaitility + awaitility + ${awaitility.version} + test + + + org.awaitility + awaitility-proxy + ${awaitility.version} + test + + + io.ebean + ebean + ${ebean.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + ch.qos.logback + logback-classic + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + + org.slf4j + slf4j-log4j12 + ${slf4j.version} + @@ -252,6 +379,48 @@ + + org.apache.maven.plugins + maven-assembly-plugin + 2.3 + + + src/main/assembly/hadoop-job.xml + + + + com.baeldung.crunch.WordCount + + + + + + make-assembly + package + + single + + + + + + io.ebean + ebean-maven-plugin + 11.11.2 + + + + main + process-classes + + debug=1 + + + enhance + + + +
    @@ -273,6 +442,10 @@ 2.4.0 2.8.2 1.1.0 + 1.5.0 + 2.8.5 + 3.0.0 + 3.6.2 3.8.4 1.8 3.0.0 @@ -282,7 +455,12 @@ 5.0.2 5.0.0-release 5.0.4 - 1.6.0.1 + 1.6.0.1 + 0.15.0 + 2.2.0 + 11.22.4 + 1.7.25 + 1.0.1 diff --git a/libraries-data/src/main/assembly/hadoop-job.xml b/libraries-data/src/main/assembly/hadoop-job.xml new file mode 100644 index 0000000000..1917e1e5a3 --- /dev/null +++ b/libraries-data/src/main/assembly/hadoop-job.xml @@ -0,0 +1,28 @@ + + + + + job + + jar + + false + + + false + runtime + lib + + ${groupId}:${artifactId} + + + + true + + ${groupId}:${artifactId} + + + + diff --git a/libraries-data/src/main/java/com/baeldung/crunch/StopWordFilter.java b/libraries-data/src/main/java/com/baeldung/crunch/StopWordFilter.java new file mode 100644 index 0000000000..bdd606e179 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/crunch/StopWordFilter.java @@ -0,0 +1,25 @@ +package com.baeldung.crunch; + +import java.util.Set; + +import org.apache.crunch.FilterFn; + +import com.google.common.collect.ImmutableSet; + +/** + * A filter that removes known stop words. + */ +public class StopWordFilter extends FilterFn { + + // English stop words, borrowed from Lucene. + private static final Set STOP_WORDS = ImmutableSet + .copyOf(new String[] { "a", "and", "are", "as", "at", "be", "but", "by", + "for", "if", "in", "into", "is", "it", "no", "not", "of", "on", + "or", "s", "such", "t", "that", "the", "their", "then", "there", + "these", "they", "this", "to", "was", "will", "with" }); + + @Override + public boolean accept(String word) { + return !STOP_WORDS.contains(word); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseFn.java b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseFn.java new file mode 100644 index 0000000000..a277883ad3 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseFn.java @@ -0,0 +1,11 @@ +package com.baeldung.crunch; + +import org.apache.crunch.MapFn; + +public class ToUpperCaseFn extends MapFn { + + @Override + public String map(String input) { + return input != null ? input.toUpperCase() : input; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseWithCounterFn.java b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseWithCounterFn.java new file mode 100644 index 0000000000..f753f98866 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/crunch/ToUpperCaseWithCounterFn.java @@ -0,0 +1,20 @@ +package com.baeldung.crunch; + +import org.apache.crunch.MapFn; + +@SuppressWarnings("serial") +public class ToUpperCaseWithCounterFn extends MapFn { + + @Override + public String map(String input) { + if (input == null) { + return input; + } else { + String output = input.toUpperCase(); + if (!input.equals(output)) { + increment("UpperCase", "modified"); + } + return output; + } + } +} diff --git a/libraries-data/src/main/java/com/baeldung/crunch/Tokenizer.java b/libraries-data/src/main/java/com/baeldung/crunch/Tokenizer.java new file mode 100644 index 0000000000..9523634be1 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/crunch/Tokenizer.java @@ -0,0 +1,23 @@ +package com.baeldung.crunch; + +import org.apache.crunch.DoFn; +import org.apache.crunch.Emitter; + +import com.google.common.base.Splitter; + +/** + * Splits a line of text, filtering known stop words. + */ +public class Tokenizer extends DoFn { + private static final Splitter SPLITTER = Splitter + .onPattern("\\s+") + .omitEmptyStrings(); + + @Override + public void process(String line, + Emitter emitter) { + for (String word : SPLITTER.split(line)) { + emitter.emit(word); + } + } +} diff --git a/libraries-data/src/main/java/com/baeldung/crunch/WordCount.java b/libraries-data/src/main/java/com/baeldung/crunch/WordCount.java new file mode 100644 index 0000000000..c49abec68a --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/crunch/WordCount.java @@ -0,0 +1,62 @@ +package com.baeldung.crunch; + +import org.apache.crunch.PCollection; +import org.apache.crunch.PTable; +import org.apache.crunch.Pipeline; +import org.apache.crunch.PipelineResult; +import org.apache.crunch.impl.mr.MRPipeline; +import org.apache.crunch.types.writable.Writables; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.conf.Configured; +import org.apache.hadoop.util.GenericOptionsParser; +import org.apache.hadoop.util.Tool; +import org.apache.hadoop.util.ToolRunner; + +/** + * A word count example for Apache Crunch, based on Crunch's example projects. + */ +public class WordCount extends Configured implements Tool { + + public static void main(String[] args) throws Exception { + ToolRunner.run(new Configuration(), new WordCount(), args); + } + + public int run(String[] args) throws Exception { + + if (args.length != 2) { + System.err.println("Usage: hadoop jar crunch-1.0.0-SNAPSHOT-job.jar" + " [generic options] input output"); + System.err.println(); + GenericOptionsParser.printGenericCommandUsage(System.err); + return 1; + } + + String inputPath = args[0]; + String outputPath = args[1]; + + // Create an object to coordinate pipeline creation and execution. + Pipeline pipeline = new MRPipeline(WordCount.class, getConf()); + + // Reference a given text file as a collection of Strings. + PCollection lines = pipeline.readTextFile(inputPath); + + // Define a function that splits each line in a PCollection of Strings into + // a PCollection made up of the individual words in the file. + // The second argument sets the serialization format. + PCollection words = lines.parallelDo(new Tokenizer(), Writables.strings()); + + // Take the collection of words and remove known stop words. + PCollection noStopWords = words.filter(new StopWordFilter()); + + // The count method applies a series of Crunch primitives and returns + // a map of the unique words in the input PCollection to their counts. + PTable counts = noStopWords.count(); + + // Instruct the pipeline to write the resulting counts to a text file. + pipeline.writeTextFile(counts, outputPath); + + // Execute the pipeline as a MapReduce. + PipelineResult result = pipeline.done(); + + return result.succeeded() ? 0 : 1; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/ebean/app/App.java b/libraries-data/src/main/java/com/baeldung/ebean/app/App.java new file mode 100644 index 0000000000..44a4fa8562 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ebean/app/App.java @@ -0,0 +1,75 @@ +package com.baeldung.ebean.app; + +import java.util.Arrays; + +import com.baeldung.ebean.model.Address; +import com.baeldung.ebean.model.Customer; + +import io.ebean.Ebean; +import io.ebean.EbeanServer; +import io.ebean.annotation.Transactional; + +public class App { + + public static void main(String[] args) { + insertAndDeleteInsideTransaction(); + crudOperations(); + queryCustomers(); + } + + @Transactional + public static void insertAndDeleteInsideTransaction() { + + Customer c1 = getCustomer(); + EbeanServer server = Ebean.getDefaultServer(); + server.save(c1); + Customer foundC1 = server.find(Customer.class, c1.getId()); + server.delete(foundC1); + } + + public static void crudOperations() { + + Address a1 = new Address("5, Wide Street", null, "New York"); + Customer c1 = new Customer("John Wide", a1); + + EbeanServer server = Ebean.getDefaultServer(); + server.save(c1); + + c1.setName("Jane Wide"); + c1.setAddress(null); + server.save(c1); + + Customer foundC1 = Ebean.find(Customer.class, c1.getId()); + + Ebean.delete(foundC1); + } + + public static void queryCustomers() { + Address a1 = new Address("1, Big Street", null, "New York"); + Customer c1 = new Customer("Big John", a1); + + Address a2 = new Address("2, Big Street", null, "New York"); + Customer c2 = new Customer("Big John", a2); + + Address a3 = new Address("3, Big Street", null, "San Jose"); + Customer c3 = new Customer("Big Bob", a3); + + Ebean.saveAll(Arrays.asList(c1, c2, c3)); + + Customer customer = Ebean.find(Customer.class) + .select("name") + .fetch("address", "city") + .where() + .eq("city", "San Jose") + .findOne(); + + Ebean.deleteAll(Arrays.asList(c1, c2, c3)); + } + + private static Customer getCustomer() { + Address a1 = new Address("1, Big Street", null, "New York"); + Customer c1 = new Customer("Big John", a1); + return c1; + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/ebean/app/App2.java b/libraries-data/src/main/java/com/baeldung/ebean/app/App2.java new file mode 100644 index 0000000000..fba77007c6 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ebean/app/App2.java @@ -0,0 +1,26 @@ +package com.baeldung.ebean.app; + +import java.util.Properties; + +import io.ebean.EbeanServer; +import io.ebean.EbeanServerFactory; +import io.ebean.config.ServerConfig; + +public class App2 { + + public static void main(String[] args) { + ServerConfig cfg = new ServerConfig(); + cfg.setDefaultServer(true); + Properties properties = new Properties(); + properties.put("ebean.db.ddl.generate", "true"); + properties.put("ebean.db.ddl.run", "true"); + properties.put("datasource.db.username", "sa"); + properties.put("datasource.db.password", ""); + properties.put("datasource.db.databaseUrl", "jdbc:h2:mem:app2"); + properties.put("datasource.db.databaseDriver", "org.h2.Driver"); + cfg.loadFromProperties(properties); + EbeanServer server = EbeanServerFactory.create(cfg); + + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/ebean/model/Address.java b/libraries-data/src/main/java/com/baeldung/ebean/model/Address.java new file mode 100644 index 0000000000..dfcd90ffa7 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ebean/model/Address.java @@ -0,0 +1,48 @@ +package com.baeldung.ebean.model; + +import javax.persistence.Entity; + +@Entity +public class Address extends BaseModel { + + public Address(String addressLine1, String addressLine2, String city) { + super(); + this.addressLine1 = addressLine1; + this.addressLine2 = addressLine2; + this.city = city; + } + + private String addressLine1; + private String addressLine2; + private String city; + + public String getAddressLine1() { + return addressLine1; + } + + public void setAddressLine1(String addressLine1) { + this.addressLine1 = addressLine1; + } + + public String getAddressLine2() { + return addressLine2; + } + + public void setAddressLine2(String addressLine2) { + this.addressLine2 = addressLine2; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + @Override + public String toString() { + return "Address [id=" + id + ", addressLine1=" + addressLine1 + ", addressLine2=" + addressLine2 + ", city=" + city + "]"; + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/ebean/model/BaseModel.java b/libraries-data/src/main/java/com/baeldung/ebean/model/BaseModel.java new file mode 100644 index 0000000000..547d5bf075 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ebean/model/BaseModel.java @@ -0,0 +1,59 @@ +package com.baeldung.ebean.model; + +import java.time.Instant; + +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; +import javax.persistence.Version; + +import io.ebean.annotation.WhenCreated; +import io.ebean.annotation.WhenModified; + +@MappedSuperclass +public abstract class BaseModel { + + @Id + protected long id; + + @Version + protected long version; + + @WhenCreated + protected Instant createdOn; + + @WhenModified + protected Instant modifiedOn; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Instant getCreatedOn() { + return createdOn; + } + + public void setCreatedOn(Instant createdOn) { + this.createdOn = createdOn; + } + + public Instant getModifiedOn() { + return modifiedOn; + } + + public void setModifiedOn(Instant modifiedOn) { + this.modifiedOn = modifiedOn; + } + + public long getVersion() { + return version; + } + + public void setVersion(long version) { + this.version = version; + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/ebean/model/Customer.java b/libraries-data/src/main/java/com/baeldung/ebean/model/Customer.java new file mode 100644 index 0000000000..4dd629245a --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ebean/model/Customer.java @@ -0,0 +1,42 @@ +package com.baeldung.ebean.model; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.OneToOne; + +@Entity +public class Customer extends BaseModel { + + public Customer(String name, Address address) { + super(); + this.name = name; + this.address = address; + } + + private String name; + + @OneToOne(cascade = CascadeType.ALL) + Address address; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + @Override + public String toString() { + return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]"; + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/flink/FlinkDataPipeline.java b/libraries-data/src/main/java/com/baeldung/flink/FlinkDataPipeline.java new file mode 100644 index 0000000000..d02b1bcb83 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/flink/FlinkDataPipeline.java @@ -0,0 +1,82 @@ +package com.baeldung.flink; + + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.model.InputMessage; +import com.baeldung.flink.operator.BackupAggregator; +import com.baeldung.flink.operator.InputMessageTimestampAssigner; +import com.baeldung.flink.operator.WordsCapitalizer; +import org.apache.flink.streaming.api.TimeCharacteristic; +import org.apache.flink.streaming.api.datastream.DataStream; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.windowing.time.Time; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011; + +import static com.baeldung.flink.connector.Consumers.*; +import static com.baeldung.flink.connector.Producers.*; + +public class FlinkDataPipeline { + + public static void capitalize() throws Exception { + String inputTopic = "flink_input"; + String outputTopic = "flink_output"; + String consumerGroup = "baeldung"; + String address = "localhost:9092"; + + StreamExecutionEnvironment environment = + StreamExecutionEnvironment.getExecutionEnvironment(); + + FlinkKafkaConsumer011 flinkKafkaConsumer = + createStringConsumerForTopic(inputTopic, address, consumerGroup); + flinkKafkaConsumer.setStartFromEarliest(); + + DataStream stringInputStream = + environment.addSource(flinkKafkaConsumer); + + FlinkKafkaProducer011 flinkKafkaProducer = + createStringProducer(outputTopic, address); + + stringInputStream + .map(new WordsCapitalizer()) + .addSink(flinkKafkaProducer); + + environment.execute(); + } + +public static void createBackup () throws Exception { + String inputTopic = "flink_input"; + String outputTopic = "flink_output"; + String consumerGroup = "baeldung"; + String kafkaAddress = "localhost:9092"; + + StreamExecutionEnvironment environment = + StreamExecutionEnvironment.getExecutionEnvironment(); + + environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); + + FlinkKafkaConsumer011 flinkKafkaConsumer = + createInputMessageConsumer(inputTopic, kafkaAddress, consumerGroup); + flinkKafkaConsumer.setStartFromEarliest(); + + flinkKafkaConsumer + .assignTimestampsAndWatermarks(new InputMessageTimestampAssigner()); + FlinkKafkaProducer011 flinkKafkaProducer = + createBackupProducer(outputTopic, kafkaAddress); + + DataStream inputMessagesStream = + environment.addSource(flinkKafkaConsumer); + + inputMessagesStream + .timeWindowAll(Time.hours(24)) + .aggregate(new BackupAggregator()) + .addSink(flinkKafkaProducer); + + environment.execute(); +} + + public static void main(String[] args) throws Exception { + createBackup(); + } + +} diff --git a/libraries/src/main/java/com/baeldung/flink/LineSplitter.java b/libraries-data/src/main/java/com/baeldung/flink/LineSplitter.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/LineSplitter.java rename to libraries-data/src/main/java/com/baeldung/flink/LineSplitter.java diff --git a/libraries/src/main/java/com/baeldung/flink/WordCount.java b/libraries-data/src/main/java/com/baeldung/flink/WordCount.java similarity index 100% rename from libraries/src/main/java/com/baeldung/flink/WordCount.java rename to libraries-data/src/main/java/com/baeldung/flink/WordCount.java diff --git a/libraries-data/src/main/java/com/baeldung/flink/connector/Consumers.java b/libraries-data/src/main/java/com/baeldung/flink/connector/Consumers.java new file mode 100644 index 0000000000..514085f9c4 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/flink/connector/Consumers.java @@ -0,0 +1,32 @@ +package com.baeldung.flink.connector; + +import com.baeldung.flink.model.InputMessage; +import com.baeldung.flink.schema.InputMessageDeserializationSchema; +import org.apache.flink.api.common.serialization.SimpleStringSchema; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011; + +import java.util.Properties; + +public class Consumers { + +public static FlinkKafkaConsumer011 createStringConsumerForTopic( + String topic, String kafkaAddress, String kafkaGroup ) { + Properties props = new Properties(); + props.setProperty("bootstrap.servers", kafkaAddress); + props.setProperty("group.id",kafkaGroup); + FlinkKafkaConsumer011 consumer = + new FlinkKafkaConsumer011<>(topic, new SimpleStringSchema(),props); + + return consumer; +} + + public static FlinkKafkaConsumer011 createInputMessageConsumer(String topic, String kafkaAddress, String kafkaGroup ) { + Properties properties = new Properties(); + properties.setProperty("bootstrap.servers", kafkaAddress); + properties.setProperty("group.id",kafkaGroup); + FlinkKafkaConsumer011 consumer = new FlinkKafkaConsumer011( + topic, new InputMessageDeserializationSchema(),properties); + + return consumer; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/flink/connector/Producers.java b/libraries-data/src/main/java/com/baeldung/flink/connector/Producers.java new file mode 100644 index 0000000000..8e6f3f8f37 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/flink/connector/Producers.java @@ -0,0 +1,17 @@ +package com.baeldung.flink.connector; + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.schema.BackupSerializationSchema; +import org.apache.flink.api.common.serialization.SimpleStringSchema; +import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011; + +public class Producers { + + public static FlinkKafkaProducer011 createStringProducer(String topic, String kafkaAddress) { + return new FlinkKafkaProducer011<>(kafkaAddress, topic, new SimpleStringSchema()); + } + + public static FlinkKafkaProducer011 createBackupProducer(String topic, String kafkaAddress) { + return new FlinkKafkaProducer011(kafkaAddress, topic, new BackupSerializationSchema()); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/flink/model/Backup.java b/libraries-data/src/main/java/com/baeldung/flink/model/Backup.java new file mode 100644 index 0000000000..268ceec7f3 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/flink/model/Backup.java @@ -0,0 +1,27 @@ +package com.baeldung.flink.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; + +public class Backup { + + @JsonProperty("inputMessages") + List inputMessages; + @JsonProperty("backupTimestamp") + LocalDateTime backupTimestamp; + @JsonProperty("uuid") + UUID uuid; + + public Backup(List inputMessages, LocalDateTime backupTimestamp) { + this.inputMessages = inputMessages; + this.backupTimestamp = backupTimestamp; + this.uuid = UUID.randomUUID(); + } + + public List getInputMessages() { + return inputMessages; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/flink/model/InputMessage.java b/libraries-data/src/main/java/com/baeldung/flink/model/InputMessage.java new file mode 100644 index 0000000000..b3f75256ae --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/flink/model/InputMessage.java @@ -0,0 +1,71 @@ +package com.baeldung.flink.model; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.google.common.base.Objects; + +import java.time.LocalDateTime; + +@JsonSerialize +public class InputMessage { + String sender; + String recipient; + LocalDateTime sentAt; + String message; + + public InputMessage() { + } + + public String getSender() { + return sender; + } + public void setSender(String sender) { + this.sender = sender; + } + + public String getRecipient() { + return recipient; + } + + public void setRecipient(String recipient) { + this.recipient = recipient; + } + + public LocalDateTime getSentAt() { + return sentAt; + } + + public void setSentAt(LocalDateTime sentAt) { + this.sentAt = sentAt; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public InputMessage(String sender, String recipient, LocalDateTime sentAt, String message) { + this.sender = sender; + this.recipient = recipient; + this.sentAt = sentAt; + this.message = message; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + InputMessage message1 = (InputMessage) o; + return Objects.equal(sender, message1.sender) && + Objects.equal(recipient, message1.recipient) && + Objects.equal(sentAt, message1.sentAt) && + Objects.equal(message, message1.message); + } + + @Override + public int hashCode() { + return Objects.hashCode(sender, recipient, sentAt, message); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/flink/operator/BackupAggregator.java b/libraries-data/src/main/java/com/baeldung/flink/operator/BackupAggregator.java new file mode 100644 index 0000000000..c39b8413d1 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/flink/operator/BackupAggregator.java @@ -0,0 +1,34 @@ +package com.baeldung.flink.operator; + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.model.InputMessage; +import org.apache.flink.api.common.functions.AggregateFunction; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + + public class BackupAggregator implements AggregateFunction, Backup> { + @Override + public List createAccumulator() { + return new ArrayList<>(); + } + + @Override + public List add(InputMessage inputMessage, List inputMessages) { + inputMessages.add(inputMessage); + return inputMessages; + } + + @Override + public Backup getResult(List inputMessages) { + Backup backup = new Backup(inputMessages, LocalDateTime.now()); + return backup; + } + + @Override + public List merge(List inputMessages, List acc1) { + inputMessages.addAll(acc1); + return inputMessages; + } + } diff --git a/libraries-data/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java b/libraries-data/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java new file mode 100644 index 0000000000..05828d9588 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/flink/operator/InputMessageTimestampAssigner.java @@ -0,0 +1,23 @@ +package com.baeldung.flink.operator; + +import com.baeldung.flink.model.InputMessage; +import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks; +import org.apache.flink.streaming.api.watermark.Watermark; + +import javax.annotation.Nullable; +import java.time.ZoneId; + +public class InputMessageTimestampAssigner implements AssignerWithPunctuatedWatermarks { + + @Override + public long extractTimestamp(InputMessage element, long previousElementTimestamp) { + ZoneId zoneId = ZoneId.systemDefault(); + return element.getSentAt().atZone(zoneId).toEpochSecond() * 1000; + } + + @Nullable + @Override + public Watermark checkAndGetNextWatermark(InputMessage lastElement, long extractedTimestamp) { + return new Watermark(extractedTimestamp - 15); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java b/libraries-data/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java new file mode 100644 index 0000000000..f9103d225c --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/flink/operator/WordsCapitalizer.java @@ -0,0 +1,11 @@ +package com.baeldung.flink.operator; + +import org.apache.flink.api.common.functions.MapFunction; + +public class WordsCapitalizer implements MapFunction { + + @Override + public String map(String s) { + return s.toUpperCase(); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java b/libraries-data/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java new file mode 100644 index 0000000000..967b266bb6 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/flink/schema/BackupSerializationSchema.java @@ -0,0 +1,33 @@ +package com.baeldung.flink.schema; + +import com.baeldung.flink.model.Backup; +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.apache.flink.api.common.serialization.SerializationSchema; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BackupSerializationSchema + implements SerializationSchema { + + static ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + + Logger logger = LoggerFactory.getLogger(BackupSerializationSchema.class); + + @Override + public byte[] serialize(Backup backupMessage) { + if(objectMapper == null) { + objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); + objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + } + try { + String json = objectMapper.writeValueAsString(backupMessage); + return json.getBytes(); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + logger.error("Failed to parse JSON", e); + } + return new byte[0]; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java b/libraries-data/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java new file mode 100644 index 0000000000..9aaf8b9877 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/flink/schema/InputMessageDeserializationSchema.java @@ -0,0 +1,32 @@ +package com.baeldung.flink.schema; + +import com.baeldung.flink.model.InputMessage; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.apache.flink.api.common.serialization.DeserializationSchema; +import org.apache.flink.api.common.typeinfo.TypeInformation; + +import java.io.IOException; + +public class InputMessageDeserializationSchema implements + DeserializationSchema { + + static ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + + + @Override + public InputMessage deserialize(byte[] bytes) throws IOException { + + return objectMapper.readValue(bytes, InputMessage.class); + } + + @Override + public boolean isEndOfStream(InputMessage inputMessage) { + return false; + } + + @Override + public TypeInformation getProducedType() { + return TypeInformation.of(InputMessage.class); + } +} diff --git a/libraries-data/src/main/resources/ebean.mf b/libraries-data/src/main/resources/ebean.mf new file mode 100644 index 0000000000..f49fecc717 --- /dev/null +++ b/libraries-data/src/main/resources/ebean.mf @@ -0,0 +1,3 @@ +entity-packages: com.baeldung.ebean.model +transactional-packages: com.baeldung.ebean.app +querybean-packages: com.baeldung.ebean.app diff --git a/libraries-data/src/main/resources/ebean.properties b/libraries-data/src/main/resources/ebean.properties new file mode 100644 index 0000000000..9cc5cc170a --- /dev/null +++ b/libraries-data/src/main/resources/ebean.properties @@ -0,0 +1,7 @@ +ebean.db.ddl.generate=true +ebean.db.ddl.run=true + +datasource.db.username=sa +datasource.db.password= +datasource.db.databaseUrl=jdbc:h2:mem:customer +datasource.db.databaseDriver=org.h2.Driver diff --git a/libraries-data/src/main/resources/logback.xml b/libraries-data/src/main/resources/logback.xml index 7d900d8ea8..a57d22fcb2 100644 --- a/libraries-data/src/main/resources/logback.xml +++ b/libraries-data/src/main/resources/logback.xml @@ -6,7 +6,9 @@ - + + + diff --git a/libraries-data/src/test/java/com/baeldung/crunch/MemPipelineUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/MemPipelineUnitTest.java new file mode 100644 index 0000000000..3ee2bb6836 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/crunch/MemPipelineUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.crunch; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Calendar; + +import org.apache.crunch.PCollection; +import org.apache.crunch.Pipeline; +import org.apache.crunch.Source; +import org.apache.crunch.Target; +import org.apache.crunch.impl.mem.MemPipeline; +import org.apache.crunch.io.From; +import org.apache.crunch.io.To; +import org.junit.Ignore; +import org.junit.Test; + +public class MemPipelineUnitTest { + + private static final String INPUT_FILE_PATH = "src/test/resources/crunch/input.txt"; + + @Test + public void givenPipeLineAndSource_whenSourceRead_thenExpectedNumberOfRecordsRead() { + Pipeline pipeline = MemPipeline.getInstance(); + Source source = From.textFile(INPUT_FILE_PATH); + + PCollection lines = pipeline.read(source); + + assertEquals(21, lines.asCollection() + .getValue() + .size()); + } + + @Test + public void givenPipeLine_whenTextFileRead_thenExpectedNumberOfRecordsRead() { + Pipeline pipeline = MemPipeline.getInstance(); + + PCollection lines = pipeline.readTextFile(INPUT_FILE_PATH); + + assertEquals(21, lines.asCollection() + .getValue() + .size()); + } + + private String createOutputPath() throws IOException { + Path path = Files.createTempDirectory("test"); + final String outputFilePath = path.toString() + File.separatorChar + + "output.text"; + return outputFilePath; + } + + @Test + @Ignore("Requires Hadoop binaries") + public void givenCollection_whenWriteCalled_fileWrittenSuccessfully() + throws IOException { + PCollection inputStrings = MemPipeline.collectionOf("Hello", + "Apache", "Crunch", Calendar.getInstance() + .toString()); + final String outputFilePath = createOutputPath(); + Target target = To.textFile(outputFilePath); + + inputStrings.write(target); + + Pipeline pipeline = MemPipeline.getInstance(); + PCollection lines = pipeline.readTextFile(outputFilePath); + assertIterableEquals(inputStrings.materialize(), lines.materialize()); + } + + @Test + @Ignore("Requires Hadoop binaries") + public void givenPipeLine_whenWriteTextFileCalled_fileWrittenSuccessfully() + throws IOException { + Pipeline pipeline = MemPipeline.getInstance(); + PCollection inputStrings = MemPipeline.collectionOf("Hello", + "Apache", "Crunch", Calendar.getInstance() + .toString()); + final String outputFilePath = createOutputPath(); + + pipeline.writeTextFile(inputStrings, outputFilePath); + + PCollection lines = pipeline.readTextFile(outputFilePath); + assertIterableEquals(inputStrings.materialize(), lines.materialize()); + } + +} diff --git a/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java new file mode 100644 index 0000000000..fffefc2bfb --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.crunch; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.apache.crunch.FilterFn; +import org.apache.crunch.PCollection; +import org.apache.crunch.impl.mem.MemPipeline; +import org.junit.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +public class StopWordFilterUnitTest { + + @Test + public void givenFilter_whenStopWordPassed_thenFalseReturned() { + FilterFn filter = new StopWordFilter(); + + assertFalse(filter.accept("the")); + } + + @Test + public void givenFilter_whenNonStopWordPassed_thenTrueReturned() { + FilterFn filter = new StopWordFilter(); + + assertTrue(filter.accept("Hello")); + } + + @Test + public void givenWordCollection_whenFiltered_thenStopWordsRemoved() { + PCollection words = MemPipeline.collectionOf("This", "is", "a", + "test", "sentence"); + + PCollection noStopWords = words.filter(new StopWordFilter()); + + assertEquals(ImmutableList.of("This", "test", "sentence"), + Lists.newArrayList(noStopWords.materialize())); + } +} diff --git a/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseFnUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseFnUnitTest.java new file mode 100644 index 0000000000..09fb9fba85 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseFnUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.crunch; + +import static org.junit.Assert.assertEquals; + +import org.apache.crunch.impl.mem.emit.InMemoryEmitter; +import org.junit.Test; + +import com.google.common.collect.ImmutableList; + +public class ToUpperCaseFnUnitTest { + + @Test + public void givenString_whenToUpperCaseFnCalled_UpperCaseStringReturned() { + InMemoryEmitter emitter = new InMemoryEmitter(); + + new ToUpperCaseFn().process("input", emitter); + + assertEquals(ImmutableList.of("INPUT"), emitter.getOutput()); + } + +} diff --git a/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java new file mode 100644 index 0000000000..76294d273d --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.crunch; + +import static org.junit.Assert.assertEquals; + +import org.apache.crunch.PCollection; +import org.apache.crunch.impl.mem.MemPipeline; +import org.apache.crunch.types.writable.Writables; +import org.junit.Before; +import org.junit.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +public class ToUpperCaseWithCounterFnUnitTest { + + @Before + public void setUp() throws Exception { + MemPipeline.clearCounters(); + } + + @Test + public void whenFunctionCalled_counterIncementendForChangedValues() { + PCollection inputStrings = MemPipeline.collectionOf("This", "is", "a", "TEST", "string"); + PCollection upperCaseStrings = inputStrings.parallelDo(new ToUpperCaseWithCounterFn(), Writables.strings()); + + assertEquals(ImmutableList.of("THIS", "IS", "A", "TEST", "STRING"), Lists.newArrayList(upperCaseStrings.materialize())); + assertEquals(4L, MemPipeline.getCounters() + .findCounter("UpperCase", "modified") + .getValue()); + } +} diff --git a/libraries-data/src/test/java/com/baeldung/crunch/TokenizerUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/TokenizerUnitTest.java new file mode 100644 index 0000000000..1e85826d17 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/crunch/TokenizerUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.crunch; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import org.apache.crunch.Emitter; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class TokenizerUnitTest { + @Mock + private Emitter emitter; + + @Test + public void givenTokenizer_whenLineProcessed_thenOnlyExpectedWordsEmitted() { + Tokenizer splitter = new Tokenizer(); + + splitter.process(" hello world ", emitter); + + verify(emitter).emit("hello"); + verify(emitter).emit("world"); + verifyNoMoreInteractions(emitter); + } +} diff --git a/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java new file mode 100644 index 0000000000..ab7d119c16 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java @@ -0,0 +1,103 @@ +package com.baeldung.flink; + +import com.baeldung.flink.model.Backup; +import com.baeldung.flink.model.InputMessage; +import com.baeldung.flink.operator.BackupAggregator; +import com.baeldung.flink.operator.InputMessageTimestampAssigner; +import com.baeldung.flink.schema.BackupSerializationSchema; +import com.baeldung.flink.schema.InputMessageDeserializationSchema; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.apache.commons.collections.ListUtils; +import org.apache.flink.api.common.serialization.DeserializationSchema; +import org.apache.flink.api.common.serialization.SerializationSchema; +import org.apache.flink.streaming.api.TimeCharacteristic; +import org.apache.flink.streaming.api.datastream.DataStreamSource; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.functions.sink.SinkFunction; +import org.apache.flink.streaming.api.windowing.time.Time; +import org.awaitility.Awaitility; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class BackupCreatorIntegrationTest { + public static ObjectMapper mapper; + + @Before + public void setup() { + mapper = new ObjectMapper().registerModule(new JavaTimeModule()); + } + + @Test + public void givenProperJson_whenDeserializeIsInvoked_thenProperObjectIsReturned() throws IOException { + InputMessage message = new InputMessage("Me", "User", LocalDateTime.now(), "Test Message"); + byte[] messageSerialized = mapper.writeValueAsBytes(message); + DeserializationSchema deserializationSchema = new InputMessageDeserializationSchema(); + InputMessage messageDeserialized = deserializationSchema.deserialize(messageSerialized); + + assertEquals(message, messageDeserialized); + } + + @Test + public void givenMultipleInputMessagesFromDifferentDays_whenBackupCreatorIsUser_thenMessagesAreGroupedProperly() throws Exception { + LocalDateTime currentTime = LocalDateTime.now(); + InputMessage message = new InputMessage("Me", "User", currentTime, "First TestMessage"); + InputMessage secondMessage = new InputMessage("Me", "User", currentTime.plusHours(1), "First TestMessage"); + InputMessage thirdMessage = new InputMessage("Me", "User", currentTime.plusHours(2), "First TestMessage"); + InputMessage fourthMessage = new InputMessage("Me", "User", currentTime.plusHours(3), "First TestMessage"); + InputMessage fifthMessage = new InputMessage("Me", "User", currentTime.plusHours(25), "First TestMessage"); + InputMessage sixthMessage = new InputMessage("Me", "User", currentTime.plusHours(26), "First TestMessage"); + + List firstBackupMessages = Arrays.asList(message, secondMessage, thirdMessage, fourthMessage); + List secondBackupMessages = Arrays.asList(fifthMessage, sixthMessage); + List inputMessages = ListUtils.union(firstBackupMessages, secondBackupMessages); + + StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); + env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); + env.setParallelism(1); + DataStreamSource testDataSet = env.fromCollection(inputMessages); + CollectingSink sink = new CollectingSink(); + testDataSet.assignTimestampsAndWatermarks(new InputMessageTimestampAssigner()) + .timeWindowAll(Time.hours(24)) + .aggregate(new BackupAggregator()) + .addSink(sink); + + env.execute(); + + Awaitility.await().until(() -> sink.backups.size() == 2); + assertEquals(2, sink.backups.size()); + assertEquals(firstBackupMessages, sink.backups.get(0).getInputMessages()); + assertEquals(secondBackupMessages, sink.backups.get(1).getInputMessages()); + + } + + @Test + public void givenProperBackupObject_whenSerializeIsInvoked_thenObjectIsProperlySerialized() throws IOException { + InputMessage message = new InputMessage("Me", "User", LocalDateTime.now(), "Test Message"); + List messages = Arrays.asList(message); + Backup backup = new Backup(messages, LocalDateTime.now()); + byte[] backupSerialized = mapper.writeValueAsBytes(backup); + SerializationSchema serializationSchema = new BackupSerializationSchema(); + byte[] backupProcessed = serializationSchema.serialize(backup); + + assertEquals(backupSerialized, backupProcessed); + } + + private static class CollectingSink implements SinkFunction { + + public static List backups = new ArrayList<>(); + + @Override + public synchronized void invoke(Backup value, Context context) throws Exception { + backups.add(value); + } + } +} diff --git a/libraries-data/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java new file mode 100644 index 0000000000..8a98dae4b5 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.flink; + +import com.baeldung.flink.operator.WordsCapitalizer; +import org.apache.flink.api.java.DataSet; +import org.apache.flink.api.java.ExecutionEnvironment; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class WordCapitalizerIntegrationTest { + + @Test + public void givenDataSet_whenExecuteWordCapitalizer_thenReturnCapitalizedWords() throws Exception { + ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); + List data = Arrays.asList("dog", "cat", "wolf", "pig"); + + DataSet testDataSet = env.fromCollection(data); + + + List dataProcessed = testDataSet + .map(new WordsCapitalizer()) + .collect(); + + List testDataCapitalized = data.stream() + .map(String::toUpperCase) + .collect(Collectors.toList()); + + Assert.assertEquals(testDataCapitalized, dataProcessed); + } + +} diff --git a/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java diff --git a/libraries-data/src/test/resources/crunch/input.txt b/libraries-data/src/test/resources/crunch/input.txt new file mode 100644 index 0000000000..cb78ea5351 --- /dev/null +++ b/libraries-data/src/test/resources/crunch/input.txt @@ -0,0 +1,21 @@ +An an valley indeed so no wonder future nature vanity. Debating all she mistaken indulged believed provided declared. He many kept on draw lain song as same. Whether at dearest certain spirits is entered in to. Rich fine bred real use too many good. She compliment unaffected expression favourable any. Unknown chiefly showing to conduct no. Hung as love evil able to post at as. + + + +Is he staying arrival address earnest. To preference considered it themselves inquietude collecting estimating. View park for why gay knew face. Next than near to four so hand. Times so do he downs me would. Witty abode party her found quiet law. They door four bed fail now have. + +Tolerably earnestly middleton extremely distrusts she boy now not. Add and offered prepare how cordial two promise. Greatly who affixed suppose but enquire compact prepare all put. Added forth chief trees but rooms think may. Wicket do manner others seemed enable rather in. Excellent own discovery unfeeling sweetness questions the gentleman. Chapter shyness matters mr parlors if mention thought. + +Extended kindness trifling remember he confined outlived if. Assistance sentiments yet unpleasing say. Open they an busy they my such high. An active dinner wishes at unable hardly no talked on. Immediate him her resolving his favourite. Wished denote abroad at branch at. + +Village did removed enjoyed explain nor ham saw calling talking. Securing as informed declared or margaret. Joy horrible moreover man feelings own shy. Request norland neither mistake for yet. Between the for morning assured country believe. On even feet time have an no at. Relation so in confined smallest children unpacked delicate. Why sir end believe uncivil respect. Always get adieus nature day course for common. My little garret repair to desire he esteem. + +You vexed shy mirth now noise. Talked him people valley add use her depend letter. Allowance too applauded now way something recommend. Mrs age men and trees jokes fancy. Gay pretended engrossed eagerness continued ten. Admitting day him contained unfeeling attention mrs out. + +Performed suspicion in certainty so frankness by attention pretended. Newspaper or in tolerably education enjoyment. Extremity excellent certainty discourse sincerity no he so resembled. Joy house worse arise total boy but. Elderly up chicken do at feeling is. Like seen drew no make fond at on rent. Behaviour extremely her explained situation yet september gentleman are who. Is thought or pointed hearing he. + +If wandered relation no surprise of screened doubtful. Overcame no insisted ye of trifling husbands. Might am order hours on found. Or dissimilar companions friendship impossible at diminution. Did yourself carriage learning she man its replying. Sister piqued living her you enable mrs off spirit really. Parish oppose repair is me misery. Quick may saw style after money mrs. + +Effects present letters inquiry no an removed or friends. Desire behind latter me though in. Supposing shameless am he engrossed up additions. My possible peculiar together to. Desire so better am cannot he up before points. Remember mistaken opinions it pleasure of debating. Court front maids forty if aware their at. Chicken use are pressed removed. + +To sorry world an at do spoil along. Incommode he depending do frankness remainder to. Edward day almost active him friend thirty piqued. People as period twenty my extent as. Set was better abroad ham plenty secure had horses. Admiration has sir decisively excellence say everything inhabiting acceptance. Sooner settle add put you sudden him. diff --git a/libraries-security/.gitignore b/libraries-security/.gitignore new file mode 100644 index 0000000000..71881ad3ca --- /dev/null +++ b/libraries-security/.gitignore @@ -0,0 +1,14 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear +/bin/ diff --git a/libraries-security/README.md b/libraries-security/README.md new file mode 100644 index 0000000000..c42e91a888 --- /dev/null +++ b/libraries-security/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Guide to ScribeJava](https://www.baeldung.com/scribejava) diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml new file mode 100644 index 0000000000..3077abc29c --- /dev/null +++ b/libraries-security/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + libraries-security + libraries-security + jar + + + com.baeldung + parent-boot-1 + 0.0.1-SNAPSHOT + ../parent-boot-1 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.security.oauth + spring-security-oauth2 + 2.3.3.RELEASE + + + + com.github.scribejava + scribejava-apis + ${scribejava.version} + + + + junit + junit + ${junit.version} + test + + + org.passay + passay + 1.3.1 + + + org.cryptacular + cryptacular + 1.2.2 + + + + + + 4.12 + 2.0.4.RELEASE + 5.6.0 + + + + diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java b/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java new file mode 100644 index 0000000000..bb86c497b0 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.scribejava; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +public class ScribejavaApplication { + + public static void main(String[] args) { + SpringApplication.run(ScribejavaApplication.class, args); + } + + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java b/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java new file mode 100644 index 0000000000..cf073d3035 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java @@ -0,0 +1,27 @@ +package com.baeldung.scribejava.api; + +import com.github.scribejava.core.builder.api.DefaultApi20; + +public class MyApi extends DefaultApi20 { + + private MyApi() { + } + + private static class InstanceHolder { + private static final MyApi INSTANCE = new MyApi(); + } + + public static MyApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "http://localhost:8080/oauth/token"; + } + + @Override + protected String getAuthorizationBaseUrl() { + return null; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java new file mode 100644 index 0000000000..ffe4f0cc8a --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java @@ -0,0 +1,49 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.GoogleService; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; + +@RestController +public class GoogleController { + + @Autowired + private GoogleService service; + + + @GetMapping(value ="/me/google") + public void me(HttpServletResponse response){ + String auth = service.getService().getAuthorizationUrl(); + + response.setHeader("Location", auth); + response.setStatus(302); + + } + + @GetMapping(value = "/auth/google") + public String google(@RequestParam String code, HttpServletResponse servletResponse){ + + try { + OAuth2AccessToken token = service.getService().getAccessToken(code); + + OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"); + service.getService().signRequest(token, request); + Response response = service.getService().execute(request); + return response.getBody(); + + }catch (Exception e){ + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java new file mode 100644 index 0000000000..bfcd6d960c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java @@ -0,0 +1,57 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.TwitterService; +import com.github.scribejava.core.model.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Scanner; +import java.util.concurrent.ExecutionException; + +@RestController +public class TwitterController { + + @Autowired + private TwitterService service; + + + @GetMapping(value ="/me/twitter") + public String me(HttpServletResponse servletResponse){ + try { + OAuth1RequestToken requestToken = service.getService().getRequestToken(); + + String auth = service.getService().getAuthorizationUrl(requestToken); + + Runtime runtime = Runtime.getRuntime(); + try { + runtime.exec("rundll32 url.dll,FileProtocolHandler " + auth); + } catch (IOException e) { + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return null; + } + + System.out.println("Insert twitter code:"); + Scanner in = new Scanner(System.in); + + String oauthverifier = in.nextLine(); + + final OAuth1AccessToken accessToken = service.getService().getAccessToken(requestToken,oauthverifier); + + OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json"); + service.getService().signRequest(accessToken, request); + Response response = service.getService().execute(request); + return response.getBody(); + + } catch (IOException | InterruptedException | ExecutionException e) { + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + } + + + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java new file mode 100644 index 0000000000..68a11250de --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java @@ -0,0 +1,46 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.MyService; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import java.security.Principal; + +@RestController(value = "/user") +public class UserController { + + @Autowired + private MyService service; + + @GetMapping("/me/myapi") + public String me(@RequestParam String username, @RequestParam String password, HttpServletResponse responsehttp) { + + try { + OAuth2AccessToken token = service.getService().getAccessTokenPasswordGrant(username, password); + + OAuthRequest request = new OAuthRequest(Verb.GET, "http://localhost:8080/me"); + service.getService().signRequest(token, request); + Response response = service.getService().execute(request); + + return response.getBody(); + + } catch (Exception e) { + responsehttp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + + } + + @GetMapping("/me") + public Principal user(Principal principal) { + return principal; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java new file mode 100644 index 0000000000..2c7162399b --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java @@ -0,0 +1,45 @@ +package com.baeldung.scribejava.oauth; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; + + +@Configuration +@EnableAuthorizationServer +public class AuthServiceConfig extends AuthorizationServerConfigurerAdapter { + + @Autowired + @Qualifier("authenticationManagerBean") + private AuthenticationManager authenticationManager; + + @Override + public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { + oauthServer.tokenKeyAccess("permitAll()") + .checkTokenAccess("isAuthenticated()"); + } + + @Override + public void configure(ClientDetailsServiceConfigurer clients) throws Exception { + clients.inMemory() + .withClient("baeldung_api_key") + .secret("baeldung_api_secret") + .authorizedGrantTypes("password","refresh_token") + .scopes("read","write").autoApprove(true); + } + + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { + endpoints + .authenticationManager(authenticationManager) + .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java new file mode 100644 index 0000000000..7aa51400ea --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.scribejava.oauth; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; + +@Configuration +@EnableResourceServer +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .headers().frameOptions().disable() + .and() + .csrf().disable(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("baeldung") + .password("scribejava") + .roles("USER"); + } + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + + @EnableResourceServer + @Configuration + public class ResourceServerConfig extends ResourceServerConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/user/me").authenticated() + .and() + .csrf().disable(); + } + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java new file mode 100644 index 0000000000..fbcc39763c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java @@ -0,0 +1,31 @@ +package com.baeldung.scribejava.service; + +import com.github.scribejava.apis.GoogleApi20; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +@Component +public class GoogleService { + + private OAuth20Service service; + private final String API_KEY = "api_key"; + private final String API_SECRET = "api_secret"; + private final String SCOPE = "https://www.googleapis.com/auth/userinfo.email"; + private final String CALLBACK = "http://localhost:8080/auth/google"; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .scope(SCOPE) + .callback(CALLBACK) + .build(GoogleApi20.instance()); + } + + + public OAuth20Service getService() { + return service; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java new file mode 100644 index 0000000000..739c82172c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java @@ -0,0 +1,29 @@ +package com.baeldung.scribejava.service; + +import com.baeldung.scribejava.api.MyApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class MyService { + + private OAuth20Service service; + private final String API_KEY = "baeldung_api_key"; + private final String API_SECRET = "baeldung_api_secret"; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .scope("read write") + .build(MyApi.instance()); + } + + + public OAuth20Service getService() { + return service; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java new file mode 100644 index 0000000000..df49f74679 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java @@ -0,0 +1,29 @@ +package com.baeldung.scribejava.service; + +import com.github.scribejava.apis.TwitterApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth10aService; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class TwitterService { + + private final String API_KEY = "api_key"; + private final String API_SECRET = "api_secret"; + private OAuth10aService service; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .build(TwitterApi.instance()); + } + + public OAuth10aService getService(){ + return service; + } + + +} diff --git a/libraries-security/src/main/resources/application.properties b/libraries-security/src/main/resources/application.properties new file mode 100644 index 0000000000..71c6176533 --- /dev/null +++ b/libraries-security/src/main/resources/application.properties @@ -0,0 +1 @@ +security.oauth2.resource.filter-order = 3 \ No newline at end of file diff --git a/libraries-security/src/test/java/com/baeldung/passay/NegativeMatchingRulesUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/NegativeMatchingRulesUnitTest.java new file mode 100644 index 0000000000..5054a5880e --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/NegativeMatchingRulesUnitTest.java @@ -0,0 +1,149 @@ +package com.baeldung.passay; + +import org.cryptacular.bean.EncodingHashBean; +import org.cryptacular.spec.CodecSpec; +import org.cryptacular.spec.DigestSpec; +import org.junit.Assert; +import org.junit.Test; +import org.passay.DictionaryRule; +import org.passay.DictionarySubstringRule; +import org.passay.DigestHistoryRule; +import org.passay.EnglishSequenceData; +import org.passay.HistoryRule; +import org.passay.IllegalCharacterRule; +import org.passay.IllegalRegexRule; +import org.passay.IllegalSequenceRule; +import org.passay.NumberRangeRule; +import org.passay.PasswordData; +import org.passay.PasswordValidator; +import org.passay.RepeatCharacterRegexRule; +import org.passay.RuleResult; +import org.passay.SourceRule; +import org.passay.UsernameRule; +import org.passay.WhitespaceRule; +import org.passay.dictionary.ArrayWordList; +import org.passay.dictionary.WordListDictionary; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class NegativeMatchingRulesUnitTest { + + @Test + public void givenDictionaryRules_whenValidatePassword_thenFoundIllegalWordsFromDictionary() { + ArrayWordList arrayWordList = new ArrayWordList(new String[] { "bar", "foobar" }); + + WordListDictionary wordListDictionary = new WordListDictionary(arrayWordList); + + DictionaryRule dictionaryRule = new DictionaryRule(wordListDictionary); + DictionarySubstringRule dictionarySubstringRule = new DictionarySubstringRule(wordListDictionary); + + PasswordValidator passwordValidator = new PasswordValidator(dictionaryRule, dictionarySubstringRule); + RuleResult validate = passwordValidator.validate(new PasswordData("foobar")); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_WORD:{matchingWord=foobar}", getDetail(validate, 0)); + assertEquals("ILLEGAL_WORD:{matchingWord=bar}", getDetail(validate, 1)); + } + + @Test + public void givenHistoryRule_whenValidatePassword_thenFoundIllegalWordsFromHistory() { + HistoryRule historyRule = new HistoryRule(); + + PasswordData passwordData = new PasswordData("123"); + passwordData.setPasswordReferences(new PasswordData.HistoricalReference("12345"), new PasswordData.HistoricalReference("1234"), new PasswordData.HistoricalReference("123")); + + PasswordValidator passwordValidator = new PasswordValidator(historyRule); + + RuleResult validate = passwordValidator.validate(passwordData); + + assertFalse(validate.isValid()); + assertEquals("HISTORY_VIOLATION:{historySize=3}", getDetail(validate, 0)); + } + + @Test + public void givenSeveralIllegalRules_whenValidatePassword_thenFoundSeveralIllegalPatterns() { + IllegalCharacterRule illegalCharacterRule = new IllegalCharacterRule(new char[] { 'a' }); + IllegalRegexRule illegalRegexRule = new IllegalRegexRule("\\w{2}\\d{2}"); + IllegalSequenceRule illegalSequenceRule = new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 3, true); + NumberRangeRule numberRangeRule = new NumberRangeRule(1, 10); + WhitespaceRule whitespaceRule = new WhitespaceRule(); + + PasswordValidator passwordValidator = new PasswordValidator(illegalCharacterRule, illegalRegexRule, illegalSequenceRule, numberRangeRule, whitespaceRule); + + RuleResult validate = passwordValidator.validate(new PasswordData("abcd22 ")); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_CHAR:{illegalCharacter=a, matchBehavior=contains}", getDetail(validate, 0)); + assertEquals("ILLEGAL_MATCH:{match=cd22, pattern=\\w{2}\\d{2}}", getDetail(validate, 1)); + assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=abc}", getDetail(validate, 2)); + assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=bcd}", getDetail(validate, 3)); + assertEquals("ILLEGAL_NUMBER_RANGE:{number=2, matchBehavior=contains}", getDetail(validate, 4)); + assertEquals("ILLEGAL_WHITESPACE:{whitespaceCharacter= , matchBehavior=contains}", getDetail(validate, 5)); + } + + @Test + public void givenSourceRule_whenValidatePassword_thenFoundIllegalWordsFromSource() { + SourceRule sourceRule = new SourceRule(); + + PasswordData passwordData = new PasswordData("password"); + passwordData.setPasswordReferences(new PasswordData.SourceReference("source", "password")); + + PasswordValidator passwordValidator = new PasswordValidator(sourceRule); + RuleResult validate = passwordValidator.validate(passwordData); + + assertFalse(validate.isValid()); + assertEquals("SOURCE_VIOLATION:{source=source}", getDetail(validate, 0)); + } + + @Test + public void givenRepeatCharacterRegexRuleRule_whenValidatePassword_thenFoundIllegalPatternMatches() { + RepeatCharacterRegexRule repeatCharacterRegexRule = new RepeatCharacterRegexRule(3); + + PasswordValidator passwordValidator = new PasswordValidator(repeatCharacterRegexRule); + + RuleResult validate = passwordValidator.validate(new PasswordData("aaabbb")); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_MATCH:{match=aaa, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 0)); + assertEquals("ILLEGAL_MATCH:{match=bbb, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 1)); + } + + @Test + public void givenUserNameRule_whenValidatePassword_thenFoundUserNameInPassword() { + PasswordValidator passwordValidator = new PasswordValidator(new UsernameRule()); + + PasswordData passwordData = new PasswordData("testuser1234"); + passwordData.setUsername("testuser"); + + RuleResult validate = passwordValidator.validate(passwordData); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_USERNAME:{username=testuser, matchBehavior=contains}", getDetail(validate, 0)); + } + + @Test + public void givenPasswordAndHashBeanAndEncryptedReferences_whenValidate_thenPasswordValidationShouldPass() { + List historicalReferences = Arrays.asList(new PasswordData.HistoricalReference("SHA256", "2e4551de804e27aacf20f9df5be3e8cd384ed64488b21ab079fb58e8c90068ab")); + PasswordData passwordData = new PasswordData("example!"); + passwordData.setPasswordReferences(historicalReferences); + + EncodingHashBean encodingHashBean = new EncodingHashBean(new CodecSpec("Base64"), new DigestSpec("SHA256"), 1, false); + + PasswordValidator passwordValidator = new PasswordValidator(new DigestHistoryRule(encodingHashBean)); + + RuleResult validate = passwordValidator.validate(passwordData); + + Assert.assertTrue(validate.isValid()); + } + + private String getDetail(RuleResult validate, int i) { + return validate.getDetails() + .get(i) + .toString(); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/passay/PasswordGeneratorUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/PasswordGeneratorUnitTest.java new file mode 100644 index 0000000000..ff279e9317 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/PasswordGeneratorUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.passay; + +import org.junit.Assert; +import org.junit.Test; +import org.passay.CharacterData; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.PasswordGenerator; + +import java.util.stream.Stream; + +public class PasswordGeneratorUnitTest { + + @Test + public void givenDigitsGenerator_whenGeneratingPassword_thenPasswordContainsDigitsHasLength10() { + CharacterRule digits = new CharacterRule(EnglishCharacterData.Digit); + + PasswordGenerator passwordGenerator = new PasswordGenerator(); + String password = passwordGenerator.generatePassword(10, digits); + + Assert.assertTrue(password.length() == 10); + Assert.assertTrue(containsOnlyCharactersFromSet(password, "0123456789")); + } + + @Test + public void givenCustomizedRule_whenGenerating_thenGeneratedPasswordContainsCustomizedCharacters() { + CharacterRule specialCharacterRule = new CharacterRule(new CharacterData() { + @Override + public String getErrorCode() { + return "SAMPLE_ERROR_CODE"; + } + + @Override + public String getCharacters() { + return "ABCxyz123!@#"; + } + }); + + PasswordGenerator passwordGenerator = new PasswordGenerator(); + String password = passwordGenerator.generatePassword(10, specialCharacterRule); + + Assert.assertTrue(containsOnlyCharactersFromSet(password, "ABCxyz123!@#")); + } + + private boolean containsOnlyCharactersFromSet(String password, String setOfCharacters) { + return Stream.of(password.split("")) + .allMatch(it -> setOfCharacters.contains(it)); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/passay/PasswordValidatorUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/PasswordValidatorUnitTest.java new file mode 100644 index 0000000000..3fc59a82d5 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/PasswordValidatorUnitTest.java @@ -0,0 +1,81 @@ +package com.baeldung.passay; + +import org.junit.Assert; +import org.junit.Test; +import org.passay.LengthRule; +import org.passay.MessageResolver; +import org.passay.PasswordData; +import org.passay.PasswordValidator; +import org.passay.PropertiesMessageResolver; +import org.passay.RuleResult; +import org.passay.RuleResultDetail; +import org.passay.RuleResultMetadata; +import org.passay.WhitespaceRule; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class PasswordValidatorUnitTest { + + @Test + public void givenPasswordValidatorWithLengthRule_whenValidation_thenTooShortPassword() { + PasswordData passwordData = new PasswordData("1234"); + + PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(5)); + + RuleResult validate = passwordValidator.validate(passwordData); + assertEquals(false, validate.isValid()); + + RuleResultDetail ruleResultDetail = validate.getDetails() + .get(0); + assertEquals("TOO_SHORT", ruleResultDetail.getErrorCode()); + assertEquals(5, ruleResultDetail.getParameters() + .get("minimumLength")); + assertEquals(5, ruleResultDetail.getParameters() + .get("maximumLength")); + + Integer lengthCount = validate.getMetadata() + .getCounts() + .get(RuleResultMetadata.CountCategory.Length); + assertEquals(Integer.valueOf(4), lengthCount); + } + + @Test + public void givenPasswordValidatorWithLengthRule_whenValidation_thenTooLongPassword() { + PasswordData passwordData = new PasswordData("123456"); + + PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(5)); + + RuleResult validate = passwordValidator.validate(passwordData); + assertFalse(validate.isValid()); + Assert.assertEquals("TOO_LONG", validate.getDetails() + .get(0) + .getErrorCode()); + } + + @Test + public void givenPasswordValidatorWithLengthRule_whenValidation_thenCustomizedMeesagesAvailable() throws IOException { + URL resource = this.getClass() + .getClassLoader() + .getResource("messages.properties"); + Properties props = new Properties(); + props.load(new FileInputStream(resource.getPath())); + + MessageResolver resolver = new PropertiesMessageResolver(props); + PasswordValidator validator = new PasswordValidator(resolver, new LengthRule(8, 16), new WhitespaceRule()); + + RuleResult tooShort = validator.validate(new PasswordData("XXXX")); + RuleResult tooLong = validator.validate(new PasswordData("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ")); + + assertEquals("Password must not contain less characters than 16.", validator.getMessages(tooShort) + .get(0)); + assertEquals("Password must not have more characters than 16.", validator.getMessages(tooLong) + .get(0)); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/passay/PositiveMatchingRulesUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/PositiveMatchingRulesUnitTest.java new file mode 100644 index 0000000000..0da1b43335 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/PositiveMatchingRulesUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.passay; + +import org.junit.Test; +import org.passay.AllowedCharacterRule; +import org.passay.AllowedRegexRule; +import org.passay.CharacterCharacteristicsRule; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.LengthComplexityRule; +import org.passay.LengthRule; +import org.passay.PasswordData; +import org.passay.PasswordValidator; +import org.passay.RuleResult; + +import static org.junit.Assert.*; + +public class PositiveMatchingRulesUnitTest { + + @Test + public void givenPasswordValidationRules_whenValidatingPassword_thenPosswordIsNotValidWithSeveralErrors() { + PasswordValidator passwordValidator = new PasswordValidator(new AllowedCharacterRule(new char[] { 'a', 'b', 'c' }), new AllowedRegexRule("\\d{2}\\w{10}"), new CharacterRule(EnglishCharacterData.LowerCase, 5), new LengthRule(8, 10)); + + RuleResult validate = passwordValidator.validate(new PasswordData("12abc")); + + assertFalse(validate.isValid()); + assertEquals("ALLOWED_CHAR:{illegalCharacter=1, matchBehavior=contains}", getDetail(validate, 0)); + assertEquals("ALLOWED_CHAR:{illegalCharacter=2, matchBehavior=contains}", getDetail(validate, 1)); + assertEquals("ALLOWED_MATCH:{pattern=\\d{2}\\w{10}}", getDetail(validate, 2)); + assertEquals("INSUFFICIENT_LOWERCASE:{" + "minimumRequired=5, matchingCharacterCount=3, " + "validCharacters=abcdefghijklmnopqrstuvwxyz, " + "matchingCharacters=abc}", getDetail(validate, 3)); + assertEquals("TOO_SHORT:{minimumLength=8, maximumLength=10}", getDetail(validate, 4)); + } + + @Test + public void givenRulesForDifferentPasswordLength_whenValidatingTwoDifferentPassword_thenBothOfThemAreInvalid() { + PasswordData shortPassword = new PasswordData("12ab"); + PasswordData longPassword = new PasswordData("1234abcde"); + + LengthComplexityRule lengthComplexityRule = new LengthComplexityRule(); + lengthComplexityRule.addRules("[1,5]", new CharacterRule(EnglishCharacterData.LowerCase, 5)); + lengthComplexityRule.addRules("[6,10]", new AllowedCharacterRule(new char[] { 'a', 'b', 'c', 'd' })); + + PasswordValidator passwordValidator = new PasswordValidator(lengthComplexityRule); + + RuleResult validateShort = passwordValidator.validate(shortPassword); + RuleResult validateLong = passwordValidator.validate(longPassword); + + assertFalse(validateShort.isValid()); + assertFalse(validateLong.isValid()); + + assertEquals("INSUFFICIENT_LOWERCASE:{" + "minimumRequired=5, " + "matchingCharacterCount=2, " + "validCharacters=abcdefghijklmnopqrstuvwxyz, " + "matchingCharacters=ab}", getDetail(validateShort, 0)); + assertEquals("ALLOWED_CHAR:{illegalCharacter=1, matchBehavior=contains}", getDetail(validateLong, 0)); + } + + @Test + public void givenCharacterCharacteristicsRule_whenValidatingPassword_thenItIsInvalidAsItBreaksToManyRules() { + PasswordData shortPassword = new PasswordData(); + shortPassword.setPassword("12345abcde!"); + + CharacterCharacteristicsRule characterCharacteristicsRule = new CharacterCharacteristicsRule(4, new CharacterRule(EnglishCharacterData.LowerCase, 5), new CharacterRule(EnglishCharacterData.UpperCase, 5), new CharacterRule(EnglishCharacterData.Digit), + new CharacterRule(EnglishCharacterData.Special)); + + PasswordValidator passwordValidator = new PasswordValidator(characterCharacteristicsRule); + + RuleResult validate = passwordValidator.validate(shortPassword); + assertFalse(validate.isValid()); + + assertEquals("INSUFFICIENT_UPPERCASE:{" + "minimumRequired=5, " + "matchingCharacterCount=0, " + "validCharacters=ABCDEFGHIJKLMNOPQRSTUVWXYZ, " + "matchingCharacters=}", getDetail(validate, 0)); + assertEquals("INSUFFICIENT_CHARACTERISTICS:{" + "successCount=3, " + "minimumRequired=4, " + "ruleCount=4}", getDetail(validate, 1)); + } + + private String getDetail(RuleResult validate, int i) { + return validate.getDetails() + .get(i) + .toString(); + } +} diff --git a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java similarity index 67% rename from spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java rename to libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java index b362d72705..6565a5b085 100644 --- a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java +++ b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.cloud; +package com.baeldung.scribejava; import org.junit.Test; import org.junit.runner.RunWith; @@ -7,10 +7,11 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class LogSinkApplicationIntegrationTest { +public class ScribejavaUnitTest { @Test - public void contextLoads() { + public void contextLoad(){ + } } diff --git a/libraries-security/src/test/resources/messages.properties b/libraries-security/src/test/resources/messages.properties new file mode 100644 index 0000000000..ad0039d71d --- /dev/null +++ b/libraries-security/src/test/resources/messages.properties @@ -0,0 +1,2 @@ +TOO_LONG=Password must not have more characters than %2$s. +TOO_SHORT=Password must not contain less characters than %2$s. \ No newline at end of file diff --git a/libraries-server/README.md b/libraries-server/README.md new file mode 100644 index 0000000000..28f963ade8 --- /dev/null +++ b/libraries-server/README.md @@ -0,0 +1,9 @@ +### Relevant articles + +- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded) +- [Introduction to Netty](http://www.baeldung.com/netty) +- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling) +- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup) +- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) +- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) +- [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client) diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index 517cf6a07c..6fca09faf4 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -14,6 +14,73 @@ org.eclipse.paho org.eclipse.paho.client.mqttv3 1.2.0 - + + + + org.assertj + assertj-core + ${assertj.version} + + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + + + org.eclipse.jetty + jetty-webapp + ${jetty.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-logging + commons-logging + + + + + commons-io + commons-io + ${commons.io.version} + + + io.netty + netty-all + ${netty.version} + + + junit + junit + ${junit.version} + test + + + + + org.apache.tomcat + tomcat-catalina + ${tomcat.version} + - \ No newline at end of file + + + 3.6.2 + 4.5.3 + 2.5 + 9.4.8.v20171121 + 4.1.20.Final + 4.1 + 4.12 + 8.5.24 + + + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/AsyncServlet.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java rename to libraries-server/src/main/java/com/baeldung/jetty/AsyncServlet.java diff --git a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/BlockingServlet.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java rename to libraries-server/src/main/java/com/baeldung/jetty/BlockingServlet.java diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java b/libraries-server/src/main/java/com/baeldung/jetty/JettyServer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/JettyServer.java rename to libraries-server/src/main/java/com/baeldung/jetty/JettyServer.java diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java b/libraries-server/src/main/java/com/baeldung/jetty/JettyServerFactory.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java rename to libraries-server/src/main/java/com/baeldung/jetty/JettyServerFactory.java diff --git a/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java b/libraries-server/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java rename to libraries-server/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java b/libraries-server/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/CalculatorOperationHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerA.java b/libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerA.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ChannelHandlerA.java rename to libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerA.java diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java b/libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerB.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java rename to libraries-server/src/main/java/com/baeldung/netty/ChannelHandlerB.java diff --git a/libraries/src/main/java/com/baeldung/netty/ClientHandler.java b/libraries-server/src/main/java/com/baeldung/netty/ClientHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ClientHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/ClientHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/HttpMessageHandler.java b/libraries-server/src/main/java/com/baeldung/netty/HttpMessageHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/HttpMessageHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/HttpMessageHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/NettyClient.java b/libraries-server/src/main/java/com/baeldung/netty/NettyClient.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/NettyClient.java rename to libraries-server/src/main/java/com/baeldung/netty/NettyClient.java diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServer.java b/libraries-server/src/main/java/com/baeldung/netty/NettyServer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/NettyServer.java rename to libraries-server/src/main/java/com/baeldung/netty/NettyServer.java diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServerB.java b/libraries-server/src/main/java/com/baeldung/netty/NettyServerB.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/NettyServerB.java rename to libraries-server/src/main/java/com/baeldung/netty/NettyServerB.java diff --git a/libraries/src/main/java/com/baeldung/netty/Operation.java b/libraries-server/src/main/java/com/baeldung/netty/Operation.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/Operation.java rename to libraries-server/src/main/java/com/baeldung/netty/Operation.java diff --git a/libraries/src/main/java/com/baeldung/netty/ProcessingHandler.java b/libraries-server/src/main/java/com/baeldung/netty/ProcessingHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ProcessingHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/ProcessingHandler.java diff --git a/libraries/src/main/java/com/baeldung/netty/RequestData.java b/libraries-server/src/main/java/com/baeldung/netty/RequestData.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/RequestData.java rename to libraries-server/src/main/java/com/baeldung/netty/RequestData.java diff --git a/libraries/src/main/java/com/baeldung/netty/RequestDataEncoder.java b/libraries-server/src/main/java/com/baeldung/netty/RequestDataEncoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/RequestDataEncoder.java rename to libraries-server/src/main/java/com/baeldung/netty/RequestDataEncoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/RequestDecoder.java b/libraries-server/src/main/java/com/baeldung/netty/RequestDecoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/RequestDecoder.java rename to libraries-server/src/main/java/com/baeldung/netty/RequestDecoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseData.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseData.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ResponseData.java rename to libraries-server/src/main/java/com/baeldung/netty/ResponseData.java diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseDataDecoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java rename to libraries-server/src/main/java/com/baeldung/netty/ResponseDataDecoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseDataEncoder.java b/libraries-server/src/main/java/com/baeldung/netty/ResponseDataEncoder.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/ResponseDataEncoder.java rename to libraries-server/src/main/java/com/baeldung/netty/ResponseDataEncoder.java diff --git a/libraries/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java b/libraries-server/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java rename to libraries-server/src/main/java/com/baeldung/netty/SimpleProcessingHandler.java diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyFilter.java b/libraries-server/src/main/java/com/baeldung/tomcat/MyFilter.java similarity index 100% rename from libraries/src/main/java/com/baeldung/tomcat/MyFilter.java rename to libraries-server/src/main/java/com/baeldung/tomcat/MyFilter.java diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java b/libraries-server/src/main/java/com/baeldung/tomcat/MyServlet.java similarity index 100% rename from libraries/src/main/java/com/baeldung/tomcat/MyServlet.java rename to libraries-server/src/main/java/com/baeldung/tomcat/MyServlet.java diff --git a/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java b/libraries-server/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java similarity index 100% rename from libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java rename to libraries-server/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java b/libraries-server/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java rename to libraries-server/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java b/libraries-server/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java rename to libraries-server/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java b/libraries-server/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java rename to libraries-server/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java b/libraries-server/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java rename to libraries-server/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java diff --git a/libraries/src/test/resources/jetty-embedded-demo-app.war b/libraries-server/src/test/resources/jetty-embedded-demo-app.war similarity index 100% rename from libraries/src/test/resources/jetty-embedded-demo-app.war rename to libraries-server/src/test/resources/jetty-embedded-demo-app.war diff --git a/libraries/README.md b/libraries/README.md index aed808420e..fcf687d806 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -5,13 +5,11 @@ - [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang) - [Introduction to Javatuples](http://www.baeldung.com/java-tuples) - [Introduction to Javassist](http://www.baeldung.com/javassist) -- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded) - [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink) - [Introduction to JSONassert](http://www.baeldung.com/jsonassert) - [Intro to JaVers](http://www.baeldung.com/javers) - [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) - [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd) -- [Introduction to Netty](http://www.baeldung.com/netty) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay) - [Introduction to Quartz](http://www.baeldung.com/quartz) @@ -35,7 +33,6 @@ - [Introduction to Eclipse Collections](http://www.baeldung.com/eclipse-collections) - [DistinctBy in Java Stream API](http://www.baeldung.com/java-streams-distinct-by) - [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv) -- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) - [Introduction to NoException](http://www.baeldung.com/no-exception) - [Apache Commons IO](http://www.baeldung.com/apache-commons-io) - [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types) @@ -55,10 +52,7 @@ - [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) - [Guide to google-http-client](http://www.baeldung.com/google-http-client) - [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client) -- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup) - [A Docker Guide for Java](http://www.baeldung.com/docker-java-api) -- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling) -- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) - [Introduction To OpenCSV](http://www.baeldung.com/opencsv) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client) @@ -78,7 +72,6 @@ - [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client) - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) - [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) -- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) - [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices) - [Introduction to JavaPoet](http://www.baeldung.com/java-poet) - [Introduction to Joda-Time](http://www.baeldung.com/joda-time) @@ -88,6 +81,8 @@ - [Guide to Resilience4j](http://www.baeldung.com/resilience4j) - [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml) - [Guide to JMapper](http://www.baeldung.com/jmapper) +- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) +- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 7402d88ef3..91c54b6113 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -106,21 +106,6 @@ javers-core ${javers.version} - - org.eclipse.jetty - jetty-server - ${jetty.version} - - - org.eclipse.jetty - jetty-servlet - ${jetty.version} - - - org.eclipse.jetty - jetty-webapp - ${jetty.version} - io.nats @@ -169,34 +154,7 @@ commons-dbutils ${commons.dbutils.version} - - org.apache.flink - flink-core - ${flink.version} - - - commons-logging - commons-logging - - - - - org.apache.flink - flink-java - ${flink.version} - - - commons-logging - commons-logging - - - - - org.apache.flink - flink-test-utils_2.10 - ${flink.version} - test - + org.apache.commons commons-math3 @@ -243,6 +201,7 @@ jackson-databind ${jackson.version} + org.datanucleus @@ -379,11 +338,6 @@ jmh-generator-annprocess ${jmh.version} - - io.netty - netty-all - ${netty.version} - junit junit @@ -481,17 +435,6 @@ logging-interceptor ${logging-interceptor.version} - - com.darwinsys - hirondelle-date4j - RELEASE - test - - - joda-time - joda-time - ${joda-time.version} - com.darwinsys hirondelle-date4j @@ -669,13 +612,7 @@ test test - - - - org.apache.tomcat - tomcat-catalina - ${tomcat.version} - + org.milyn milyn-smooks-all @@ -737,11 +674,6 @@ resilience4j-timelimiter ${resilience4j.version} - - org.apache.commons - commons-math3 - ${common-math3-version} - org.knowm.xchart xchart @@ -803,19 +735,6 @@ - - org.apache.maven.plugins - maven-dependency-plugin - - - org.apache.felix - maven-bundle-plugin - ${maven-bundle-plugin.version} - maven-plugin - - - true - maven-failsafe-plugin ${maven-failsafe-plugin.version} @@ -935,12 +854,10 @@ 2.5 1.6 1.4.196 - 9.4.8.v20171121 1.0 4.5.3 2.5 - 1.2.0 2.8.5 2.92 1.9.26 @@ -948,7 +865,6 @@ 1.9.0 1.9.27 1.1.0 - 4.1.20.Final 4.1 4.12 0.10 @@ -974,10 +890,9 @@ 2.5.5 1.23.0 v4-rev493-1.21.0 - 1.0.0 + 2.0.0 1.7.0 3.0.14 - 8.5.24 2.2.0 9.1.5.Final 4.1 @@ -988,7 +903,6 @@ 2.1.2 2.5.11 0.12.1 - 3.6.1 3.5.2 3.6 2.7.1 diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java b/libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java new file mode 100644 index 0000000000..7d4316e3ec --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java @@ -0,0 +1,8 @@ +package com.baeldung.commons.lang3.application; + +public class Application { + + public static void main(String[] args) { + + } +} diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java b/libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java new file mode 100644 index 0000000000..68aab46c33 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java @@ -0,0 +1,25 @@ +package com.baeldung.commons.lang3.beans; + +public class User { + + private final String name; + private final String email; + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + return "User{" + "name=" + name + ", email=" + email + '}'; + } +} diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java b/libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java new file mode 100644 index 0000000000..ae5d80244c --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java @@ -0,0 +1,11 @@ +package com.baeldung.commons.lang3.beans; + +import org.apache.commons.lang3.concurrent.LazyInitializer; + +public class UserInitializer extends LazyInitializer { + + @Override + protected User initialize() { + return new User("John", "john@domain.com"); + } +} diff --git a/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java b/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java new file mode 100644 index 0000000000..15488bbaf4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java @@ -0,0 +1,56 @@ +package com.baeldung.kafka; + +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.KafkaException; + +import java.util.Properties; +import java.util.stream.Stream; + +import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.TRANSACTIONAL_ID_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG; + +public class TransactionalMessageProducer { + + private static final String DATA_MESSAGE_1 = "Put any space separated data here for count"; + private static final String DATA_MESSAGE_2 = "Output will contain count of every word in the message"; + + public static void main(String[] args) { + + KafkaProducer producer = createKafkaProducer(); + + producer.initTransactions(); + + try{ + + producer.beginTransaction(); + + Stream.of(DATA_MESSAGE_1, DATA_MESSAGE_2).forEach(s -> producer.send( + new ProducerRecord("input", null, s))); + + producer.commitTransaction(); + + }catch (KafkaException e){ + + producer.abortTransaction(); + + } + + } + + private static KafkaProducer createKafkaProducer() { + + Properties props = new Properties(); + props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ENABLE_IDEMPOTENCE_CONFIG, "true"); + props.put(TRANSACTIONAL_ID_CONFIG, "prod-0"); + props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + + return new KafkaProducer(props); + + } +} diff --git a/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java b/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java new file mode 100644 index 0000000000..0563ba6684 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java @@ -0,0 +1,105 @@ +package com.baeldung.kafka; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.consumer.OffsetAndMetadata; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.KafkaException; +import org.apache.kafka.common.TopicPartition; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.time.Duration.ofSeconds; +import static java.util.Collections.singleton; +import static org.apache.kafka.clients.consumer.ConsumerConfig.*; +import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.*; + +public class TransactionalWordCount { + + private static final String CONSUMER_GROUP_ID = "my-group-id"; + private static final String OUTPUT_TOPIC = "output"; + private static final String INPUT_TOPIC = "input"; + + public static void main(String[] args) { + + KafkaConsumer consumer = createKafkaConsumer(); + KafkaProducer producer = createKafkaProducer(); + + producer.initTransactions(); + + try { + + while (true) { + + ConsumerRecords records = consumer.poll(ofSeconds(60)); + + Map wordCountMap = records.records(new TopicPartition(INPUT_TOPIC, 0)) + .stream() + .flatMap(record -> Stream.of(record.value().split(" "))) + .map(word -> Tuple.of(word, 1)) + .collect(Collectors.toMap(tuple -> tuple.getKey(), t1 -> t1.getValue(), (v1, v2) -> v1 + v2)); + + producer.beginTransaction(); + + wordCountMap.forEach((key, value) -> producer.send(new ProducerRecord(OUTPUT_TOPIC, key, value.toString()))); + + Map offsetsToCommit = new HashMap<>(); + + for (TopicPartition partition : records.partitions()) { + List> partitionedRecords = records.records(partition); + long offset = partitionedRecords.get(partitionedRecords.size() - 1).offset(); + + offsetsToCommit.put(partition, new OffsetAndMetadata(offset + 1)); + } + + producer.sendOffsetsToTransaction(offsetsToCommit, CONSUMER_GROUP_ID); + producer.commitTransaction(); + + } + + } catch (KafkaException e) { + + producer.abortTransaction(); + + } + + + } + + private static KafkaConsumer createKafkaConsumer() { + Properties props = new Properties(); + props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(GROUP_ID_CONFIG, CONSUMER_GROUP_ID); + props.put(ENABLE_AUTO_COMMIT_CONFIG, "false"); + props.put(ISOLATION_LEVEL_CONFIG, "read_committed"); + props.put(KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); + props.put(VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); + + KafkaConsumer consumer = new KafkaConsumer<>(props); + consumer.subscribe(singleton(INPUT_TOPIC)); + return consumer; + } + + private static KafkaProducer createKafkaProducer() { + + Properties props = new Properties(); + props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ENABLE_IDEMPOTENCE_CONFIG, "true"); + props.put(TRANSACTIONAL_ID_CONFIG, "prod-1"); + props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + + return new KafkaProducer(props); + + } + +} diff --git a/libraries/src/main/java/com/baeldung/kafka/Tuple.java b/libraries/src/main/java/com/baeldung/kafka/Tuple.java new file mode 100644 index 0000000000..883de4ba21 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kafka/Tuple.java @@ -0,0 +1,24 @@ +package com.baeldung.kafka; + +public class Tuple { + + private String key; + private Integer value; + + private Tuple(String key, Integer value) { + this.key = key; + this.value = value; + } + + public static Tuple of(String key, Integer value){ + return new Tuple(key,value); + } + + public String getKey() { + return key; + } + + public Integer getValue() { + return value; + } +} diff --git a/libraries/src/main/java/com/baeldung/opencsv/examples/sync/BeanExamples.java b/libraries/src/main/java/com/baeldung/opencsv/examples/sync/BeanExamples.java index 76d044ca60..086f32677e 100644 --- a/libraries/src/main/java/com/baeldung/opencsv/examples/sync/BeanExamples.java +++ b/libraries/src/main/java/com/baeldung/opencsv/examples/sync/BeanExamples.java @@ -18,16 +18,19 @@ import java.util.List; public class BeanExamples { public static List beanBuilderExample(Path path, Class clazz) { + ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy(); + return beanBuilderExample(path, clazz, ms); + } + + public static List beanBuilderExample(Path path, Class clazz, MappingStrategy ms) { CsvTransfer csvTransfer = new CsvTransfer(); try { - ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy(); ms.setType(clazz); Reader reader = Files.newBufferedReader(path); - CsvToBean cb = new CsvToBeanBuilder(reader) - .withType(clazz) - .withMappingStrategy(ms) - .build(); + CsvToBean cb = new CsvToBeanBuilder(reader).withType(clazz) + .withMappingStrategy(ms) + .build(); csvTransfer.setCsvList(cb.parse()); reader.close(); @@ -40,11 +43,10 @@ public class BeanExamples { public static String writeCsvFromBean(Path path) { try { - Writer writer = new FileWriter(path.toString()); + Writer writer = new FileWriter(path.toString()); - StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer) - .withSeparator(CSVWriter.DEFAULT_SEPARATOR) - .build(); + StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer).withSeparator(CSVWriter.DEFAULT_SEPARATOR) + .build(); List list = new ArrayList<>(); list.add(new WriteExampleBean("Test1", "sfdsf", "fdfd")); diff --git a/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java index e46d8654a2..64e13a277e 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java @@ -42,4 +42,13 @@ public class BidiMapUnitTest { map.put("key1", "value1"); assertEquals(map.getKey("value1"), "key1"); } + + @Test + public void givenKeyValue_whenAddValue_thenReplaceFirstKey() { + BidiMap map = new DualHashBidiMap<>(); + map.put("key1", "value1"); + map.put("key2", "value1"); + assertEquals(map.size(), 1); + assertFalse(map.containsKey("key1")); + } } diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java new file mode 100644 index 0000000000..5eba736b4a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.commons.lang3.test; + +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.lang3.ArrayUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class ArrayUtilsUnitTest { + + @Test + public void givenArrayUtilsClass_whenCalledtoString_thenCorrect() { + String[] array = {"a", "b", "c"}; + assertThat(ArrayUtils.toString(array)).isEqualTo("{a,b,c}"); + } + + @Test + public void givenArrayUtilsClass_whenCalledtoStringIfArrayisNull_thenCorrect() { + String[] array = null; + assertThat(ArrayUtils.toString(array, "Array is null")).isEqualTo("Array is null"); + } + + @Test + public void givenArrayUtilsClass_whenCalledhashCode_thenCorrect() { + String[] array = {"a", "b", "c"}; + assertThat(ArrayUtils.hashCode(array)).isEqualTo(997619); + } + + @Test + public void givenArrayUtilsClass_whenCalledtoMap_thenCorrect() { + String[][] array = {{"1", "one", }, {"2", "two", }, {"3", "three"}}; + Map map = new HashMap(); + map.put("1", "one"); + map.put("2", "two"); + map.put("3", "three"); + assertThat(ArrayUtils.toMap(array)).isEqualTo(map); + } + + @Test + public void givenArrayUtilsClass_whenCallednullToEmptyStringArray_thenCorrect() { + String[] array = null; + assertThat(ArrayUtils.nullToEmpty(array)).isEmpty(); + } + + @Test + public void givenArrayUtilsClass_whenCallednullToEmptyObjectArray_thenCorrect() { + Object[] array = null; + assertThat(ArrayUtils.nullToEmpty(array)).isEmpty(); + } + + @Test + public void givenArrayUtilsClass_whenCalledsubarray_thenCorrect() { + int[] array = {1, 2, 3}; + int[] expected = {1}; + assertThat(ArrayUtils.subarray(array, 0, 1)).isEqualTo(expected); + } + + @Test + public void givenArrayUtilsClass_whenCalledisSameLength_thenCorrect() { + int[] array1 = {1, 2, 3}; + int[] array2 = {1, 2, 3}; + assertThat(ArrayUtils.isSameLength(array1, array2)).isTrue(); + } + + @Test + public void givenArrayUtilsClass_whenCalledreverse_thenCorrect() { + int[] array1 = {1, 2, 3}; + int[] array2 = {3, 2, 1}; + ArrayUtils.reverse(array1); + assertThat(array1).isEqualTo(array2); + } + + @Test + public void givenArrayUtilsClass_whenCalledIndexOf_thenCorrect() { + int[] array = {1, 2, 3}; + assertThat(ArrayUtils.indexOf(array, 1, 0)).isEqualTo(0); + } + + @Test + public void givenArrayUtilsClass_whenCalledcontains_thenCorrect() { + int[] array = {1, 2, 3}; + assertThat(ArrayUtils.contains(array, 1)).isTrue(); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java new file mode 100644 index 0000000000..f32980269a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class BasicThreadFactoryUnitTest { + + @Test + public void givenBasicThreadFactoryInstance_whenCalledBuilder_thenCorrect() { + BasicThreadFactory factory = new BasicThreadFactory.Builder() + .namingPattern("workerthread-%d") + .daemon(true) + .priority(Thread.MAX_PRIORITY) + .build(); + assertThat(factory).isInstanceOf(BasicThreadFactory.class); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java new file mode 100644 index 0000000000..f55f239d75 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.commons.lang3.test; + +import com.baeldung.commons.lang3.beans.User; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import org.apache.commons.lang3.reflect.ConstructorUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class ConstructorUtilsUnitTest { + + @Test + public void givenConstructorUtilsClass_whenCalledgetAccessibleConstructor_thenCorrect() { + assertThat(ConstructorUtils.getAccessibleConstructor(User.class, String.class, String.class)).isInstanceOf(Constructor.class); + } + + @Test + public void givenConstructorUtilsClass_whenCalledinvokeConstructor_thenCorrect() throws Exception { + assertThat(ConstructorUtils.invokeConstructor(User.class, "name", "email")).isInstanceOf(User.class); + } + + @Test + public void givenConstructorUtilsClass_whenCalledinvokeExactConstructor_thenCorrect() throws Exception { + String[] args = {"name", "email"}; + Class[] parameterTypes= {String.class, String.class}; + assertThat(ConstructorUtils.invokeExactConstructor(User.class, args, parameterTypes)).isInstanceOf(User.class); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java new file mode 100644 index 0000000000..8abb373e30 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.commons.lang3.test; + +import com.baeldung.commons.lang3.beans.User; +import org.apache.commons.lang3.reflect.FieldUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class FieldUtilsUnitTest { + + private static User user; + + @BeforeClass + public static void setUpUserInstance() { + user = new User("Julie", "julie@domain.com"); + } + + @Test + public void givenFieldUtilsClass_whenCalledgetField_thenCorrect() { + assertThat(FieldUtils.getField(User.class, "name", true).getName()).isEqualTo("name"); + } + + @Test + public void givenFieldUtilsClass_whenCalledgetFieldForceAccess_thenCorrect() { + assertThat(FieldUtils.getField(User.class, "name", true).getName()).isEqualTo("name"); + } + + @Test + public void givenFieldUtilsClass_whenCalledgetDeclaredFieldForceAccess_thenCorrect() { + assertThat(FieldUtils.getDeclaredField(User.class, "name", true).getName()).isEqualTo("name"); + } + + @Test + public void givenFieldUtilsClass_whenCalledgetAllField_thenCorrect() { + assertThat(FieldUtils.getAllFields(User.class).length).isEqualTo(2); + } + + @Test + public void givenFieldUtilsClass_whenCalledreadField_thenCorrect() throws IllegalAccessException { + assertThat(FieldUtils.readField(user, "name", true)).isEqualTo("Julie"); + } + + @Test + public void givenFieldUtilsClass_whenCalledreadDeclaredField_thenCorrect() throws IllegalAccessException { + assertThat(FieldUtils.readDeclaredField(user, "name", true)).isEqualTo("Julie"); + } + + @Test + public void givenFieldUtilsClass_whenCalledwriteField_thenCorrect() throws IllegalAccessException { + FieldUtils.writeField(user, "name", "Julie", true); + assertThat(FieldUtils.readField(user, "name", true)).isEqualTo("Julie"); + + } + + @Test + public void givenFieldUtilsClass_whenCalledwriteDeclaredField_thenCorrect() throws IllegalAccessException { + FieldUtils.writeDeclaredField(user, "name", "Julie", true); + assertThat(FieldUtils.readField(user, "name", true)).isEqualTo("Julie"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java new file mode 100644 index 0000000000..1a5094a16d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.math.Fraction; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class FractionUnitTest { + + @Test + public void givenFractionClass_whenCalledgetFraction_thenCorrect() { + assertThat(Fraction.getFraction(5, 6)).isInstanceOf(Fraction.class); + } + + @Test + public void givenTwoFractionInstances_whenCalledadd_thenCorrect() { + Fraction fraction1 = Fraction.getFraction(1, 4); + Fraction fraction2 = Fraction.getFraction(3, 4); + assertThat(fraction1.add(fraction2).toString()).isEqualTo("1/1"); + } + + @Test + public void givenTwoFractionInstances_whenCalledsubstract_thenCorrect() { + Fraction fraction1 = Fraction.getFraction(3, 4); + Fraction fraction2 = Fraction.getFraction(1, 4); + assertThat(fraction1.subtract(fraction2).toString()).isEqualTo("1/2"); + } + + @Test + public void givenTwoFractionInstances_whenCalledmultiply_thenCorrect() { + Fraction fraction1 = Fraction.getFraction(3, 4); + Fraction fraction2 = Fraction.getFraction(1, 4); + assertThat(fraction1.multiplyBy(fraction2).toString()).isEqualTo("3/16"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java new file mode 100644 index 0000000000..bbd24c8207 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.builder.HashCodeBuilder; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class HashCodeBuilderUnitTest { + + @Test + public void givenHashCodeBuilderInstance_whenCalledtoHashCode_thenCorrect() { + int hashcode = new HashCodeBuilder(17, 37) + .append("John") + .append("john@domain.com") + .toHashCode(); + assertThat(hashcode).isEqualTo(1269178828); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java new file mode 100644 index 0000000000..28ed8d2514 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ImmutablePairUnitTest { + + private static ImmutablePair immutablePair; + + @BeforeClass + public static void setUpImmutablePairInstance() { + immutablePair = new ImmutablePair<>("leftElement", "rightElement"); + } + + @Test + public void givenImmutablePairInstance_whenCalledgetLeft_thenCorrect() { + assertThat(immutablePair.getLeft()).isEqualTo("leftElement"); + } + + @Test + public void givenImmutablePairInstance_whenCalledgetRight_thenCorrect() { + assertThat(immutablePair.getRight()).isEqualTo("rightElement"); + } + + @Test + public void givenImmutablePairInstance_whenCalledof_thenCorrect() { + assertThat(ImmutablePair.of("leftElement", "rightElement")).isInstanceOf(ImmutablePair.class); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenImmutablePairInstance_whenCalledSetValue_thenThrowUnsupportedOperationException() { + immutablePair.setValue("newValue"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java new file mode 100644 index 0000000000..a9dd3fa7c0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.tuple.ImmutableTriple; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ImmutableTripleUnitTest { + + private static ImmutableTriple immutableTriple; + + @BeforeClass + public static void setUpImmutableTripleInstance() { + immutableTriple = new ImmutableTriple<>("leftElement", "middleElement", "rightElement"); + } + + @Test + public void givenImmutableTripleInstance_whenCalledgetLeft_thenCorrect() { + assertThat(immutableTriple.getLeft()).isEqualTo("leftElement"); + } + + @Test + public void givenImmutableTripleInstance_whenCalledgetMiddle_thenCorrect() { + assertThat(immutableTriple.getMiddle()).isEqualTo("middleElement"); + } + + @Test + public void givenImmutableInstance_whenCalledgetRight_thenCorrect() { + assertThat(immutableTriple.getRight()).isEqualTo("rightElement"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java new file mode 100644 index 0000000000..a08399f8de --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.commons.lang3.test; + +import com.baeldung.commons.lang3.beans.User; +import com.baeldung.commons.lang3.beans.UserInitializer; +import org.apache.commons.lang3.concurrent.ConcurrentException; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class LazyInitializerUnitTest { + + @Test + public void givenLazyInitializerInstance_whenCalledget_thenCorrect() throws ConcurrentException { + UserInitializer userInitializer = new UserInitializer(); + assertThat(userInitializer.get()).isInstanceOf(User.class); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java new file mode 100644 index 0000000000..5e1d15f2f8 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.lang3.test; + +import com.baeldung.commons.lang3.beans.User; +import java.lang.reflect.Method; +import org.apache.commons.lang3.reflect.MethodUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class MethodUtilsUnitTest { + + @Test + public void givenMethodUtilsClass_whenCalledgetAccessibleMethod_thenCorrect() { + assertThat(MethodUtils.getAccessibleMethod(User.class, "getName")).isInstanceOf(Method.class); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java new file mode 100644 index 0000000000..02041f51e8 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.mutable.MutableObject; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class MutableObjectUnitTest { + + private static MutableObject mutableObject; + + @BeforeClass + public static void setUpMutableObject() { + mutableObject = new MutableObject("Initial value"); + } + + @Test + public void givenMutableObject_whenCalledgetValue_thenCorrect() { + assertThat(mutableObject.getValue()).isInstanceOf(String.class); + } + + @Test + public void givenMutableObject_whenCalledsetValue_thenCorrect() { + mutableObject.setValue("Another value"); + assertThat(mutableObject.getValue()).isEqualTo("Another value"); + } + + @Test + public void givenMutableObject_whenCalledtoString_thenCorrect() { + assertThat(mutableObject.toString()).isEqualTo("Another value"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java new file mode 100644 index 0000000000..174ec70c4d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.tuple.MutablePair; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class MutablePairUnitTest { + + private static MutablePair mutablePair; + + @BeforeClass + public static void setUpMutablePairInstance() { + mutablePair = new MutablePair<>("leftElement", "rightElement"); + } + + @Test + public void givenMutablePairInstance_whenCalledgetLeft_thenCorrect() { + assertThat(mutablePair.getLeft()).isEqualTo("leftElement"); + } + + @Test + public void givenMutablePairInstance_whenCalledgetRight_thenCorrect() { + assertThat(mutablePair.getRight()).isEqualTo("rightElement"); + } + + @Test + public void givenMutablePairInstance_whenCalledsetLeft_thenCorrect() { + mutablePair.setLeft("newLeftElement"); + assertThat(mutablePair.getLeft()).isEqualTo("newLeftElement"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java new file mode 100644 index 0000000000..bdf254a102 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.math.NumberUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class NumberUtilsUnitTest { + + @Test + public void givenNumberUtilsClass_whenCalledcompareWithIntegers_thenCorrect() { + assertThat(NumberUtils.compare(1, 1)).isEqualTo(0); + } + + @Test + public void givenNumberUtilsClass_whenCalledcompareWithLongs_thenCorrect() { + assertThat(NumberUtils.compare(1L, 1L)).isEqualTo(0); + } + + @Test + public void givenNumberUtilsClass_whenCalledcreateNumber_thenCorrect() { + assertThat(NumberUtils.createNumber("123456")).isEqualTo(123456); + } + + @Test + public void givenNumberUtilsClass_whenCalledisDigits_thenCorrect() { + assertThat(NumberUtils.isDigits("123456")).isTrue(); + } + + @Test + public void givenNumberUtilsClass_whenCallemaxwithIntegerArray_thenCorrect() { + int[] array = {1, 2, 3, 4, 5, 6}; + assertThat(NumberUtils.max(array)).isEqualTo(6); + } + + @Test + public void givenNumberUtilsClass_whenCalleminwithIntegerArray_thenCorrect() { + int[] array = {1, 2, 3, 4, 5, 6}; + assertThat(NumberUtils.min(array)).isEqualTo(1); + } + + @Test + public void givenNumberUtilsClass_whenCalleminwithByteArray_thenCorrect() { + byte[] array = {1, 2, 3, 4, 5, 6}; + assertThat(NumberUtils.min(array)).isEqualTo((byte) 1); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java new file mode 100644 index 0000000000..ab39ba7bd9 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class StringUtilsUnitTest { + + @Test + public void givenStringUtilsClass_whenCalledisBlank_thenCorrect() { + assertThat(StringUtils.isBlank(" ")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisEmpty_thenCorrect() { + assertThat(StringUtils.isEmpty("")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisAllLowerCase_thenCorrect() { + assertThat(StringUtils.isAllLowerCase("abd")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisAllUpperCase_thenCorrect() { + assertThat(StringUtils.isAllUpperCase("ABC")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisMixedCase_thenCorrect() { + assertThat(StringUtils.isMixedCase("abC")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisAlpha_thenCorrect() { + assertThat(StringUtils.isAlpha("abc")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledisAlphanumeric_thenCorrect() { + assertThat(StringUtils.isAlphanumeric("abc123")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledcontains_thenCorrect() { + assertThat(StringUtils.contains("abc", "ab")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledcontainsAny_thenCorrect() { + assertThat(StringUtils.containsAny("abc", 'a', 'b', 'c')).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledcontainsIgnoreCase_thenCorrect() { + assertThat(StringUtils.containsIgnoreCase("abc", "ABC")).isTrue(); + } + + @Test + public void givenStringUtilsClass_whenCalledswapCase_thenCorrect() { + assertThat(StringUtils.swapCase("abc")).isEqualTo("ABC"); + } + + @Test + public void givenStringUtilsClass_whenCalledreverse_thenCorrect() { + assertThat(StringUtils.reverse("abc")).isEqualTo("cba"); + } + + @Test + public void givenStringUtilsClass_whenCalleddifference_thenCorrect() { + assertThat(StringUtils.difference("abc", "abd")).isEqualTo("d"); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java new file mode 100644 index 0000000000..0efe97f912 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.commons.lang3.test; + +import java.io.File; +import org.apache.commons.lang3.JavaVersion; +import org.apache.commons.lang3.SystemUtils; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class SystemsUtilsUnitTest { + + @Test + public void givenSystemUtilsClass_whenCalledgetJavaHome_thenCorrect() { + assertThat(SystemUtils.getJavaHome()).isEqualTo(new File("/usr/lib/jvm/java-8-oracle/jre")); + } + + @Test + public void givenSystemUtilsClass_whenCalledgetUserHome_thenCorrect() { + assertThat(SystemUtils.getUserHome()).isEqualTo(new File("/home/travis")); + } + + @Test + public void givenSystemUtilsClass_whenCalledisJavaVersionAtLeast_thenCorrect() { + assertThat(SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_RECENT)).isTrue(); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java new file mode 100644 index 0000000000..7d506bbbab --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.commons.lang3.test; + +import org.apache.commons.lang3.tuple.Triple; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class TripleUnitTest { + + private static Triple triple; + + @BeforeClass + public static void setUpTripleInstance() { + triple = Triple.of("leftElement", "middleElement", "rightElement"); + } + + @Test + public void givenTripleInstance_whenCalledgetLeft_thenCorrect() { + assertThat(triple.getLeft()).isEqualTo("leftElement"); + } + + @Test + public void givenTripleInstance_whenCalledgetMiddle_thenCorrect() { + assertThat(triple.getMiddle()).isEqualTo("middleElement"); + } + + @Test + public void givenTripleInstance_whenCalledgetRight_thenCorrect() { + assertThat(triple.getRight()).isEqualTo("rightElement"); + } +} diff --git a/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java b/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java index 4406494d30..e61f4158a7 100644 --- a/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java +++ b/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java @@ -4,10 +4,12 @@ import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.KafkaStreams; +import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.StreamsConfig; +import org.apache.kafka.streams.Topology; import org.apache.kafka.streams.kstream.KStream; -import org.apache.kafka.streams.kstream.KStreamBuilder; import org.apache.kafka.streams.kstream.KTable; +import org.apache.kafka.streams.kstream.Produced; import org.apache.kafka.test.TestUtils; import org.junit.Ignore; import org.junit.Test; @@ -36,20 +38,20 @@ public class KafkaStreamsLiveTest { streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getAbsolutePath()); // when - KStreamBuilder builder = new KStreamBuilder(); + StreamsBuilder builder = new StreamsBuilder(); KStream textLines = builder.stream(inputTopic); Pattern pattern = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS); KTable wordCounts = textLines.flatMapValues(value -> Arrays.asList(pattern.split(value.toLowerCase()))).groupBy((key, word) -> word).count(); - wordCounts.foreach((word, count) -> System.out.println("word: " + word + " -> " + count)); + textLines.foreach((word, count) -> System.out.println("word: " + word + " -> " + count)); String outputTopic = "outputTopic"; final Serde stringSerde = Serdes.String(); - final Serde longSerde = Serdes.Long(); - wordCounts.to(stringSerde, longSerde, outputTopic); + final Serde longSerde = Serdes.String(); + textLines.to(outputTopic, Produced.with(stringSerde,longSerde)); - KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration); + KafkaStreams streams = new KafkaStreams(new Topology(), streamsConfiguration); streams.start(); // then diff --git a/logging-modules/log4j/README.md b/logging-modules/log4j/README.md index 8aae1b5826..9f4184ccba 100644 --- a/logging-modules/log4j/README.md +++ b/logging-modules/log4j/README.md @@ -4,3 +4,4 @@ - [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode) - [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback) - [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders) +- [Logging Exceptions Using SLF4J](https://www.baeldung.com/slf4j-log-exceptions) diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/style.css b/logging-modules/log4j2/${sys:logging.folder.path} old mode 100644 new mode 100755 similarity index 100% rename from spring-security-mvc-socket/src/main/webapp/resources/styles/style.css rename to logging-modules/log4j2/${sys:logging.folder.path} diff --git a/logging-modules/log4j2/README.md b/logging-modules/log4j2/README.md index e209c6f035..2cf6f9768f 100644 --- a/logging-modules/log4j2/README.md +++ b/logging-modules/log4j2/README.md @@ -3,3 +3,4 @@ - [Intro to Log4j2 – Appenders, Layouts and Filters](http://www.baeldung.com/log4j2-appenders-layouts-filters) - [Log4j 2 and Lambda Expressions](http://www.baeldung.com/log4j-2-lazy-logging) - [Programmatic Configuration with Log4j 2](http://www.baeldung.com/log4j2-programmatic-config) +- [Creating a Custom Log4j2 Appender](https://www.baeldung.com/log4j2-custom-appender) diff --git a/lombok/README.md b/lombok/README.md index 1a787e32c7..d12c14416d 100644 --- a/lombok/README.md +++ b/lombok/README.md @@ -1,3 +1,5 @@ ## Relevant Articles: - [Introduction to Project Lombok](http://www.baeldung.com/intro-to-project-lombok) - [Using Lombok’s @Builder Annotation](http://www.baeldung.com/lombok-builder) +- [Using Lombok’s @Getter for Boolean Fields](https://www.baeldung.com/lombok-getter-boolean) +- [Lombok @Builder with Inheritance](https://www.baeldung.com/lombok-builder-inheritance) diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/Child.java b/lombok/src/main/java/com/baeldung/lombok/builder/Child.java new file mode 100644 index 0000000000..70f6d9c46e --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/Child.java @@ -0,0 +1,19 @@ +package com.baeldung.lombok.builder; + +import lombok.Builder; +import lombok.Getter; + +@Getter +public class Child extends Parent { + + private final String childName; + private final int childAge; + + @Builder(builderMethodName = "childBuilder") + public Child(String parentName, int parentAge, String childName, int childAge) { + super(parentName, parentAge); + this.childName = childName; + this.childAge = childAge; + } + +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/Parent.java b/lombok/src/main/java/com/baeldung/lombok/builder/Parent.java new file mode 100644 index 0000000000..0cf76d4b00 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/Parent.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.builder; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +public class Parent { + private final String parentName; + private final int parentAge; +} \ No newline at end of file diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterBoolean.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBoolean.java new file mode 100644 index 0000000000..2191396e5d --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBoolean.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.getter; + + +import lombok.Getter; + +/** + * Related Article Sections: + * 4. Using @Getter on a Boolean Field + * + */ +public class GetterBoolean { + + @Getter + private Boolean running = true; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitive.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitive.java new file mode 100644 index 0000000000..5601f85b8b --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitive.java @@ -0,0 +1,16 @@ +package com.baeldung.lombok.getter; + + +import lombok.Getter; + +/** + * Related Article Sections: + * 3. Using @Getter on a boolean Field + * + */ +public class GetterBooleanPrimitive { + + @Getter + private boolean running; + +} diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitiveSameAccessor.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitiveSameAccessor.java new file mode 100644 index 0000000000..af29a33c20 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanPrimitiveSameAccessor.java @@ -0,0 +1,18 @@ +package com.baeldung.lombok.getter; + + +import lombok.Getter; + +/** + * Related Article Sections: + * 3.2. Two boolean Fields With the Same Accessor Name + * + */ +public class GetterBooleanPrimitiveSameAccessor { + + @Getter + boolean running = true; + + @Getter + boolean isRunning = false; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanSameAccessor.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanSameAccessor.java new file mode 100644 index 0000000000..d972273b71 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanSameAccessor.java @@ -0,0 +1,13 @@ +package com.baeldung.lombok.getter; + +import lombok.Getter; + +/** + * Related Article Sections: + * 3.1. A boolean Field Having the Same Name With Its Accessor + * + */ +public class GetterBooleanSameAccessor { + @Getter + private boolean isRunning = true; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanType.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanType.java new file mode 100644 index 0000000000..0d3b9a928a --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterBooleanType.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.getter; + + +import lombok.Getter; + +/** + * Related Article Sections: + * 4. Using @Getter on a Boolean Field + * + */ +public class GetterBooleanType { + + @Getter + private Boolean running = true; +} diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java index acad7d6c04..56a380569d 100644 --- a/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java +++ b/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java @@ -1,42 +1,59 @@ package com.baeldung.lombok.builder; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.*; - -public class BuilderUnitTest -{ +public class BuilderUnitTest { @Test public void givenBuilder_WidgetIsBuilt() { - Widget testWidget = Widget.builder().name("foo").id(1).build(); - assertThat(testWidget.getName()) - .isEqualTo("foo"); - assertThat(testWidget.getId()) - .isEqualTo(1); + Widget testWidget = Widget.builder() + .name("foo") + .id(1) + .build(); + assertThat(testWidget.getName()).isEqualTo("foo"); + assertThat(testWidget.getId()).isEqualTo(1); } @Test public void givenToBuilder_whenToBuilder_BuilderIsCreated() { - Widget testWidget = Widget.builder().name("foo").id(1).build(); + Widget testWidget = Widget.builder() + .name("foo") + .id(1) + .build(); Widget.WidgetBuilder widgetBuilder = testWidget.toBuilder(); - Widget newWidget = widgetBuilder.id(2).build(); - assertThat(newWidget.getName()) - .isEqualTo("foo"); - assertThat(newWidget.getId()) - .isEqualTo(2); + Widget newWidget = widgetBuilder.id(2) + .build(); + assertThat(newWidget.getName()).isEqualTo("foo"); + assertThat(newWidget.getId()).isEqualTo(2); } - - @Test public void givenBuilderMethod_ClientIsBuilt() { - ImmutableClient testImmutableClient = ClientBuilder.builder().name("foo").id(1).build(); - assertThat(testImmutableClient.getName()) - .isEqualTo("foo"); - assertThat(testImmutableClient.getId()) - .isEqualTo(1); + ImmutableClient testImmutableClient = ClientBuilder.builder() + .name("foo") + .id(1) + .build(); + assertThat(testImmutableClient.getName()).isEqualTo("foo"); + assertThat(testImmutableClient.getId()).isEqualTo(1); } + + @Test + public void givenBuilderAtMethodLevel_ChildInheritingParentIsBuilt() { + Child child = Child.childBuilder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .build(); + + assertThat(child.getChildName()).isEqualTo("Emma"); + assertThat(child.getChildAge()).isEqualTo(6); + assertThat(child.getParentName()).isEqualTo("Andrea"); + assertThat(child.getParentAge()).isEqualTo(38); + } + } diff --git a/lombok/src/test/java/com/baeldung/lombok/getter/GetterBooleanUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/getter/GetterBooleanUnitTest.java new file mode 100644 index 0000000000..632594d575 --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/getter/GetterBooleanUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.lombok.getter; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class GetterBooleanUnitTest { + + @Test + public void whenBasicBooleanField_thenMethodNamePrefixedWithIsFollowedByFieldName() { + GetterBooleanPrimitive lombokExamples = new GetterBooleanPrimitive(); + assertFalse(lombokExamples.isRunning()); + } + + @Test + public void whenBooleanFieldPrefixedWithIs_thenMethodNameIsSameAsFieldName() { + GetterBooleanSameAccessor lombokExamples = new GetterBooleanSameAccessor(); + assertTrue(lombokExamples.isRunning()); + } + + @Test + public void whenTwoBooleanFieldsCauseNamingConflict_thenLombokMapsToFirstDeclaredField() { + GetterBooleanPrimitiveSameAccessor lombokExamples = new GetterBooleanPrimitiveSameAccessor(); + assertTrue(lombokExamples.isRunning() == lombokExamples.running); + assertFalse(lombokExamples.isRunning() == lombokExamples.isRunning); + } + + @Test + public void whenFieldOfBooleanType_thenLombokPrefixesMethodWithGetInsteadOfIs() { + GetterBooleanType lombokExamples = new GetterBooleanType(); + assertTrue(lombokExamples.getRunning()); + } +} diff --git a/lucene/README.md b/lucene/README.md index b1d33472f4..ea7f715480 100644 --- a/lucene/README.md +++ b/lucene/README.md @@ -2,3 +2,4 @@ - [Introduction to Apache Lucene](http://www.baeldung.com/lucene) - [A Simple File Search with Lucene](http://www.baeldung.com/lucene-file-search) +- [Guide to Lucene Analyzers](https://www.baeldung.com/lucene-analyzers) diff --git a/lucene/pom.xml b/lucene/pom.xml index a3960f6059..f427cfd8a7 100644 --- a/lucene/pom.xml +++ b/lucene/pom.xml @@ -23,6 +23,12 @@ lucene-queryparser ${lucene.version} + + org.apache.lucene + lucene-analyzers-common + ${lucene.version} + + @@ -32,7 +38,7 @@ 1.0.0.Final 1.16.10.0 - 7.1.0 + 7.4.0 \ No newline at end of file diff --git a/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java index 97b1ec7b5d..8a31d3cb5b 100644 --- a/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java +++ b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java @@ -4,7 +4,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; -import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.SortedDocValuesField; @@ -27,9 +27,9 @@ import org.apache.lucene.util.BytesRef; public class InMemoryLuceneIndex { private Directory memoryIndex; - private StandardAnalyzer analyzer; + private Analyzer analyzer; - public InMemoryLuceneIndex(Directory memoryIndex, StandardAnalyzer analyzer) { + public InMemoryLuceneIndex(Directory memoryIndex, Analyzer analyzer) { super(); this.memoryIndex = memoryIndex; this.analyzer = analyzer; diff --git a/lucene/src/main/java/com/baeldung/lucene/MyCustomAnalyzer.java b/lucene/src/main/java/com/baeldung/lucene/MyCustomAnalyzer.java new file mode 100644 index 0000000000..609e2d09d3 --- /dev/null +++ b/lucene/src/main/java/com/baeldung/lucene/MyCustomAnalyzer.java @@ -0,0 +1,26 @@ +package com.baeldung.lucene; + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.LowerCaseFilter; +import org.apache.lucene.analysis.StopFilter; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.analysis.en.PorterStemFilter; +import org.apache.lucene.analysis.miscellaneous.CapitalizationFilter; +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.analysis.standard.StandardFilter; +import org.apache.lucene.analysis.standard.StandardTokenizer; + +public class MyCustomAnalyzer extends Analyzer{ + + @Override + protected TokenStreamComponents createComponents(String fieldName) { + final StandardTokenizer src = new StandardTokenizer(); + TokenStream result = new StandardFilter(src); + result = new LowerCaseFilter(result); + result = new StopFilter(result, StandardAnalyzer.STOP_WORDS_SET); + result = new PorterStemFilter(result); + result = new CapitalizationFilter(result); + return new TokenStreamComponents(src, result); + } + +} diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneAnalyzerIntegrationTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneAnalyzerIntegrationTest.java new file mode 100644 index 0000000000..28a87bba8c --- /dev/null +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneAnalyzerIntegrationTest.java @@ -0,0 +1,147 @@ +package com.baeldung.lucene; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.analysis.core.KeywordAnalyzer; +import org.apache.lucene.analysis.core.SimpleAnalyzer; +import org.apache.lucene.analysis.core.StopAnalyzer; +import org.apache.lucene.analysis.core.WhitespaceAnalyzer; +import org.apache.lucene.analysis.custom.CustomAnalyzer; +import org.apache.lucene.analysis.en.EnglishAnalyzer; +import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper; +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; +import org.apache.lucene.document.Document; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.store.RAMDirectory; +import org.junit.Test; + +public class LuceneAnalyzerIntegrationTest { + + private static final String SAMPLE_TEXT = "This is baeldung.com Lucene Analyzers test"; + private static final String FIELD_NAME = "sampleName"; + + @Test + public void whenUseStandardAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new StandardAnalyzer()); + + assertThat(result, contains("baeldung.com", "lucene", "analyzers", "test")); + } + + @Test + public void whenUseStopAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new StopAnalyzer()); + + assertThat(result, contains("baeldung", "com", "lucene", "analyzers", "test")); + } + + @Test + public void whenUseSimpleAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new SimpleAnalyzer()); + + assertThat(result, contains("this", "is", "baeldung", "com", "lucene", "analyzers", "test")); + } + + @Test + public void whenUseWhiteSpaceAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new WhitespaceAnalyzer()); + + assertThat(result, contains("This", "is", "baeldung.com", "Lucene", "Analyzers", "test")); + } + + @Test + public void whenUseKeywordAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new KeywordAnalyzer()); + + assertThat(result, contains("This is baeldung.com Lucene Analyzers test")); + } + + @Test + public void whenUseEnglishAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new EnglishAnalyzer()); + + assertThat(result, contains("baeldung.com", "lucen", "analyz", "test")); + } + + @Test + public void whenUseCustomAnalyzerBuilder_thenAnalyzed() throws IOException { + Analyzer analyzer = CustomAnalyzer.builder() + .withTokenizer("standard") + .addTokenFilter("lowercase") + .addTokenFilter("stop") + .addTokenFilter("porterstem") + .addTokenFilter("capitalization") + .build(); + List result = analyze(SAMPLE_TEXT, analyzer); + + assertThat(result, contains("Baeldung.com", "Lucen", "Analyz", "Test")); + } + + @Test + public void whenUseCustomAnalyzer_thenAnalyzed() throws IOException { + List result = analyze(SAMPLE_TEXT, new MyCustomAnalyzer()); + + assertThat(result, contains("Baeldung.com", "Lucen", "Analyz", "Test")); + } + + // ================= usage example + + @Test + public void givenTermQuery_whenUseCustomAnalyzer_thenCorrect() { + InMemoryLuceneIndex luceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new MyCustomAnalyzer()); + luceneIndex.indexDocument("introduction", "introduction to lucene"); + luceneIndex.indexDocument("analyzers", "guide to lucene analyzers"); + Query query = new TermQuery(new Term("body", "Introduct")); + + List documents = luceneIndex.searchIndex(query); + assertEquals(1, documents.size()); + } + + @Test + public void givenTermQuery_whenUsePerFieldAnalyzerWrapper_thenCorrect() { + Map analyzerMap = new HashMap<>(); + analyzerMap.put("title", new MyCustomAnalyzer()); + analyzerMap.put("body", new EnglishAnalyzer()); + + PerFieldAnalyzerWrapper wrapper = + new PerFieldAnalyzerWrapper(new StandardAnalyzer(), analyzerMap); + InMemoryLuceneIndex luceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), wrapper); + luceneIndex.indexDocument("introduction", "introduction to lucene"); + luceneIndex.indexDocument("analyzers", "guide to lucene analyzers"); + + Query query = new TermQuery(new Term("body", "introduct")); + List documents = luceneIndex.searchIndex(query); + assertEquals(1, documents.size()); + + query = new TermQuery(new Term("title", "Introduct")); + + documents = luceneIndex.searchIndex(query); + assertEquals(1, documents.size()); + } + + // =================================================================== + + public List analyze(String text, Analyzer analyzer) throws IOException { + List result = new ArrayList(); + TokenStream tokenStream = analyzer.tokenStream(FIELD_NAME, text); + CharTermAttribute attr = tokenStream.addAttribute(CharTermAttribute.class); + tokenStream.reset(); + while (tokenStream.incrementToken()) { + result.add(attr.toString()); + } + return result; + } + +} diff --git a/maven-polyglot/README.md b/maven-polyglot/README.md new file mode 100644 index 0000000000..589315efd1 --- /dev/null +++ b/maven-polyglot/README.md @@ -0,0 +1,3 @@ +To run the maven-polyglot-json-app successfully, you first have to build the maven-polyglot-json-extension module using: mvn clean install. + +Related Articles: diff --git a/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml b/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml new file mode 100644 index 0000000000..c06b76e1b2 --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml @@ -0,0 +1,8 @@ + + + + com.baeldung.maven.polyglot + maven-polyglot-json-extension + 1.0-SNAPSHOT + + \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-json-app/pom.json b/maven-polyglot/maven-polyglot-json-app/pom.json new file mode 100644 index 0000000000..abd58f3127 --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-app/pom.json @@ -0,0 +1,34 @@ +{ + "modelVersion": "4.0.0", + "groupId": "com.baeldung.maven.polyglot", + "artifactId": "maven-polyglot-json-app", + "version": "1.0-SNAPSHOT", + "name": "Json Maven Polyglot", + "parent": { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-parent", + "version": "2.0.5.RELEASE", + "relativePath": null + }, + "properties": { + "project.build.sourceEncoding": "UTF-8", + "project.reporting.outputEncoding": "UTF-8", + "maven.compiler.source": "1.8", + "maven.compiler.target": "1.8", + "java.version": "1.8" + }, + "dependencies": [ + { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-web" + } + ], + "build": { + "plugins": [ + { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-maven-plugin" + } + ] + } +} \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java b/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java new file mode 100644 index 0000000000..d03116889f --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.maven.polyglot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.GetMapping; + +@RestController +@SpringBootApplication +public class MavenPolyglotApplication { + public static void main(String[] args) { + SpringApplication.run(MavenPolyglotApplication.class, args); + } + + @GetMapping("/") + public String home(){ + return "Hello JSON Maven Model !"; + } +} diff --git a/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json b/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json new file mode 100644 index 0000000000..f006582c12 --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json @@ -0,0 +1,109 @@ +{ + "modules": [], + "distributionManagement": null, + "properties": { + "project.reporting.outputEncoding": "UTF-8", + "java.version": "1.8", + "maven.compiler.source": "1.8", + "project.build.sourceEncoding": "UTF-8", + "maven.compiler.target": "1.8" + }, + "dependencyManagement": null, + "dependencies": [ + { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-web", + "version": null, + "type": "jar", + "classifier": null, + "scope": null, + "systemPath": null, + "exclusions": [], + "optional": null, + "managementKey": "org.springframework.boot:spring-boot-starter-web:jar" + } + ], + "repositories": [], + "pluginRepositories": [], + "reports": null, + "reporting": null, + "modelVersion": "4.0.0", + "parent": { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-parent", + "version": "2.0.5.RELEASE", + "relativePath": "", + "id": "org.springframework.boot:spring-boot-starter-parent:pom:2.0.5.RELEASE" + }, + "groupId": "com.demo.polyglot", + "artifactId": "maven-polyglot-app", + "version": "1.0.1", + "packaging": "jar", + "name": "Json Maven Polyglot", + "description": null, + "url": null, + "inceptionYear": null, + "organization": null, + "licenses": [], + "developers": [], + "contributors": [], + "mailingLists": [], + "prerequisites": null, + "scm": null, + "issueManagement": null, + "ciManagement": null, + "build": { + "plugins": [ + { + "inherited": null, + "configuration": null, + "inheritanceApplied": true, + "groupId": "org.liquibase", + "artifactId": "liquibase-maven-plugin", + "version": "3.0.5", + "extensions": null, + "executions": [], + "dependencies": [], + "goals": null, + "key": "org.liquibase:liquibase-maven-plugin", + "id": "org.liquibase:liquibase-maven-plugin:3.0.5", + "executionsAsMap": {} + } + ], + "pluginManagement": null, + "defaultGoal": null, + "resources": [], + "testResources": [], + "directory": null, + "finalName": null, + "filters": [], + "sourceDirectory": null, + "scriptSourceDirectory": null, + "testSourceDirectory": null, + "outputDirectory": null, + "testOutputDirectory": null, + "extensions": [], + "pluginsAsMap": { + "org.liquibase:liquibase-maven-plugin": { + "inherited": null, + "configuration": null, + "inheritanceApplied": true, + "groupId": "org.liquibase", + "artifactId": "liquibase-maven-plugin", + "version": "3.0.5", + "extensions": null, + "executions": [], + "dependencies": [], + "goals": null, + "key": "org.liquibase:liquibase-maven-plugin", + "id": "org.liquibase:liquibase-maven-plugin:3.0.5", + "executionsAsMap": {} + } + } + }, + "profiles": [], + "modelEncoding": "UTF-8", + "pomFile": null, + "id": "com.demo.polyglot:maven-polyglot-app:jar:1.0.1", + "projectDirectory": null +} diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml new file mode 100644 index 0000000000..d5c5b7ab55 --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + com.baeldung.maven.polyglot + maven-polyglot-json-extension + 1.0-SNAPSHOT + + + 1.8 + 1.8 + + + + + org.apache.maven + maven-core + 3.5.4 + provided + + + com.fasterxml.jackson.core + jackson-databind + 2.9.6 + + + + + + + org.codehaus.plexus + plexus-component-metadata + 1.7.1 + + + + generate-metadata + + + + + + + + \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java b/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java new file mode 100644 index 0000000000..a1756192e9 --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java @@ -0,0 +1,62 @@ +package com.demo.polyglot; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.maven.model.Model; +import org.apache.maven.model.building.FileModelSource; +import org.apache.maven.model.building.ModelProcessor; +import org.apache.maven.model.io.ModelParseException; +import org.apache.maven.model.io.ModelReader; +import org.codehaus.plexus.component.annotations.Component; +import org.codehaus.plexus.component.annotations.Requirement; +import org.codehaus.plexus.util.ReaderFactory; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.Map; + +@Component(role = ModelProcessor.class) +public class CustomModelProcessor implements ModelProcessor { + + private static final String XML_POM = "pom.xml"; + private static final String JSON_POM = "pom.json"; + private static final String JSON_EXT = ".json"; + + ObjectMapper objectMapper = new ObjectMapper(); + + @Requirement + private ModelReader modelReader; + + @Override + public File locatePom(File projectDirectory) { + File pomFile = new File(projectDirectory, JSON_POM); + if (!pomFile.exists()) { + pomFile = new File(projectDirectory, XML_POM); + } + return pomFile; + } + + @Override + public Model read(InputStream input, Map options) throws IOException, ModelParseException { + try (final Reader in = ReaderFactory.newPlatformReader(input)) { + return read(in, options); + } + } + + @Override + public Model read(Reader reader, Map options) throws IOException, ModelParseException { + FileModelSource source = (options != null) ? (FileModelSource) options.get(SOURCE) : null; + if (source != null && source.getLocation().endsWith(JSON_EXT)) { + Model model = objectMapper.readValue(reader, Model.class); + return model; + } + //It's a normal maven project with a pom.xml file + return modelReader.read(reader, options); + } + + @Override + public Model read(File input, Map options) throws IOException, ModelParseException { + return null; + } +} \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml b/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml new file mode 100644 index 0000000000..cfc6275681 --- /dev/null +++ b/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml @@ -0,0 +1,8 @@ + + + + io.takari.polyglot + polyglot-yaml + 0.3.1 + + \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-yml-app/pom.yml b/maven-polyglot/maven-polyglot-yml-app/pom.yml new file mode 100644 index 0000000000..445e2eec3b --- /dev/null +++ b/maven-polyglot/maven-polyglot-yml-app/pom.yml @@ -0,0 +1,7 @@ +modelVersion: 4.0.0 +groupId: com.baeldung.maven.polyglot +artifactId: maven-polyglot-yml-app +version: 1.0-SNAPSHOT +name: 'YAML Demo' + +properties: {maven.compiler.source: 1.8, maven.compiler.target: 1.8} \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java b/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java new file mode 100644 index 0000000000..2142c7f9b8 --- /dev/null +++ b/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java @@ -0,0 +1,7 @@ +package com.baeldung.maven.polyglot; + +public class YamlDemoApplication { + public static void main(String[] args) { + System.out.println("Hello Maven Polyglot YAML !"); + } +} diff --git a/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json b/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json new file mode 100644 index 0000000000..f006582c12 --- /dev/null +++ b/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json @@ -0,0 +1,109 @@ +{ + "modules": [], + "distributionManagement": null, + "properties": { + "project.reporting.outputEncoding": "UTF-8", + "java.version": "1.8", + "maven.compiler.source": "1.8", + "project.build.sourceEncoding": "UTF-8", + "maven.compiler.target": "1.8" + }, + "dependencyManagement": null, + "dependencies": [ + { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-web", + "version": null, + "type": "jar", + "classifier": null, + "scope": null, + "systemPath": null, + "exclusions": [], + "optional": null, + "managementKey": "org.springframework.boot:spring-boot-starter-web:jar" + } + ], + "repositories": [], + "pluginRepositories": [], + "reports": null, + "reporting": null, + "modelVersion": "4.0.0", + "parent": { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-parent", + "version": "2.0.5.RELEASE", + "relativePath": "", + "id": "org.springframework.boot:spring-boot-starter-parent:pom:2.0.5.RELEASE" + }, + "groupId": "com.demo.polyglot", + "artifactId": "maven-polyglot-app", + "version": "1.0.1", + "packaging": "jar", + "name": "Json Maven Polyglot", + "description": null, + "url": null, + "inceptionYear": null, + "organization": null, + "licenses": [], + "developers": [], + "contributors": [], + "mailingLists": [], + "prerequisites": null, + "scm": null, + "issueManagement": null, + "ciManagement": null, + "build": { + "plugins": [ + { + "inherited": null, + "configuration": null, + "inheritanceApplied": true, + "groupId": "org.liquibase", + "artifactId": "liquibase-maven-plugin", + "version": "3.0.5", + "extensions": null, + "executions": [], + "dependencies": [], + "goals": null, + "key": "org.liquibase:liquibase-maven-plugin", + "id": "org.liquibase:liquibase-maven-plugin:3.0.5", + "executionsAsMap": {} + } + ], + "pluginManagement": null, + "defaultGoal": null, + "resources": [], + "testResources": [], + "directory": null, + "finalName": null, + "filters": [], + "sourceDirectory": null, + "scriptSourceDirectory": null, + "testSourceDirectory": null, + "outputDirectory": null, + "testOutputDirectory": null, + "extensions": [], + "pluginsAsMap": { + "org.liquibase:liquibase-maven-plugin": { + "inherited": null, + "configuration": null, + "inheritanceApplied": true, + "groupId": "org.liquibase", + "artifactId": "liquibase-maven-plugin", + "version": "3.0.5", + "extensions": null, + "executions": [], + "dependencies": [], + "goals": null, + "key": "org.liquibase:liquibase-maven-plugin", + "id": "org.liquibase:liquibase-maven-plugin:3.0.5", + "executionsAsMap": {} + } + } + }, + "profiles": [], + "modelEncoding": "UTF-8", + "pomFile": null, + "id": "com.demo.polyglot:maven-polyglot-app:jar:1.0.1", + "projectDirectory": null +} diff --git a/maven/README.md b/maven/README.md index c5b875ce02..2d838bcb76 100644 --- a/maven/README.md +++ b/maven/README.md @@ -8,3 +8,5 @@ - [The Maven Verifier Plugin](http://www.baeldung.com/maven-verifier-plugin) - [The Maven Clean Plugin](http://www.baeldung.com/maven-clean-plugin) - [Build a Jar with Maven and Ignore the Test Results](http://www.baeldung.com/maven-ignore-test-results) +- [Maven Project with Multiple Source Directories](https://www.baeldung.com/maven-project-multiple-src-directories) +- [Integration Testing with Maven](https://www.baeldung.com/maven-integration-test) diff --git a/maven/pom.xml b/maven/pom.xml index a409432f8b..4bec533226 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -1,18 +1,60 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung maven 0.0.1-SNAPSHOT + war - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - + + + org.glassfish.jersey.containers + jersey-container-servlet-core + ${jersey.version} + + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey.version} + + + junit + junit + ${junit.version} + test + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.version} + + + 8999 + + quit + 9000 + + + + start-jetty + pre-integration-test + + start + + + + stop-jetty + post-integration-test + + stop + + + + maven-resources-plugin ${maven.resources.version} @@ -31,7 +73,7 @@ maven-compiler-plugin - ${maven-compiler-plugin.version} + ${maven.compiler.version} ${java.version} ${java.version} @@ -42,11 +84,13 @@ maven-surefire-plugin - ${maven-surefire-plugin.version} + ${maven.surefire.version} DataTest.java + **/*IntegrationTest + com.baeldung.maven.it.Integration TestFail.java DataCheck.java @@ -94,15 +138,166 @@ + + org.codehaus.mojo + build-helper-maven-plugin + ${maven.build.helper.version} + + + generate-sources + + add-source + + + + src/main/another-src + + + + + add-integration-test-source + generate-test-sources + + add-test-source + + + + src/integration-test/java + + + + + add-integration-test-resource + generate-test-resources + + add-test-resource + + + + + src/integration-test/resources + + + + + + + + + default + + + + maven-surefire-plugin + ${maven.surefire.version} + + + DataTest.java + + + TestFail.java + DataCheck.java + + true + + + + + + + failsafe + + + + maven-failsafe-plugin + ${maven.failsafe.version} + + + **/*RestIT + **/RestITCase + + + + + + integration-test + verify + + + + + + + + + surefire + + + + maven-surefire-plugin + ${maven.surefire.version} + + + integration-test + + test + + + + none + + + **/*IntegrationTest + + + + + + + + + + category + + + + maven-failsafe-plugin + ${maven.failsafe.version} + + + **/* + + com.baeldung.maven.it.Integration + + + + + integration-test + verify + + + + + + + + + + 1.8 3.0.2 - 2.21.0 + 3.8.0 + 2.22.0 + 2.22.0 1.1 3.0.0 + 3.0.0 Baeldung + 9.4.11.v20180605 + 2.27 + 4.12 - \ No newline at end of file diff --git a/maven/src/integration-test/java/com/baeldung/maven/it/RestITCase.java b/maven/src/integration-test/java/com/baeldung/maven/it/RestITCase.java new file mode 100644 index 0000000000..aaeeedb661 --- /dev/null +++ b/maven/src/integration-test/java/com/baeldung/maven/it/RestITCase.java @@ -0,0 +1,24 @@ +package com.baeldung.maven.it; + +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; + +import static org.junit.Assert.assertEquals; + +public class RestITCase { + @Test + public void whenSendingGet_thenMessageIsReturned() throws IOException { + String url = "http://localhost:8999"; + URLConnection connection = new URL(url).openConnection(); + try (InputStream response = connection.getInputStream(); + Scanner scanner = new Scanner(response)) { + String responseBody = scanner.nextLine(); + assertEquals("Welcome to Baeldung!", responseBody); + } + } +} diff --git a/maven/src/main/another-src/com/baeldung/maven/plugins/Foo.java b/maven/src/main/another-src/com/baeldung/maven/plugins/Foo.java new file mode 100644 index 0000000000..f8a6fe9853 --- /dev/null +++ b/maven/src/main/another-src/com/baeldung/maven/plugins/Foo.java @@ -0,0 +1,10 @@ +package com.baeldung.maven.plugins; + +public class Foo { + + public static String foo() { + return "foo"; + } + +} + diff --git a/maven/src/main/java/com/baeldung/maven/it/EndpointConfig.java b/maven/src/main/java/com/baeldung/maven/it/EndpointConfig.java new file mode 100644 index 0000000000..919210ccff --- /dev/null +++ b/maven/src/main/java/com/baeldung/maven/it/EndpointConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.maven.it; + +import org.glassfish.jersey.server.ResourceConfig; + +public class EndpointConfig extends ResourceConfig { + public EndpointConfig() { + register(RestEndpoint.class); + } +} diff --git a/maven/src/main/java/com/baeldung/maven/it/RestEndpoint.java b/maven/src/main/java/com/baeldung/maven/it/RestEndpoint.java new file mode 100644 index 0000000000..c234891865 --- /dev/null +++ b/maven/src/main/java/com/baeldung/maven/it/RestEndpoint.java @@ -0,0 +1,12 @@ +package com.baeldung.maven.it; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/") +public class RestEndpoint { + @GET + public String hello() { + return "Welcome to Baeldung!"; + } +} diff --git a/maven/src/main/java/com/baeldung/maven/plugins/MultipleSrcFolders.java b/maven/src/main/java/com/baeldung/maven/plugins/MultipleSrcFolders.java new file mode 100644 index 0000000000..d403918dd3 --- /dev/null +++ b/maven/src/main/java/com/baeldung/maven/plugins/MultipleSrcFolders.java @@ -0,0 +1,9 @@ +package com.baeldung.maven.plugins; + +public class MultipleSrcFolders { + + public static void callFoo() { + Foo.foo(); + } + +} diff --git a/maven/src/main/webapp/WEB-INF/web.xml b/maven/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..1751ad17a5 --- /dev/null +++ b/maven/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,17 @@ + + + rest-servlet + org.glassfish.jersey.servlet.ServletContainer + + javax.ws.rs.Application + com.baeldung.maven.it.EndpointConfig + + + + rest-servlet + /* + + \ No newline at end of file diff --git a/maven/src/test/java/com/baeldung/maven/it/Integration.java b/maven/src/test/java/com/baeldung/maven/it/Integration.java new file mode 100644 index 0000000000..112ce178ce --- /dev/null +++ b/maven/src/test/java/com/baeldung/maven/it/Integration.java @@ -0,0 +1,4 @@ +package com.baeldung.maven.it; + +public interface Integration { +} diff --git a/maven/src/test/java/com/baeldung/maven/it/RestIT.java b/maven/src/test/java/com/baeldung/maven/it/RestIT.java new file mode 100644 index 0000000000..0115d34f1e --- /dev/null +++ b/maven/src/test/java/com/baeldung/maven/it/RestIT.java @@ -0,0 +1,24 @@ +package com.baeldung.maven.it; + +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; + +import static org.junit.Assert.assertEquals; + +public class RestIT { + @Test + public void whenSendingGet_thenMessageIsReturned() throws IOException { + String url = "http://localhost:8999"; + URLConnection connection = new URL(url).openConnection(); + try (InputStream response = connection.getInputStream(); + Scanner scanner = new Scanner(response)) { + String responseBody = scanner.nextLine(); + assertEquals("Welcome to Baeldung!", responseBody); + } + } +} diff --git a/maven/src/test/java/com/baeldung/maven/it/RestIntegrationTest.java b/maven/src/test/java/com/baeldung/maven/it/RestIntegrationTest.java new file mode 100644 index 0000000000..2f913c8429 --- /dev/null +++ b/maven/src/test/java/com/baeldung/maven/it/RestIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.maven.it; + +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; + +import static org.junit.Assert.assertEquals; + +public class RestIntegrationTest { + @Test + public void whenSendingGet_thenMessageIsReturned() throws IOException { + String url = "http://localhost:8999"; + URLConnection connection = new URL(url).openConnection(); + try (InputStream response = connection.getInputStream(); + Scanner scanner = new Scanner(response)) { + String responseBody = scanner.nextLine(); + assertEquals("Welcome to Baeldung!", responseBody); + } + } +} diff --git a/maven/src/test/java/com/baeldung/maven/it/RestJUnitTest.java b/maven/src/test/java/com/baeldung/maven/it/RestJUnitTest.java new file mode 100644 index 0000000000..60995d75bd --- /dev/null +++ b/maven/src/test/java/com/baeldung/maven/it/RestJUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.maven.it; + +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; + +import static org.junit.Assert.assertEquals; + +@Category(Integration.class) +public class RestJUnitTest { + @Test + public void whenSendingGet_thenMessageIsReturned() throws IOException { + String url = "http://localhost:8999"; + URLConnection connection = new URL(url).openConnection(); + try (InputStream response = connection.getInputStream(); + Scanner scanner = new Scanner(response)) { + String responseBody = scanner.nextLine(); + assertEquals("Welcome to Baeldung!", responseBody); + } + } +} diff --git a/maven/src/test/java/testfail/TestFail.java b/maven/src/test/java/testfail/TestFail.java index 16f1619db4..3febd21031 100644 --- a/maven/src/test/java/testfail/TestFail.java +++ b/maven/src/test/java/testfail/TestFail.java @@ -1,10 +1,13 @@ package testfail; import org.junit.Test; +import org.junit.Ignore; import static org.junit.Assert.assertNotNull; public class TestFail { + + @Ignore //ignored so the entire tutorials build passes @Test public void whenMessageAssigned_thenItIsNotNull() { String message = "hello there"; diff --git a/maven/versions-maven-plugin/original/pom.xml b/maven/versions-maven-plugin/original/pom.xml new file mode 100644 index 0000000000..295c77b860 --- /dev/null +++ b/maven/versions-maven-plugin/original/pom.xml @@ -0,0 +1,76 @@ + + 4.0.0 + com.baeldung + versions-maven-plugin-example + 0.0.1-SNAPSHOT + + + 1.15 + + + + + + commons-io + commons-io + 2.3 + + + + org.apache.commons + commons-collections4 + 4.0 + + + + org.apache.commons + commons-lang3 + 3.0 + + + + org.apache.commons + commons-compress + ${commons-compress-version} + + + + commons-beanutils + commons-beanutils + 1.9.1-SNAPSHOT + + + + + + + + org.codehaus.mojo + versions-maven-plugin + 2.7 + + + org.apache.commons:commons-collections4 + + + + + + + + + apache.snapshots + Apache Development Snapshot Repository + https://repository.apache.org/content/repositories/snapshots/ + + false + + + true + + + + + \ No newline at end of file diff --git a/maven/versions-maven-plugin/pom.xml b/maven/versions-maven-plugin/pom.xml new file mode 100644 index 0000000000..295c77b860 --- /dev/null +++ b/maven/versions-maven-plugin/pom.xml @@ -0,0 +1,76 @@ + + 4.0.0 + com.baeldung + versions-maven-plugin-example + 0.0.1-SNAPSHOT + + + 1.15 + + + + + + commons-io + commons-io + 2.3 + + + + org.apache.commons + commons-collections4 + 4.0 + + + + org.apache.commons + commons-lang3 + 3.0 + + + + org.apache.commons + commons-compress + ${commons-compress-version} + + + + commons-beanutils + commons-beanutils + 1.9.1-SNAPSHOT + + + + + + + + org.codehaus.mojo + versions-maven-plugin + 2.7 + + + org.apache.commons:commons-collections4 + + + + + + + + + apache.snapshots + Apache Development Snapshot Repository + https://repository.apache.org/content/repositories/snapshots/ + + false + + + true + + + + + \ No newline at end of file diff --git a/maven/versions-maven-plugin/run-the-demo.sh b/maven/versions-maven-plugin/run-the-demo.sh new file mode 100755 index 0000000000..89ca871e01 --- /dev/null +++ b/maven/versions-maven-plugin/run-the-demo.sh @@ -0,0 +1,74 @@ +#!/bin/bash +#function to display commands +exe() { echo -e "\$ $@\n" ; "$@" ; } + +TEXT_COLOR='\033[1;33m' #Yellow +NO_COLOR='\033[0m' # No Color + +clear + +echo -e "======================================================================================" +echo -e " Showcase for the BAELDUNG tutorial \"Use the latest version of a dependency in Maven\"" +echo -e " Author: Andrea Ligios" +echo -e "======================================================================================" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Resetting the demo environment (which will be altered during the run): " +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +rm -f pom.xml.versionsBackup +cp original/pom.xml pom.xml +ls -lt pom.* +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Checking for newer versions of the Maven dependencies:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:display-dependency-updates +echo +read -p "Press enter to continue" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Updating SNAPSHOT dependencies to their RELEASE version, if any:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:use-releases +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " A backup has been created automatically:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +ls -lt pom.* +echo +read -p "Press enter to continue" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Updating RELEASE dependencies to their *next* RELEASE version:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:use-next-releases +echo +read -p "Press enter to continue" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Reverting every modification made since the beginning:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:revert +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " The backup is gone, and the pom.xml contains the initial dependencies:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +ls -lt pom.* +echo +read -p "Press enter to continue" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Updating RELEASE dependencies to their *latest* RELEASE version:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:use-latest-releases +echo +read -p "Press enter to continue" + +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " Committing the modifications to pom.xml:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +exe mvn versions:commit +echo -e "${TEXT_COLOR}\n--------------------------------------------------------------------------------------" +echo -e " The backup is gone, and the pom.xml contains the latest dependencies:" +echo -e "--------------------------------------------------------------------------------------${NO_COLOR}" +ls -lt pom.* +echo + +echo -e "${TEXT_COLOR}\nThat's all folks!${NO_COLOR}\n" diff --git a/meecrowave/pom.xml b/meecrowave/pom.xml deleted file mode 100644 index cf13aa1c1b..0000000000 --- a/meecrowave/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - 4.0.0 - com.baeldung - apache-meecrowave - 0.0.1 - apache-meecrowave - A sample REST API application with Meecrowave - - - 1.8 - 1.8 - - - - - org.apache.meecrowave - meecrowave-core - 1.2.1 - - - - org.apache.meecrowave - meecrowave-jpa - 1.2.1 - - - - com.squareup.okhttp3 - okhttp - 3.10.0 - - - org.apache.meecrowave - meecrowave-junit - 1.2.0 - test - - - - junit - junit - 4.10 - test - - - - - - - org.apache.meecrowave - meecrowave-maven-plugin - 1.2.1 - - - - \ No newline at end of file diff --git a/meecrowave/src/main/java/com/baeldung/meecrowave/Article.java b/meecrowave/src/main/java/com/baeldung/meecrowave/Article.java deleted file mode 100644 index 7925e8ff99..0000000000 --- a/meecrowave/src/main/java/com/baeldung/meecrowave/Article.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.meecrowave; - -public class Article { - private String name; - private String author; - - public Article() { - } - - public Article(String name, String author) { - this.author = author; - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } -} \ No newline at end of file diff --git a/meecrowave/src/main/java/com/baeldung/meecrowave/ArticleEndpoints.java b/meecrowave/src/main/java/com/baeldung/meecrowave/ArticleEndpoints.java deleted file mode 100644 index 6cb7012c64..0000000000 --- a/meecrowave/src/main/java/com/baeldung/meecrowave/ArticleEndpoints.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.meecrowave; - -import javax.enterprise.context.RequestScoped; -import javax.inject.Inject; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - -@RequestScoped -@Path("article") -public class ArticleEndpoints { - - @Inject - ArticleService articleService; - - @GET - public Response getArticle() { - return Response.ok() - .entity(new Article("name", "author")) - .build(); - - } - - @POST - public Response createArticle(Article article) { - return Response.status(Status.CREATED) - .entity(articleService.createArticle(article)) - .build(); - } -} \ No newline at end of file diff --git a/meecrowave/src/main/java/com/baeldung/meecrowave/ArticleService.java b/meecrowave/src/main/java/com/baeldung/meecrowave/ArticleService.java deleted file mode 100644 index 7bd6b87345..0000000000 --- a/meecrowave/src/main/java/com/baeldung/meecrowave/ArticleService.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.meecrowave; - -import javax.enterprise.context.ApplicationScoped; - -@ApplicationScoped -public class ArticleService { - public Article createArticle(Article article) { - return article; - } -} diff --git a/meecrowave/src/main/java/com/baeldung/meecrowave/Server.java b/meecrowave/src/main/java/com/baeldung/meecrowave/Server.java deleted file mode 100644 index 2aa7d0556f..0000000000 --- a/meecrowave/src/main/java/com/baeldung/meecrowave/Server.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.meecrowave; - -import org.apache.meecrowave.Meecrowave; - -public class Server { - public static void main(String[] args) { - final Meecrowave.Builder builder = new Meecrowave.Builder(); - builder.setScanningPackageIncludes("com.baeldung.meecrowave"); - builder.setJaxrsMapping("/api/*"); - builder.setJsonpPrettify(true); - - try (Meecrowave meecrowave = new Meecrowave(builder)) { - meecrowave.bake().await(); - } - } -} diff --git a/meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsTest.java b/meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsTest.java deleted file mode 100644 index 0dc9773490..0000000000 --- a/meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.meecrowave; - - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.meecrowave.Meecrowave; -import org.apache.meecrowave.junit.MonoMeecrowave; -import org.apache.meecrowave.testing.ConfigurationInject; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -@RunWith(MonoMeecrowave.Runner.class) -public class ArticleEndpointsTest { - - @ConfigurationInject - private Meecrowave.Builder config; - private static OkHttpClient client; - - @BeforeClass - public static void setup() { - client = new OkHttpClient(); - } - - @Test - public void whenRetunedArticle_thenCorrect() throws IOException { - final String base = "http://localhost:"+config.getHttpPort(); - - Request request = new Request.Builder() - .url(base+"/article") - .build(); - Response response = client.newCall(request).execute(); - assertEquals(200, response.code()); - } -} diff --git a/metrics/pom.xml b/metrics/pom.xml index 86f197240b..9cf1ec588f 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -84,6 +84,13 @@ spectator-api ${spectator-api.version} + + + org.assertj + assertj-core + test + + diff --git a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java index e7f3d7ec72..689e23ad6d 100644 --- a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java @@ -1,8 +1,12 @@ package com.baeldung.metrics.micrometer; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; +import static org.assertj.core.api.Assertions.withinPercentage; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import io.micrometer.atlas.AtlasMeterRegistry; @@ -31,8 +35,10 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import org.assertj.core.data.Percentage; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import com.netflix.spectator.atlas.AtlasConfig; @@ -156,7 +162,8 @@ public class MicrometerAtlasIntegrationTest { timer.record(30, TimeUnit.MILLISECONDS); assertTrue(2 == timer.count()); - assertTrue(50 > timer.totalTime(TimeUnit.MILLISECONDS) && 45 <= timer.totalTime(TimeUnit.MILLISECONDS)); + + assertThat(timer.totalTime(TimeUnit.MILLISECONDS)).isBetween(40.0, 55.0); } @Test @@ -173,7 +180,7 @@ public class MicrometerAtlasIntegrationTest { } long timeElapsed = longTaskTimer.stop(currentTaskId); - assertTrue(timeElapsed / (int) 1e6 == 2); + assertEquals(2L, timeElapsed/((int) 1e6),1L); } @Test diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java index 134c3c91cf..b8a5b93e49 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java @@ -27,6 +27,9 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; +/** + * Atlas server needs to be up and running for this live test to work. + */ public class AtlasObserverLiveTest { private final String atlasUri = "http://localhost:7101/api/v1"; diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeManualTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeManualTest.java index d810de155a..92bbd615b9 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeManualTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeManualTest.java @@ -109,20 +109,20 @@ public class MetricTypeManualTest { .build(), MILLISECONDS); Stopwatch stopwatch = timer.start(); - MILLISECONDS.sleep(1); - timer.record(2, MILLISECONDS); + SECONDS.sleep(1); + timer.record(2, SECONDS); stopwatch.stop(); - assertEquals("timer should count 1 millisecond", 1, timer + assertEquals("timer should count 1 second", 1000, timer .getValue() - .intValue()); - assertEquals("timer should count 3 millisecond in total", 3, timer.getTotalTime() - .intValue()); + .intValue(),1000); + assertEquals("timer should count 3 second in total", 3000, timer.getTotalTime() + .intValue(),1000); assertEquals("timer should record 2 updates", 2, timer .getCount() .intValue()); - assertEquals("timer should have max 2", 2, timer.getMax(), 0.01); + assertEquals("timer should have max 2", 2000, timer.getMax(), 0.01); } @Test @@ -161,7 +161,6 @@ public class MetricTypeManualTest { } @Test - //== public void givenStatsTimer_whenExecuteTask_thenStatsCalculated() throws Exception { System.setProperty("netflix.servo", "1000"); StatsTimer timer = new StatsTimer(MonitorConfig @@ -178,21 +177,21 @@ public class MetricTypeManualTest { .build(), MILLISECONDS); Stopwatch stopwatch = timer.start(); - MILLISECONDS.sleep(1); - timer.record(3, MILLISECONDS); + SECONDS.sleep(1); + timer.record(3, SECONDS); stopwatch.stop(); stopwatch = timer.start(); - timer.record(6, MILLISECONDS); - MILLISECONDS.sleep(2); + timer.record(6, SECONDS); + SECONDS.sleep(2); stopwatch.stop(); - assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalTime()); - assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalMeasurement()); + assertEquals("timer should count 12 seconds in total", 12000, timer.getTotalTime(),500); + assertEquals("timer should count 12 seconds in total", 12000, timer.getTotalMeasurement(),500); assertEquals("timer should record 4 updates", 4, timer.getCount()); - assertEquals("stats timer value time-cost/update should be 2", 3, timer + assertEquals("stats timer value time-cost/update should be 2", 3000, timer .getValue() - .intValue()); + .intValue(),500); final Map metricMap = timer .getMonitors() @@ -235,4 +234,4 @@ public class MetricTypeManualTest { assertEquals("information collected", informational.getValue()); } -} +} \ No newline at end of file diff --git a/micronaut/pom.xml b/micronaut/pom.xml index 56d051e506..7b722306b6 100644 --- a/micronaut/pom.xml +++ b/micronaut/pom.xml @@ -1,8 +1,10 @@ 4.0.0 com.baeldung.micronaut - hello-world + micronaut 0.1 + micronaut + com.baeldung.micronaut.helloworld.server.ServerApplication 1.0.0.M2 diff --git a/msf4j/pom.xml b/msf4j/pom.xml index cca8281764..9a6483772b 100644 --- a/msf4j/pom.xml +++ b/msf4j/pom.xml @@ -6,12 +6,22 @@ msf4j 0.0.1-SNAPSHOT - - org.wso2.msf4j - msf4j-service - 2.6.0 - + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + org.wso2.msf4j + msf4j-service + ${msf4j.version} + pom + + + org.wso2.msf4j @@ -27,7 +37,7 @@ com.baeldung.msf4j.msf4jintro.Application - 2.6.1 + 2.6.3 \ No newline at end of file diff --git a/mustache/pom.xml b/mustache/pom.xml index 6012c9a15a..a276dfbf43 100644 --- a/mustache/pom.xml +++ b/mustache/pom.xml @@ -3,7 +3,6 @@ 4.0.0 mustache - 0.0.1-SNAPSHOT jar mustache @@ -24,10 +23,8 @@ org.assertj assertj-core - ${assertj.version} - log4j log4j @@ -55,13 +52,6 @@ ${datafactory.version} - - junit - junit - ${junit.version} - test - - @@ -73,90 +63,13 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/AutoconfigurationTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - 0.9.2 - 3.7.0 1.2.16 - 4.12 - UTF-8 - 3.7.0 - 2.19.1 0.8 3.3.7 - 1.8 \ No newline at end of file diff --git a/optaplanner/README.md b/optaplanner/README.md new file mode 100644 index 0000000000..1568a615c0 --- /dev/null +++ b/optaplanner/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [A Guide to OptaPlanner](https://www.baeldung.com/opta-planner) diff --git a/optaplanner/pom.xml b/optaplanner/pom.xml new file mode 100644 index 0000000000..22abbedc8c --- /dev/null +++ b/optaplanner/pom.xml @@ -0,0 +1,27 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + optaplanner + + + + org.optaplanner + optaplanner-core + 7.9.0.Final + + + + + + + + + \ No newline at end of file diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java b/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java new file mode 100644 index 0000000000..8a820ab56e --- /dev/null +++ b/optaplanner/src/main/java/com/baeldung/optaplanner/CourseSchedule.java @@ -0,0 +1,63 @@ +package com.baeldung.optaplanner; + +import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; +import org.optaplanner.core.api.domain.solution.PlanningScore; +import org.optaplanner.core.api.domain.solution.PlanningSolution; +import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty; +import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +@PlanningSolution +public class CourseSchedule { + + Logger logger = LoggerFactory.getLogger("CourseSchedule"); + + private List roomList; + private List periodList; + private List lectureList; + private HardSoftScore score; + + public CourseSchedule(){ + roomList = new ArrayList<>(); + periodList = new ArrayList<>(); + lectureList = new ArrayList<>(); + } + + @ValueRangeProvider(id = "availableRooms") + @ProblemFactCollectionProperty + public List getRoomList() { + return roomList; + } + + @ValueRangeProvider(id = "availablePeriods") + @ProblemFactCollectionProperty + public List getPeriodList() { + return periodList; + } + + @PlanningEntityCollectionProperty + public List getLectureList() { + return lectureList; + } + + @PlanningScore + public HardSoftScore getScore() { + return score; + } + + public void setScore(HardSoftScore score) { + this.score = score; + } + + public void printCourseSchedule() { + lectureList.stream() + .map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString()) + .forEach(k -> logger.info(k)); + } + +} diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java b/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java new file mode 100644 index 0000000000..48af4e89d1 --- /dev/null +++ b/optaplanner/src/main/java/com/baeldung/optaplanner/Lecture.java @@ -0,0 +1,30 @@ +package com.baeldung.optaplanner; + +import org.optaplanner.core.api.domain.entity.PlanningEntity; +import org.optaplanner.core.api.domain.variable.PlanningVariable; + +@PlanningEntity +public class Lecture { + + private Integer roomNumber; + private Integer period; + + @PlanningVariable(valueRangeProviderRefs = {"availablePeriods"}) + public Integer getPeriod() { + return period; + } + + @PlanningVariable(valueRangeProviderRefs = {"availableRooms"}) + public Integer getRoomNumber() { + return roomNumber; + } + + public void setPeriod(Integer period) { + this.period = period; + } + + public void setRoomNumber(Integer roomNumber) { + this.roomNumber = roomNumber; + } + +} diff --git a/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java b/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java new file mode 100644 index 0000000000..11e5e4a5be --- /dev/null +++ b/optaplanner/src/main/java/com/baeldung/optaplanner/ScoreCalculator.java @@ -0,0 +1,32 @@ +package com.baeldung.optaplanner; + +import org.optaplanner.core.api.score.Score; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; +import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator; + +import java.util.HashSet; + +public class ScoreCalculator implements EasyScoreCalculator { + + @Override + public Score calculateScore(CourseSchedule courseSchedule) { + int hardScore = 0; + int softScore = 0; + + HashSet occupiedRooms = new HashSet<>(); + for (Lecture lecture : courseSchedule.getLectureList()) { + if(lecture.getPeriod() != null && lecture.getRoomNumber() != null) { + String roomInUse = lecture.getPeriod().toString() + ":" + lecture.getRoomNumber().toString(); + if (occupiedRooms.contains(roomInUse)) { + hardScore += -1; + } else { + occupiedRooms.add(roomInUse); + } + } else { + hardScore += -1; + } + } + + return HardSoftScore.valueOf(hardScore, softScore); + } +} diff --git a/optaplanner/src/main/resources/courseSchedule.drl b/optaplanner/src/main/resources/courseSchedule.drl new file mode 100644 index 0000000000..9372a24976 --- /dev/null +++ b/optaplanner/src/main/resources/courseSchedule.drl @@ -0,0 +1,14 @@ +package com.baeldung.optaplanner + +import com.baeldung.optaplanner.Lecture; +import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder; + +global HardSoftScoreHolder scoreHolder; + +rule "noNullRoomPeriod" + when + Lecture( roomNumber == null ); + Lecture( period == null ); + then + scoreHolder.addHardConstraintMatch(kcontext, -1); +end \ No newline at end of file diff --git a/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml b/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml new file mode 100644 index 0000000000..7cf95fdcd3 --- /dev/null +++ b/optaplanner/src/main/resources/courseScheduleSolverConfigDrools.xml @@ -0,0 +1,12 @@ + + + + + + courseSchedule.drl + + + + 10 + + \ No newline at end of file diff --git a/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml b/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml new file mode 100644 index 0000000000..0ad2264dcd --- /dev/null +++ b/optaplanner/src/main/resources/courseScheduleSolverConfiguration.xml @@ -0,0 +1,12 @@ + + + + + + com.baeldung.optaplanner.ScoreCalculator + + + + 10 + + \ No newline at end of file diff --git a/optaplanner/src/main/resources/logback.xml b/optaplanner/src/main/resources/logback.xml new file mode 100644 index 0000000000..c109aa19e2 --- /dev/null +++ b/optaplanner/src/main/resources/logback.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java b/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java new file mode 100644 index 0000000000..2847a233a5 --- /dev/null +++ b/optaplanner/src/test/java/com/baeldung/optaplanner/test/OptaPlannerUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.optaplanner.test; + +import com.baeldung.optaplanner.CourseSchedule; +import com.baeldung.optaplanner.Lecture; +import org.junit.Assert; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.optaplanner.core.api.solver.Solver; +import org.optaplanner.core.api.solver.SolverFactory; +import java.util.Arrays; + +public class OptaPlannerUnitTest { + + static CourseSchedule unsolvedCourseSchedule; + + @BeforeAll + public static void setUp() { + + unsolvedCourseSchedule = new CourseSchedule(); + + for(int i = 0; i < 10; i++){ + unsolvedCourseSchedule.getLectureList().add(new Lecture()); + } + + unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 })); + unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 })); + } + + @Test + public void test_whenCustomJavaSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(-4, solvedCourseSchedule.getScore().getHardScore()); + } + + @Test + public void test_whenDroolsSolver() { + + SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml"); + Solver solver = solverFactory.buildSolver(); + CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); + + Assert.assertNotNull(solvedCourseSchedule.getScore()); + Assert.assertEquals(0, solvedCourseSchedule.getScore().getHardScore()); + } +} diff --git a/orika/src/main/resources/logback.xml b/orika/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/orika/src/main/resources/logback.xml +++ b/orika/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/osgi/osgi-intro-sample-activator/pom.xml b/osgi/osgi-intro-sample-activator/pom.xml index 42008dafdd..77d7198698 100644 --- a/osgi/osgi-intro-sample-activator/pom.xml +++ b/osgi/osgi-intro-sample-activator/pom.xml @@ -8,7 +8,7 @@ - osgi-intro + osgi com.baeldung 1.0-SNAPSHOT diff --git a/osgi/osgi-intro-sample-client/pom.xml b/osgi/osgi-intro-sample-client/pom.xml index f0cf0a357a..7f5faedb30 100644 --- a/osgi/osgi-intro-sample-client/pom.xml +++ b/osgi/osgi-intro-sample-client/pom.xml @@ -8,7 +8,7 @@ bundle - osgi-intro + osgi com.baeldung 1.0-SNAPSHOT diff --git a/osgi/osgi-intro-sample-service/pom.xml b/osgi/osgi-intro-sample-service/pom.xml index 29741e7eb2..8f81645ad4 100644 --- a/osgi/osgi-intro-sample-service/pom.xml +++ b/osgi/osgi-intro-sample-service/pom.xml @@ -8,7 +8,7 @@ - osgi-intro + osgi com.baeldung 1.0-SNAPSHOT diff --git a/osgi/pom.xml b/osgi/pom.xml index 7c59fbaff4..9ebcb09091 100644 --- a/osgi/pom.xml +++ b/osgi/pom.xml @@ -2,9 +2,10 @@ 4.0.0 - osgi-intro + osgi pom 1.0-SNAPSHOT + osgi com.baeldung diff --git a/out/production/generated-sources8/src.main.resources.reladomo.ReladomoClassList.xml.log b/out/production/generated-sources8/src.main.resources.reladomo.ReladomoClassList.xml.log deleted file mode 100644 index 0bd4e29a45..0000000000 --- a/out/production/generated-sources8/src.main.resources.reladomo.ReladomoClassList.xml.log +++ /dev/null @@ -1,2 +0,0 @@ -f5a6ba3b942a82fcbfb72e61502d5c30 -9201deea diff --git a/out/production/introduction/views/index.scala.html b/out/production/introduction/views/index.scala.html deleted file mode 100644 index 4539f5a10b..0000000000 --- a/out/production/introduction/views/index.scala.html +++ /dev/null @@ -1,20 +0,0 @@ -@* - * 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") - -} diff --git a/out/production/introduction/views/main.scala.html b/out/production/introduction/views/main.scala.html deleted file mode 100644 index 9414f4be6e..0000000000 --- a/out/production/introduction/views/main.scala.html +++ /dev/null @@ -1,23 +0,0 @@ -@* - * This template is called from the `index` template. This template - * handles the rendering of the page header and body tags. It takes - * two arguments, a `String` for the title of the page and an `Html` - * object to insert into the body of the page. - *@ -@(title: String)(content: Html) - - - - - @* Here's where we render the page title `String`. *@ - @title - - - - - - @* And here's where we render the `Html` object containing - * the page content. *@ - @content - - diff --git a/out/production/main/com/baeldung/.gitignore b/out/production/main/com/baeldung/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/out/production/main/com/baeldung/.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/out/production/main151/com/baeldung/README.md b/out/production/main/com/baeldung/README.md similarity index 100% rename from out/production/main151/com/baeldung/README.md rename to out/production/main/com/baeldung/README.md diff --git a/out/production/main330/com/baeldung/enums/README.md b/out/production/main/com/baeldung/enums/README.md similarity index 100% rename from out/production/main330/com/baeldung/enums/README.md rename to out/production/main/com/baeldung/enums/README.md diff --git a/out/production/main330/com/baeldung/networking/README.md b/out/production/main/com/baeldung/networking/README.md similarity index 100% rename from out/production/main330/com/baeldung/networking/README.md rename to out/production/main/com/baeldung/networking/README.md diff --git a/out/production/main/com/baeldung/objectsize/MANIFEST.MF b/out/production/main/com/baeldung/objectsize/MANIFEST.MF new file mode 100644 index 0000000000..b814f624d0 --- /dev/null +++ b/out/production/main/com/baeldung/objectsize/MANIFEST.MF @@ -0,0 +1 @@ +Premain-class: com.baeldung.objectsize.InstrumentationAgent diff --git a/out/production/main330/com/baeldung/printscreen/README.md b/out/production/main/com/baeldung/printscreen/README.md similarity index 100% rename from out/production/main330/com/baeldung/printscreen/README.md rename to out/production/main/com/baeldung/printscreen/README.md diff --git a/out/production/main/javac-args/arguments b/out/production/main/javac-args/arguments new file mode 100644 index 0000000000..51639800a7 --- /dev/null +++ b/out/production/main/javac-args/arguments @@ -0,0 +1,2 @@ +-d javac-target -verbose +com/baeldung/javac/Data.java \ No newline at end of file diff --git a/out/production/main/javac-args/options b/out/production/main/javac-args/options new file mode 100644 index 0000000000..f02f2344ff --- /dev/null +++ b/out/production/main/javac-args/options @@ -0,0 +1,2 @@ +-d javac-target +-verbose \ No newline at end of file diff --git a/out/production/main/javac-args/types b/out/production/main/javac-args/types new file mode 100644 index 0000000000..ef2d861f84 --- /dev/null +++ b/out/production/main/javac-args/types @@ -0,0 +1 @@ +com/baeldung/javac/Data.java \ No newline at end of file diff --git a/out/production/main/javac-args/xlint-ops b/out/production/main/javac-args/xlint-ops new file mode 100644 index 0000000000..cdccbc0cce --- /dev/null +++ b/out/production/main/javac-args/xlint-ops @@ -0,0 +1,3 @@ +-d javac-target +-Xlint:rawtypes,unchecked,static,cast,serial,fallthrough +com/baeldung/javac/Data.java \ No newline at end of file diff --git a/out/production/main173/log4j.properties b/out/production/main/log4j.properties similarity index 100% rename from out/production/main173/log4j.properties rename to out/production/main/log4j.properties diff --git a/out/production/main237/com/baeldung/datetime/README.md b/out/production/main1/com/baeldung/datetime/README.md similarity index 100% rename from out/production/main237/com/baeldung/datetime/README.md rename to out/production/main1/com/baeldung/datetime/README.md diff --git a/out/production/main155/com/baeldung/git/README.md b/out/production/main155/com/baeldung/git/README.md deleted file mode 100644 index 7e6a597c28..0000000000 --- a/out/production/main155/com/baeldung/git/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information) diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt deleted file mode 100644 index bffe24e485..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt +++ /dev/null @@ -1,76 +0,0 @@ -About the application ---------------------- -This application demonstrates the usage of JavaEE Web Annotations. - - -Contents of the application ---------------------------- -1. AccountServlet.java - Demonstrates the @WebServlet and @ServletSecurity annotation. - -NOTES: @WebServlet annotation designates the AccountServlet class as a Servlet component. - The usage of its parameters 'urlPatterns' & 'initParams' can be observed. - An initialization parameter 'type' is being set to denote the type of the bank account. - - @ServletSecurity annotation imposes security constraints on the AccountServlet based on - the tomcat-users.xml. -   - This code assumes that your tomcat-users.xml looks as follows: - - - - - - - -   -N.B : To see @ServletSecurity annotation in action, please uncomment the annotation code - for @ServletSecurity. - - -2. BankAppServletContextListener.java - Demonstrates the @WebListener annotation for denoting a class as a ServletContextListener. - -NOTES: Sets a Servlet context attribute ATTR_DEFAULT_LANGUAGE to 'english' on web application start up, - which can then be used throughout the application. - - -3. LogInFilter.java - Demonstrates the @WebFilter annotation. - -NOTES: @WebFilter annotation designates the LogInFilter class as a Filter component. - It filters all requests to the bank account servlet and redirects them to - the login page. - -N.B : To see @WebFilter annotation in action, please uncomment the annotation code for @WebFilter. - - -4. UploadCustomerDocumentsServlet.java - Demonstrates the @MultipartConfig annotation. - -NOTES: @MultipartConfig anotation designates the UploadCustomerDocumentsServlet Servlet component, - to handle multipart/form-data requests. - To see it in action, deploy the web application an access the url: http://:/JavaEEAnnotationsSample/upload.jsp - Once you upload a file from here, it will get uploaded to D:/custDocs (assuming such a folder exists). - - -5. index.jsp - This is the welcome page. - -NOTES: You can enter a deposit amount here and click on the 'Deposit' button to see the AccountServlet in action. - -6. login.jsp - All requests to the AccountServlet are redirected to this page, if the LogInFilter is imposed. - -7. upload.jsp - Demonstrates the usage of handling multipart/form-data requests by the UploadCustomerDocumentsServlet. - - -Building and Running the application ------------------------------------- -To build the application: - -1. Open the project in eclipse -2. Right click on it in eclispe and choose Run As > Maven build -3. Give 'clean install' under Goals -4. This should build the WAR file of the application - -To run the application: - -1. Right click on the project -2. Run as > Run on Server -3. This will start you Tomcat server and deploy the application (Provided that you have configured Tomcat in your eclipse) -4. You should now be able to access the url : http://:/JavaEEAnnotationsSample diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml deleted file mode 100644 index 25f901459c..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - 4.0.0 - com.baeldung.javaeeannotations - JavaEEAnnotationsSample - 0.0.1-SNAPSHOT - war - JavaEEAnnotationsSample - JavaEEAnnotationsSample - - - - - javax.annotation - javax.annotation-api - ${annotation-api.version} - - - - javax.servlet - javax.servlet-api - ${servlet.version} - - - - javax.servlet.jsp - jsp-api - ${jsp.version} - - - - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - src/main/webapp - SpringFieldConstructorInjection - false - - - - - JavaEEAnnotationsSample - - - - 1.3 - 3.1.0 - 2.1 - 2.4 - - \ No newline at end of file diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index a92885ec11..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - BASIC - default - - diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp deleted file mode 100644 index c49dec859e..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp +++ /dev/null @@ -1,16 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -My Account - - -
    - Amount: -    - -
    - - \ No newline at end of file diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp deleted file mode 100644 index 6892cb0420..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp +++ /dev/null @@ -1,12 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Login - - -Login Here... - - \ No newline at end of file diff --git a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp b/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp deleted file mode 100644 index 3601322ef0..0000000000 --- a/out/production/main180/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp +++ /dev/null @@ -1,16 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Insert title here - - -
    - -
    - -
    - - \ No newline at end of file diff --git a/out/production/main180/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl b/out/production/main180/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl deleted file mode 100644 index 426717f90e..0000000000 --- a/out/production/main180/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/out/production/main195/com/baeldung/java/nio/selector/README.md b/out/production/main195/com/baeldung/java/nio/selector/README.md deleted file mode 100644 index b28aae1397..0000000000 --- a/out/production/main195/com/baeldung/java/nio/selector/README.md +++ /dev/null @@ -1,2 +0,0 @@ -###Relevant Articles: -- [Introduction to the Java NIO Selector](http://www.baeldung.com/java-nio-selector) diff --git a/out/production/main216/com/baeldung/googlehttpclientguide/logging.properties b/out/production/main216/com/baeldung/googlehttpclientguide/logging.properties deleted file mode 100644 index 02489378df..0000000000 --- a/out/production/main216/com/baeldung/googlehttpclientguide/logging.properties +++ /dev/null @@ -1,10 +0,0 @@ -# Properties file which configures the operation of the JDK logging facility. -# The system will look for this config file to be specified as a system property: -# -Djava.util.logging.config.file=${project_loc:dailymotion-simple-cmdline-sample}/logging.properties - -# Set up the console handler (uncomment "level" to show more fine-grained messages) -handlers = java.util.logging.ConsoleHandler -java.util.logging.ConsoleHandler.level = ALL - -# Set up logging of HTTP requests and responses (uncomment "level" to show) -com.google.api.client.http.level = ALL diff --git a/out/production/main231/com/baeldung/wicket/examples/HelloWorld.html b/out/production/main231/com/baeldung/wicket/examples/HelloWorld.html deleted file mode 100644 index 497e98e01a..0000000000 --- a/out/production/main231/com/baeldung/wicket/examples/HelloWorld.html +++ /dev/null @@ -1,52 +0,0 @@ - - - - -Wicket Intro Examples - - - -
    -
    -
    -

    Wicket Introduction Examples:

    - - Hello World! -
    -
    - Cafes -
    -
    -
    -
    - - diff --git a/out/production/main231/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html b/out/production/main231/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html deleted file mode 100644 index c5ada2323d..0000000000 --- a/out/production/main231/com/baeldung/wicket/examples/cafeaddress/CafeAddress.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - -Cafes - - -
    - -

    - Address: address -

    -
    - - diff --git a/out/production/main231/com/baeldung/wicket/examples/helloworld/HelloWorld.html b/out/production/main231/com/baeldung/wicket/examples/helloworld/HelloWorld.html deleted file mode 100644 index c56d07fc10..0000000000 --- a/out/production/main231/com/baeldung/wicket/examples/helloworld/HelloWorld.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/out/production/main234/com/baeldung/activiti/security.rar b/out/production/main234/com/baeldung/activiti/security.rar deleted file mode 100644 index 38c4946168..0000000000 Binary files a/out/production/main234/com/baeldung/activiti/security.rar and /dev/null differ diff --git a/out/production/main291/xml-bean-config.xml b/out/production/main291/xml-bean-config.xml deleted file mode 100644 index 3b880bbd70..0000000000 --- a/out/production/main291/xml-bean-config.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/out/production/main30/com/baeldung/factorybean/README.md b/out/production/main30/com/baeldung/factorybean/README.md deleted file mode 100644 index 13f9f379e0..0000000000 --- a/out/production/main30/com/baeldung/factorybean/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) diff --git a/out/production/main330/com/baeldung/README.md b/out/production/main330/com/baeldung/README.md deleted file mode 100644 index 51809b2882..0000000000 --- a/out/production/main330/com/baeldung/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java) diff --git a/out/production/main330/log4j.properties b/out/production/main330/log4j.properties deleted file mode 100644 index 5fe42d854c..0000000000 --- a/out/production/main330/log4j.properties +++ /dev/null @@ -1,9 +0,0 @@ -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=DEBUG, A1 - -# A1 is set to be a ConsoleAppender. -log4j.appender.A1=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n diff --git a/out/production/main351/com/baeldung/produceimage/README.md b/out/production/main351/com/baeldung/produceimage/README.md deleted file mode 100644 index acd546598d..0000000000 --- a/out/production/main351/com/baeldung/produceimage/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Returning an Image or a File with Spring](http://www.baeldung.com/spring-controller-return-image-file) diff --git a/out/production/main96/com/baeldung/git/README.md b/out/production/main96/com/baeldung/git/README.md deleted file mode 100644 index 7e6a597c28..0000000000 --- a/out/production/main96/com/baeldung/git/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information) diff --git a/out/production/routing-in-play/views/index.scala.html b/out/production/routing-in-play/views/index.scala.html deleted file mode 100644 index 4539f5a10b..0000000000 --- a/out/production/routing-in-play/views/index.scala.html +++ /dev/null @@ -1,20 +0,0 @@ -@* - * 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") - -} diff --git a/out/production/routing-in-play/views/main.scala.html b/out/production/routing-in-play/views/main.scala.html deleted file mode 100644 index 9414f4be6e..0000000000 --- a/out/production/routing-in-play/views/main.scala.html +++ /dev/null @@ -1,23 +0,0 @@ -@* - * This template is called from the `index` template. This template - * handles the rendering of the page header and body tags. It takes - * two arguments, a `String` for the title of the page and an `Html` - * object to insert into the body of the page. - *@ -@(title: String)(content: Html) - - - - - @* Here's where we render the page title `String`. *@ - @title - - - - - - @* And here's where we render the `Html` object containing - * the page content. *@ - @content - - diff --git a/out/test/test95/com/baeldung/hexToAscii/README.md b/out/test/test/com/baeldung/hexToAscii/README.md similarity index 100% rename from out/test/test95/com/baeldung/hexToAscii/README.md rename to out/test/test/com/baeldung/hexToAscii/README.md diff --git a/out/test/test95/com/baeldung/java/conversion/README.md b/out/test/test/com/baeldung/java/conversion/README.md similarity index 100% rename from out/test/test95/com/baeldung/java/conversion/README.md rename to out/test/test/com/baeldung/java/conversion/README.md diff --git a/out/test/test/com/baeldung/stringisnumeric.zip b/out/test/test/com/baeldung/stringisnumeric.zip new file mode 100644 index 0000000000..b8a7b9b35a Binary files /dev/null and b/out/test/test/com/baeldung/stringisnumeric.zip differ diff --git a/out/test/test105/com/baeldung/cglib/proxy/README.md b/out/test/test105/com/baeldung/cglib/proxy/README.md deleted file mode 100644 index abeabc6162..0000000000 --- a/out/test/test105/com/baeldung/cglib/proxy/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Introduction to cglib](http://www.baeldung.com/cglib) diff --git a/out/test/test143/com/baeldung/java9/README.MD b/out/test/test143/com/baeldung/java9/README.MD deleted file mode 100644 index 2f44a2336b..0000000000 --- a/out/test/test143/com/baeldung/java9/README.MD +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Artiles: -- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional) diff --git a/out/test/test174/org/baeldung/hamcrest/README.md b/out/test/test174/org/baeldung/hamcrest/README.md deleted file mode 100644 index 7266ecda3a..0000000000 --- a/out/test/test174/org/baeldung/hamcrest/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide) diff --git a/out/test/test191/com/baeldung/web/controller/README.md b/out/test/test191/com/baeldung/web/controller/README.md deleted file mode 100644 index 9923962dde..0000000000 --- a/out/test/test191/com/baeldung/web/controller/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [WebAppConfiguration in Spring Tests](http://www.baeldung.com/spring-webappconfiguration) diff --git a/out/test/test197/com/baeldung/java/nio2/README.md b/out/test/test197/com/baeldung/java/nio2/README.md deleted file mode 100644 index 569be82d27..0000000000 --- a/out/test/test197/com/baeldung/java/nio2/README.md +++ /dev/null @@ -1,11 +0,0 @@ -### Relevant Articles: -- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api) -- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path) -- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel) -- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng) -- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel) -- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor) -- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute) -- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) -- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice) -- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels) diff --git a/out/test/test237/META-INF/persistence.xml b/out/test/test237/META-INF/persistence.xml deleted file mode 100644 index 922aedbc39..0000000000 --- a/out/test/test237/META-INF/persistence.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - org.baeldung.persistence.model.Foo - org.baeldung.persistence.model.Bar - - - - - - - - - - - - - diff --git a/out/test/test95/org/baeldung/java/collections/README.md b/out/test/test95/org/baeldung/java/collections/README.md deleted file mode 100644 index 317d81fae7..0000000000 --- a/out/test/test95/org/baeldung/java/collections/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: -- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split) -- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) diff --git a/out/test/test95/org/baeldung/java/lists/README.md b/out/test/test95/org/baeldung/java/lists/README.md deleted file mode 100644 index 2a1e8aeeaa..0000000000 --- a/out/test/test95/org/baeldung/java/lists/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) diff --git a/out/test/test98/com/baeldung/applicationcontext/README.md b/out/test/test98/com/baeldung/applicationcontext/README.md deleted file mode 100644 index 211007e0cf..0000000000 --- a/out/test/test98/com/baeldung/applicationcontext/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: -- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) -- [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext) diff --git a/out/test/test98/com/baeldung/beanfactory/README.md b/out/test/test98/com/baeldung/beanfactory/README.md deleted file mode 100644 index cff20a184b..0000000000 --- a/out/test/test98/com/baeldung/beanfactory/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Guide to the Spring BeanFactory](http://www.baeldung.com/spring-beanfactory) diff --git a/parent-boot-1/pom.xml b/parent-boot-1/pom.xml index e4902de0e6..7742841d07 100644 --- a/parent-boot-1/pom.xml +++ b/parent-boot-1/pom.xml @@ -1,117 +1,55 @@ - 4.0.0 - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - pom - Parent for all Spring Boot 1.x modules + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + parent-boot-1 + 0.0.1-SNAPSHOT + pom + Parent for all Spring Boot 1.x modules - - org.springframework.boot - spring-boot-starter-parent - 1.5.13.RELEASE - - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - io.rest-assured - rest-assured - ${rest-assured.version} - - - org.springframework.boot - spring-boot-starter-test - test - - + + + + org.springframework.boot + spring-boot-dependencies + 1.5.15.RELEASE + pom + import + + + + + + io.rest-assured + rest-assured + ${rest-assured.version} + + + org.springframework.boot + spring-boot-starter-test + test + + - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*LiveTest.java - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - + + + + + org.springframework.boot + spring-boot-maven-plugin + 1.5.15.RELEASE + + + + - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - **/*LiveTest.java - **/AutoconfigurationTest.java - **/*UnitTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - */EthControllerTestOne.java - **/*EntryPointsTest.java - - - - - - - json - - - - - - - - - - UTF-8 - UTF-8 - 1.8 - 3.0.6 - - 2.20.1 - 3.7.0 - 1.8 - 1.8 - + + 3.1.0 + \ No newline at end of file diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index ab6162a5a5..de6cb5d068 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -1,25 +1,33 @@ 4.0.0 - com.baeldung parent-boot-2 0.0.1-SNAPSHOT pom Parent for all Spring Boot 2 modules - org.springframework.boot - spring-boot-starter-parent - 2.0.1.RELEASE - + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + org.springframework.boot + spring-boot-dependencies + 2.0.4.RELEASE + pom + import + + + io.rest-assured rest-assured - ${rest-assured.version} - + org.springframework.boot spring-boot-starter-test @@ -27,79 +35,19 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*LiveTest.java - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.0.4.RELEASE + + + + + - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - **/*LiveTest.java - **/AutoconfigurationTest.java - **/*UnitTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - */EthControllerTestOne.java - **/*EntryPointsTest.java - - - - - - - json - - - - - - thin-jar @@ -122,13 +70,8 @@ - UTF-8 - UTF-8 - 1.8 3.1.0 - 1.8 - 1.8 1.0.11.RELEASE diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml new file mode 100644 index 0000000000..7fd18e4fa4 --- /dev/null +++ b/parent-kotlin/pom.xml @@ -0,0 +1,194 @@ + + + 4.0.0 + parent-kotlin + pom + parent-kotlin + Parent for all kotlin modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + jcenter + http://jcenter.bintray.com + + + kotlin-ktor + https://dl.bintray.com/kotlin/ktor/ + + + + + + + org.springframework.boot + spring-boot-dependencies + 2.0.1.RELEASE + pom + import + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + ${kotlinx.version} + + + + io.ktor + ktor-server-netty + ${ktor.io.version} + + + io.ktor + ktor-gson + ${ktor.io.version} + + + + org.jetbrains.kotlin + kotlin-test-junit + ${kotlin.version} + test + + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + + compile + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + ${java.version} + + + + test-compile + + test-compile + + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + ${java.version} + + + + + + spring + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + default-compile + none + + + + default-testCompile + none + + + java-compile + compile + + compile + + + + java-test-compile + test-compile + + testCompile + + + + + + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + junit5 + + integration-test + verify + + + + **/*Test5.java + + + + + + + + + + 1.2.61 + 0.25.0 + 0.9.3 + 3.11.0 + 1.2.0 + + diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index 5fb8f735ab..75f7cec73a 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -11,3 +11,4 @@ - [Visitor Design Pattern in Java](http://www.baeldung.com/java-visitor-pattern) - [The DAO Pattern in Java](http://www.baeldung.com/java-dao-pattern) - [Interpreter Design Pattern in Java](http://www.baeldung.com/java-interpreter-pattern) +- [State Design Pattern in Java](https://www.baeldung.com/java-state-design-pattern) diff --git a/patterns/design-patterns/pom.xml b/patterns/design-patterns/pom.xml index 22fc88b75a..dc2631b36e 100644 --- a/patterns/design-patterns/pom.xml +++ b/patterns/design-patterns/pom.xml @@ -2,13 +2,12 @@ 4.0.0 - com.baeldung design-patterns 1.0 jar com.baeldung - patterns-parent + patterns 1.0.0-SNAPSHOT .. diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/DeliveredState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/DeliveredState.java new file mode 100644 index 0000000000..9f5e4d8fc4 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/DeliveredState.java @@ -0,0 +1,25 @@ +package com.baeldung.state; + +public class DeliveredState implements PackageState { + + @Override + public void next(Package pkg) { + pkg.setState(new ReceivedState()); + } + + @Override + public void prev(Package pkg) { + pkg.setState(new OrderedState()); + } + + @Override + public void printStatus() { + System.out.println("Package delivered to post office, not received yet."); + } + + @Override + public String toString() { + return "DeliveredState{}"; + } + +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/OrderedState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/OrderedState.java new file mode 100644 index 0000000000..0642c4c73c --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/OrderedState.java @@ -0,0 +1,24 @@ +package com.baeldung.state; + +public class OrderedState implements PackageState { + + @Override + public void next(Package pkg) { + pkg.setState(new DeliveredState()); + } + + @Override + public void prev(Package pkg) { + System.out.println("The package is in it's root state."); + } + + @Override + public void printStatus() { + System.out.println("Package ordered, not delivered to the office yet."); + } + + @Override + public String toString() { + return "OrderedState{}"; + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/Package.java b/patterns/design-patterns/src/main/java/com/baeldung/state/Package.java new file mode 100644 index 0000000000..f3dfbb3fa7 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/Package.java @@ -0,0 +1,26 @@ +package com.baeldung.state; + +public class Package { + + private PackageState state = new OrderedState(); + + public PackageState getState() { + return state; + } + + public void setState(PackageState state) { + this.state = state; + } + + public void previousState() { + state.prev(this); + } + + public void nextState() { + state.next(this); + } + + public void printStatus() { + state.printStatus(); + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/PackageState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/PackageState.java new file mode 100644 index 0000000000..d6656c78ac --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/PackageState.java @@ -0,0 +1,10 @@ +package com.baeldung.state; + +public interface PackageState { + + void next(Package pkg); + + void prev(Package pkg); + + void printStatus(); +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/ReceivedState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/ReceivedState.java new file mode 100644 index 0000000000..84136fa48e --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/ReceivedState.java @@ -0,0 +1,24 @@ +package com.baeldung.state; + +public class ReceivedState implements PackageState { + + @Override + public void next(Package pkg) { + System.out.println("This package is already received by a client."); + } + + @Override + public void prev(Package pkg) { + pkg.setState(new DeliveredState()); + } + + @Override + public void printStatus() { + System.out.println("Package was received by client."); + } + + @Override + public String toString() { + return "ReceivedState{}"; + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/StateDemo.java b/patterns/design-patterns/src/main/java/com/baeldung/state/StateDemo.java new file mode 100644 index 0000000000..1a63ea3ddf --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/StateDemo.java @@ -0,0 +1,19 @@ +package com.baeldung.state; + +public class StateDemo { + + public static void main(String[] args) { + + Package pkg = new Package(); + pkg.printStatus(); + + pkg.nextState(); + pkg.printStatus(); + + pkg.nextState(); + pkg.printStatus(); + + pkg.nextState(); + pkg.printStatus(); + } +} diff --git a/patterns/design-patterns/src/test/java/com/baeldung/state/StatePatternUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/state/StatePatternUnitTest.java new file mode 100644 index 0000000000..731974f92b --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/state/StatePatternUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.state; + +import com.baeldung.state.Package; + +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.instanceOf; + +import org.junit.Test; + +public class StatePatternUnitTest { + + @Test + public void givenNewPackage_whenPackageReceived_thenStateReceived() { + Package pkg = new Package(); + + assertThat(pkg.getState(), instanceOf(OrderedState.class)); + pkg.nextState(); + + assertThat(pkg.getState(), instanceOf(DeliveredState.class)); + pkg.nextState(); + + assertThat(pkg.getState(), instanceOf(ReceivedState.class)); + } + + @Test + public void givenDeliveredPackage_whenPrevState_thenStateOrdered() { + Package pkg = new Package(); + pkg.setState(new DeliveredState()); + pkg.previousState(); + + assertThat(pkg.getState(), instanceOf(OrderedState.class)); + } +} diff --git a/patterns/front-controller/pom.xml b/patterns/front-controller/pom.xml index 96ed86d975..435b0dd9cd 100644 --- a/patterns/front-controller/pom.xml +++ b/patterns/front-controller/pom.xml @@ -6,7 +6,7 @@ war - patterns-parent + patterns com.baeldung 1.0.0-SNAPSHOT .. diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml index ee6fef30c9..fa94d5d1fd 100644 --- a/patterns/intercepting-filter/pom.xml +++ b/patterns/intercepting-filter/pom.xml @@ -8,7 +8,7 @@ com.baeldung - patterns-parent + patterns 1.0.0-SNAPSHOT .. diff --git a/patterns/pom.xml b/patterns/pom.xml index c8f44227a3..df09f1836a 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -2,8 +2,7 @@ 4.0.0 - com.baeldung - patterns-parent + patterns pom diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index 0240b2c2ea..8c9d027724 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -3,7 +3,7 @@ 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 - performancetests + performance-tests parent-modules diff --git a/persistence-modules/README.md b/persistence-modules/README.md index 8f8c3eb13d..f12163bd6a 100644 --- a/persistence-modules/README.md +++ b/persistence-modules/README.md @@ -7,6 +7,5 @@ - [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) - [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) - [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce) -- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) - [A Guide to Jdbi](http://www.baeldung.com/jdbi) - [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index e9aabaaa74..418e0a67e2 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -1,3 +1,4 @@ # Relevant Articles -* [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) +- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) +- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/Car.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java similarity index 100% rename from jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/Car.java rename to persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/Car.java diff --git a/jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/QueryParameter.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java similarity index 100% rename from jpa-storedprocedure/src/main/java/com/baeldung/jpa/model/QueryParameter.java rename to persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index e9230eb6cd..3d881673b2 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -20,4 +20,18 @@ + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.model.Car + + + + + + + + + + \ No newline at end of file diff --git a/jpa-storedprocedure/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql b/persistence-modules/java-jpa/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql similarity index 100% rename from jpa-storedprocedure/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql rename to persistence-modules/java-jpa/src/main/resources/config/database/FindCarByYearProcedureMySQL.sql diff --git a/jpa-storedprocedure/src/main/resources/config/database/create_table_mysql.sql b/persistence-modules/java-jpa/src/main/resources/config/database/create_table_mysql.sql similarity index 100% rename from jpa-storedprocedure/src/main/resources/config/database/create_table_mysql.sql rename to persistence-modules/java-jpa/src/main/resources/config/database/create_table_mysql.sql diff --git a/jpa-storedprocedure/src/main/resources/config/database/insert_cars.sql b/persistence-modules/java-jpa/src/main/resources/config/database/insert_cars.sql similarity index 100% rename from jpa-storedprocedure/src/main/resources/config/database/insert_cars.sql rename to persistence-modules/java-jpa/src/main/resources/config/database/insert_cars.sql diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java similarity index 100% rename from jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java rename to persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java diff --git a/jpa-storedprocedure/src/test/resources/persistence.xml b/persistence-modules/java-jpa/src/test/resources/persistence.xml similarity index 100% rename from jpa-storedprocedure/src/test/resources/persistence.xml rename to persistence-modules/java-jpa/src/test/resources/persistence.xml diff --git a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..46ee3cd368 --- /dev/null +++ b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,67 @@ +package org.baeldung; + +import java.io.IOException; +import java.util.HashMap; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import org.baeldung.spring.data.cassandra.config.CassandraConfig; +import org.baeldung.spring.data.cassandra.model.Book; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class SpringContextIntegrationTest { + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private CassandraAdminOperations adminTemplate; + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + final Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + Thread.sleep(5000); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/persistence-modules/spring-data-dynamodb/pom.xml b/persistence-modules/spring-data-dynamodb/pom.xml index 9f2b63c17c..4cb805131a 100644 --- a/persistence-modules/spring-data-dynamodb/pom.xml +++ b/persistence-modules/spring-data-dynamodb/pom.xml @@ -2,10 +2,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - spring-boot-dynamodb + spring-data-dynamodb 0.0.1-SNAPSHOT jar - spring-boot-dynamodb + spring-data-dynamodb This is simple boot application for Spring boot dynamodb test @@ -154,69 +154,16 @@ org.apache.maven.plugins maven-war-plugin - - org.apache.maven.plugins - maven-dependency-plugin - ${maven-dependency-plugin.version} - - - copy-dependencies - test-compile - - copy-dependencies - - - test - so,dll,dylib - ${project.basedir}/native-libs - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - dynamodb-local DynamoDB Local Release Repository ${dynamodblocal.repository.url} - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - @@ -230,7 +177,6 @@ 1.11.106 1.11.86 https://s3-us-west-2.amazonaws.com/dynamodb-local/release - 2.10 diff --git a/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7f906bdbcd --- /dev/null +++ b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-eclipselink/pom.xml b/persistence-modules/spring-data-eclipselink/pom.xml index 8a55425fc2..618fa83ee5 100644 --- a/persistence-modules/spring-data-eclipselink/pom.xml +++ b/persistence-modules/spring-data-eclipselink/pom.xml @@ -2,9 +2,7 @@ 4.0.0 - com.baeldung spring-data-eclipselink - 1.0.0-SNAPSHOT spring-data-eclipselink @@ -20,7 +18,6 @@ spring-boot-dependencies ${spring.version} pom - import org.springframework.boot diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4be5891e3e --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.eclipselink.springdata.EclipselinkSpringDataApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = EclipselinkSpringDataApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2f0557ccc1 --- /dev/null +++ b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.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 com.baeldung.spring.data.gemfire.function.GemfireConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml index 923d877fd7..2be4df71be 100644 --- a/persistence-modules/spring-data-neo4j/pom.xml +++ b/persistence-modules/spring-data-neo4j/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-data-neo4j 1.0 @@ -37,18 +36,6 @@ org.springframework.data spring-data-neo4j ${spring-data-neo4j.version} - - - commons-logging - commons-logging - - - - - org.springframework.data - spring-data-neo4j - ${spring-data-neo4j.version} - test-jar com.voodoodyne.jackson.jsog @@ -96,23 +83,17 @@ org.springframework spring-test ${spring-test.version} - - - commons-logging - commons-logging - - - 1.1.1 - 3.1.0 - 4.1.6.RELEASE + 1.6.2 + 3.4.6 + 5.0.1.RELEASE 1.1 - 1.5.13.RELEASE - 4.3.17.RELEASE - 2.1.1 + 2.0.1.RELEASE + 5.0.1.RELEASE + 3.1.2 diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java index 344282d665..9bbc571aee 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java @@ -1,5 +1,6 @@ package com.baeldung.spring.data.neo4j.config; +import org.neo4j.ogm.config.Configuration.Builder; import org.neo4j.ogm.session.SessionFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -8,15 +9,14 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; @ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration -@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") +@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repository") public class MovieDatabaseNeo4jConfiguration { public static final String URL = System.getenv("NEO4J_URL") != null ? System.getenv("NEO4J_URL") : "http://neo4j:movies@localhost:7474"; @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { - org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver").setURI(URL); + org.neo4j.ogm.config.Configuration config = new Builder().uri(URL).build(); return config; } diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java index fda478e5be..a4cbe4b809 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java @@ -1,26 +1,25 @@ package com.baeldung.spring.data.neo4j.config; +import org.neo4j.ogm.config.Configuration.Builder; import org.neo4j.ogm.session.SessionFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; -import org.springframework.data.neo4j.config.Neo4jConfiguration; import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; +import org.springframework.data.neo4j.transaction.Neo4jTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) -@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") +@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repository") @Profile({ "embedded", "test" }) -public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { +public class MovieDatabaseNeo4jTestConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { - final org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config.driverConfiguration() - .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); + org.neo4j.ogm.config.Configuration config = new Builder().build(); return config; } @@ -28,5 +27,10 @@ public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { public SessionFactory getSessionFactory() { return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain"); } + + @Bean + public Neo4jTransactionManager transactionManager() { + return new Neo4jTransactionManager(getSessionFactory()); + } } diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java index f2325a334f..455407a92b 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Car.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.neo4j.domain; -import org.neo4j.ogm.annotation.GraphId; +import org.neo4j.ogm.annotation.GeneratedValue; +import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; @NodeEntity public class Car { - @GraphId + @Id @GeneratedValue private Long id; private String make; diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java index 029754c0fc..996a661b07 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java @@ -2,7 +2,9 @@ package com.baeldung.spring.data.neo4j.domain; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; -import org.neo4j.ogm.annotation.GraphId; + +import org.neo4j.ogm.annotation.GeneratedValue; +import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; @@ -13,7 +15,7 @@ import java.util.List; @NodeEntity public class Movie { - @GraphId + @Id @GeneratedValue Long id; private String title; diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java index dc5a850f29..453ca1c3f3 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java @@ -2,7 +2,9 @@ package com.baeldung.spring.data.neo4j.domain; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; -import org.neo4j.ogm.annotation.GraphId; + +import org.neo4j.ogm.annotation.GeneratedValue; +import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; @@ -11,7 +13,7 @@ import java.util.List; @JsonIdentityInfo(generator = JSOGGenerator.class) @NodeEntity public class Person { - @GraphId + @Id @GeneratedValue Long id; private String name; diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java index 40dabb054b..5a18837dae 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java @@ -3,7 +3,8 @@ package com.baeldung.spring.data.neo4j.domain; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; import org.neo4j.ogm.annotation.EndNode; -import org.neo4j.ogm.annotation.GraphId; +import org.neo4j.ogm.annotation.GeneratedValue; +import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.RelationshipEntity; import org.neo4j.ogm.annotation.StartNode; @@ -12,8 +13,8 @@ import java.util.Collection; @JsonIdentityInfo(generator = JSOGGenerator.class) @RelationshipEntity(type = "ACTED_IN") public class Role { - @GraphId - Long id; + @Id @GeneratedValue + Long id; private Collection roles; @StartNode private Person person; diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java similarity index 78% rename from persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java rename to persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java index afb82551e7..dde946ea73 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/MovieRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.spring.data.neo4j.repostory; +package com.baeldung.spring.data.neo4j.repository; import com.baeldung.spring.data.neo4j.domain.Movie; import org.springframework.data.neo4j.annotation.Query; -import org.springframework.data.neo4j.repository.GraphRepository; +import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @@ -11,7 +11,7 @@ import java.util.List; import java.util.Map; @Repository -public interface MovieRepository extends GraphRepository { +public interface MovieRepository extends Neo4jRepository { Movie findByTitle(@Param("title") String title); diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java new file mode 100644 index 0000000000..22094d26b6 --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repository/PersonRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.data.neo4j.repository; + +import com.baeldung.spring.data.neo4j.domain.Person; +import org.springframework.data.neo4j.repository.Neo4jRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PersonRepository extends Neo4jRepository { +} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java deleted file mode 100644 index 4ac40ef75b..0000000000 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.spring.data.neo4j.repostory; - -import com.baeldung.spring.data.neo4j.domain.Person; -import org.springframework.data.neo4j.repository.GraphRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface PersonRepository extends GraphRepository { -} diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java index ae1f6eb8e5..086bf48bfa 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java @@ -1,10 +1,11 @@ package com.baeldung.spring.data.neo4j.services; -import com.baeldung.spring.data.neo4j.repostory.MovieRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import com.baeldung.spring.data.neo4j.repository.MovieRepository; + import java.util.*; @Service diff --git a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java index 06b31667dd..96e5e76402 100644 --- a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java +++ b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/neo4j/Neo4jOgmLiveTest.java @@ -12,14 +12,12 @@ import org.neo4j.ogm.session.SessionFactory; import com.baeldung.spring.data.neo4j.domain.Car; import com.baeldung.spring.data.neo4j.domain.Company; -import org.neo4j.ogm.transaction.Transaction; public class Neo4jOgmLiveTest { @Test public void testOgm() { - Configuration conf = new Configuration(); - conf.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); + Configuration conf = new Configuration.Builder().build(); SessionFactory factory = new SessionFactory(conf, "com.baeldung.spring.data.neo4j.domain"); Session session = factory.openSession(); diff --git a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java index 95bc38aafc..3d9215f32f 100644 --- a/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java @@ -4,8 +4,9 @@ import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration import com.baeldung.spring.data.neo4j.domain.Movie; import com.baeldung.spring.data.neo4j.domain.Person; import com.baeldung.spring.data.neo4j.domain.Role; -import com.baeldung.spring.data.neo4j.repostory.MovieRepository; -import com.baeldung.spring.data.neo4j.repostory.PersonRepository; +import com.baeldung.spring.data.neo4j.repository.MovieRepository; +import com.baeldung.spring.data.neo4j.repository.PersonRepository; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -50,10 +51,10 @@ public class MovieRepositoryIntegrationTest { Role charlie = new Role(); charlie.setMovie(italianJob); charlie.setPerson(mark); - Collection roleNames = new HashSet(); + Collection roleNames = new HashSet<>(); roleNames.add("Charlie Croker"); charlie.setRoles(roleNames); - List roles = new ArrayList(); + List roles = new ArrayList<>(); roles.add(charlie); italianJob.setRoles(roles); movieRepository.save(italianJob); diff --git a/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ea32ed324b --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class) +@ActiveProfiles(profiles = "test") +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 5981bf41e0..bee3d683b8 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -7,17 +7,61 @@ jar + parent-boot-2 com.baeldung - parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-5 + ../../parent-boot-2 - org.springframework.data - spring-data-redis - ${spring-data-redis} + org.springframework.boot + spring-boot-starter-data-redis-reactive + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + + + io.projectreactor + reactor-test + test + + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test @@ -33,42 +77,12 @@ jar - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - - - - - org.springframework - spring-context - ${spring.version} - - - - org.springframework - spring-test - ${spring.version} - test - - com.lordofthejars nosqlunit-redis ${nosqlunit.version} - - org.springframework.data - spring-data-commons - ${spring-data-commons.version} - com.github.kstyrc embedded-redis @@ -77,12 +91,13 @@ - 2.0.3.RELEASE 3.2.4 2.9.0 0.10.0 2.0.3.RELEASE 0.6 + 1.0.0 + 5.0.2 diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java new file mode 100644 index 0000000000..8b1f892f67 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.data.reactive.redis; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringRedisReactiveApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringRedisReactiveApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java new file mode 100644 index 0000000000..d23d0092eb --- /dev/null +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.data.reactive.redis.config; + + +import com.baeldung.spring.data.reactive.redis.model.Employee; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.ReactiveKeyCommands; +import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; +import org.springframework.data.redis.connection.ReactiveStringCommands; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import javax.annotation.PreDestroy; + +@Configuration +public class RedisConfig { + + @Autowired + RedisConnectionFactory factory; + + @Bean + public ReactiveRedisTemplate reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) { + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(Employee.class); + RedisSerializationContext.RedisSerializationContextBuilder builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer()); + RedisSerializationContext context = builder.value(serializer) + .build(); + return new ReactiveRedisTemplate<>(factory, context); + } + + @Bean + public ReactiveRedisTemplate reactiveRedisTemplateString(ReactiveRedisConnectionFactory connectionFactory) { + return new ReactiveRedisTemplate<>(connectionFactory, RedisSerializationContext.string()); + } + + @Bean + public ReactiveKeyCommands keyCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) { + return reactiveRedisConnectionFactory.getReactiveConnection() + .keyCommands(); + } + + @Bean + public ReactiveStringCommands stringCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) { + return reactiveRedisConnectionFactory.getReactiveConnection() + .stringCommands(); + } + + @PreDestroy + public void cleanRedis() { + factory.getConnection() + .flushDb(); + } +} diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java new file mode 100644 index 0000000000..9178f6e112 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.data.reactive.redis.model; + +import java.io.Serializable; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Data +@ToString +@AllArgsConstructor +@NoArgsConstructor +@EqualsAndHashCode +public class Employee implements Serializable { + private static final long serialVersionUID = 1603714798906422731L; + private String id; + private String name; + private String department; +} diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java index 62a7886f46..6fdb3c5bef 100644 --- a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java @@ -1,6 +1,8 @@ package com.baeldung.spring.data.redis.config; -import org.springframework.beans.factory.annotation.Value; +import com.baeldung.spring.data.redis.queue.MessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -13,10 +15,6 @@ import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; import org.springframework.data.redis.serializer.GenericToStringSerializer; -import com.baeldung.spring.data.redis.queue.MessagePublisher; -import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; -import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; - @Configuration @ComponentScan("com.baeldung.spring.data.redis") @EnableRedisRepositories(basePackages = "com.baeldung.spring.data.redis.repo") diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java new file mode 100644 index 0000000000..e48aa1e06a --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java @@ -0,0 +1,51 @@ +package com.baeldung.spring.data.reactive.redis.template; + + +import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; +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.redis.connection.ReactiveKeyCommands; +import org.springframework.data.redis.connection.ReactiveStringCommands; +import org.springframework.data.redis.connection.ReactiveStringCommands.SetCommand; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.nio.ByteBuffer; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +public class RedisKeyCommandsIntegrationTest { + + @Autowired + private ReactiveKeyCommands keyCommands; + + @Autowired + private ReactiveStringCommands stringCommands; + + @Test + public void givenFluxOfKeys_whenPerformOperations_thenPerformOperations() { + Flux keys = Flux.just("key1", "key2", "key3", "key4"); + + Flux generator = keys.map(String::getBytes) + .map(ByteBuffer::wrap) + .map(key -> SetCommand.set(key) + .value(key)); + + StepVerifier.create(stringCommands.set(generator)) + .expectNextCount(4L) + .verifyComplete(); + + Mono keyCount = keyCommands.keys(ByteBuffer.wrap("key*".getBytes())) + .flatMapMany(Flux::fromIterable) + .count(); + + StepVerifier.create(keyCount) + .expectNext(4L) + .verifyComplete(); + + } +} diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java new file mode 100644 index 0000000000..3ebeff87b1 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java @@ -0,0 +1,49 @@ +package com.baeldung.spring.data.reactive.redis.template; + + +import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.redis.core.ReactiveListOperations; +import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +public class RedisTemplateListOpsIntegrationTest { + + private static final String LIST_NAME = "demo_list"; + + @Autowired + private ReactiveRedisTemplate redisTemplate; + + private ReactiveListOperations reactiveListOps; + + @Before + public void setup() { + reactiveListOps = redisTemplate.opsForList(); + } + + @Test + public void givenListAndValues_whenLeftPushAndLeftPop_thenLeftPushAndLeftPop() { + Mono lPush = reactiveListOps.leftPushAll(LIST_NAME, "first", "second") + .log("Pushed"); + + StepVerifier.create(lPush) + .expectNext(2L) + .verifyComplete(); + + Mono lPop = reactiveListOps.leftPop(LIST_NAME) + .log("Popped"); + + StepVerifier.create(lPop) + .expectNext("second") + .verifyComplete(); + } + +} diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java new file mode 100644 index 0000000000..9490568089 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java @@ -0,0 +1,71 @@ +package com.baeldung.spring.data.reactive.redis.template; + + +import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; +import com.baeldung.spring.data.reactive.redis.model.Employee; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.data.redis.core.ReactiveValueOperations; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.time.Duration; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +public class RedisTemplateValueOpsIntegrationTest { + + @Autowired + private ReactiveRedisTemplate redisTemplate; + + private ReactiveValueOperations reactiveValueOps; + + @Before + public void setup() { + reactiveValueOps = redisTemplate.opsForValue(); + } + + @Test + public void givenEmployee_whenSet_thenSet() { + + Mono result = reactiveValueOps.set("123", new Employee("123", "Bill", "Accounts")); + + StepVerifier.create(result) + .expectNext(true) + .verifyComplete(); + } + + @Test + public void givenEmployeeId_whenGet_thenReturnsEmployee() { + + Mono fetchedEmployee = reactiveValueOps.get("123"); + + StepVerifier.create(fetchedEmployee) + .expectNext(new Employee("123", "Bill", "Accounts")) + .verifyComplete(); + } + + @Test + public void givenEmployee_whenSetWithExpiry_thenSetsWithExpiryTime() throws InterruptedException { + + Mono result = reactiveValueOps.set("129", new Employee("129", "John", "Programming"), Duration.ofSeconds(1)); + + Mono fetchedEmployee = reactiveValueOps.get("129"); + + StepVerifier.create(result) + .expectNext(true) + .verifyComplete(); + + Thread.sleep(2000L); + + StepVerifier.create(fetchedEmployee) + .expectNextCount(0L) + .verifyComplete(); + } + +} diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java index 5bc70069c5..99febb6430 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java @@ -31,7 +31,7 @@ public class RedisMessageListenerIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new redis.embedded.RedisServer(6379); + redisServer = new redis.embedded.RedisServer(6380); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java index 48832a8de9..43aadefc01 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java @@ -32,7 +32,7 @@ public class StudentRepositoryIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new redis.embedded.RedisServer(6379); + redisServer = new redis.embedded.RedisServer(6380); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e093892365 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +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.spring.data.redis.config.RedisConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RedisConfig.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e76967ae8a --- /dev/null +++ b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +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.spring.data.solr.config.SolrConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SolrConfig.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a81a4eedb1 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.PersistenceConfig; +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; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index d48723ac31..b4d73708c3 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -3,3 +3,4 @@ - [Guide to @Immutable Annotation in Hibernate](http://www.baeldung.com/hibernate-immutable) - [Hibernate Many to Many Annotation Tutorial](http://www.baeldung.com/hibernate-many-to-many) - [Programmatic Transactions in the Spring TestContext Framework](http://www.baeldung.com/spring-test-programmatic-transactions) +- [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/model/Item.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/model/Item.java new file mode 100644 index 0000000000..957207b7e6 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/model/Item.java @@ -0,0 +1,81 @@ +package com.baeldung.hibernate.criteria.model; + +import java.io.Serializable; + +public class Item implements Serializable { + + private static final long serialVersionUID = 1L; + private Integer itemId; + private String itemName; + private String itemDescription; + private Integer itemPrice; + + // constructors + public Item() { + + } + + public Item(final Integer itemId, final String itemName, final String itemDescription) { + super(); + this.itemId = itemId; + this.itemName = itemName; + this.itemDescription = itemDescription; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((itemId == null) ? 0 : itemId.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 Item other = (Item) obj; + if (itemId == null) { + if (other.itemId != null) + return false; + } else if (!itemId.equals(other.itemId)) + return false; + return true; + } + + public Integer getItemId() { + return itemId; + } + + public void setItemId(final Integer itemId) { + this.itemId = itemId; + } + + public String getItemName() { + return itemName; + } + + public void setItemName(final String itemName) { + this.itemName = itemName; + } + + public String getItemDescription() { + return itemDescription; + } + + public Integer getItemPrice() { + return itemPrice; + } + + public void setItemPrice(final Integer itemPrice) { + this.itemPrice = itemPrice; + } + + public void setItemDescription(final String itemDescription) { + this.itemDescription = itemDescription; + } +} diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java similarity index 100% rename from spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java new file mode 100644 index 0000000000..72d4dea377 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java @@ -0,0 +1,335 @@ +/** + * ApplicationViewer is the class that starts the application + * First it creates the session object and then creates the + * criteria query. + * + * @author Pritam Banerjee + * @version 1.0 + * @since 07/20/2016 + */ + +package com.baeldung.hibernate.criteria.view; + +import java.util.List; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import org.hibernate.Session; +import org.hibernate.query.Query; + +import com.baeldung.hibernate.criteria.model.Item; +import com.baeldung.hibernate.criteria.util.HibernateUtil; + +public class ApplicationView { + + // default Constructor + public ApplicationView() { + + } + + public boolean checkIfCriteriaTimeLower() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + + // calculate the time taken by criteria + final long startTimeCriteria = System.nanoTime(); + cr.select(root) + .where(cb.like(root.get("itemName"), "%item One%")); + // .add(Restrictions.like("itemName", "%item One%")); + Query query = session.createQuery(cr); + + final List results = query.getResultList(); + final long endTimeCriteria = System.nanoTime(); + final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; + + // calculate the time taken by HQL + final long startTimeHQL = System.nanoTime(); + session.beginTransaction(); + final List items = session.createQuery("FROM Item where itemName like '%item One%'") + .list(); + final long endTimeHQL = System.nanoTime(); + final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; + + if (durationCriteria > durationHQL) { + return false; + } else { + return true; + } + } + + // To get items having price more than 1000 + public String[] greaterThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.gt(root.get("itemPrice"), 1000)); + // cr.add(Restrictions.gt("itemPrice", 1000)); + Query query = session.createQuery(cr); + final List greaterThanItemsList = query.getResultList(); + final String greaterThanItems[] = new String[greaterThanItemsList.size()]; + for (int i = 0; i < greaterThanItemsList.size(); i++) { + greaterThanItems[i] = greaterThanItemsList.get(i) + .getItemName(); + } + session.close(); + return greaterThanItems; + } + + // To get items having price less than 1000 + public String[] lessThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.lt(root.get("itemPrice"), 1000)); + // cr.add(Restrictions.lt("itemPrice", 1000)); + Query query = session.createQuery(cr); + final List lessThanItemsList = query.getResultList(); + final String lessThanItems[] = new String[lessThanItemsList.size()]; + for (int i = 0; i < lessThanItemsList.size(); i++) { + lessThanItems[i] = lessThanItemsList.get(i) + .getItemName(); + } + session.close(); + return lessThanItems; + } + + // To get items whose Name start with Chair + public String[] likeCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.like(root.get("itemName"), "%chair%")); + // cr.add(Restrictions.like("itemName", "%chair%")); + Query query = session.createQuery(cr); + final List likeItemsList = query.getResultList(); + final String likeItems[] = new String[likeItemsList.size()]; + for (int i = 0; i < likeItemsList.size(); i++) { + likeItems[i] = likeItemsList.get(i) + .getItemName(); + } + session.close(); + return likeItems; + } + + // Case sensitive search + public String[] likeCaseCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.like(cb.lower(root.get("itemName")), "%chair%")); + // cr.add(Restrictions.ilike("itemName", "%Chair%")); + Query query = session.createQuery(cr); + final List ilikeItemsList = query.getResultList(); + final String ilikeItems[] = new String[ilikeItemsList.size()]; + for (int i = 0; i < ilikeItemsList.size(); i++) { + ilikeItems[i] = ilikeItemsList.get(i) + .getItemName(); + } + session.close(); + return ilikeItems; + } + + // To get records having itemPrice in between 100 and 200 + public String[] betweenCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.between(root.get("itemPrice"), 100, 200)); + // cr.add(Restrictions.between("itemPrice", 100, 200)); + Query query = session.createQuery(cr); + final List betweenItemsList = query.getResultList(); + final String betweenItems[] = new String[betweenItemsList.size()]; + for (int i = 0; i < betweenItemsList.size(); i++) { + betweenItems[i] = betweenItemsList.get(i) + .getItemName(); + } + session.close(); + return betweenItems; + } + + // To check if the given property is null + public String[] nullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.isNull(root.get("itemDescription"))); + // cr.add(Restrictions.isNull("itemDescription")); + Query query = session.createQuery(cr); + final List nullItemsList = query.getResultList(); + final String nullDescItems[] = new String[nullItemsList.size()]; + for (int i = 0; i < nullItemsList.size(); i++) { + nullDescItems[i] = nullItemsList.get(i) + .getItemName(); + } + session.close(); + return nullDescItems; + } + + // To check if the given property is not null + public String[] notNullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(cb.isNotNull(root.get("itemDescription"))); + // cr.add(Restrictions.isNotNull("itemDescription")); + Query query = session.createQuery(cr); + final List notNullItemsList = query.getResultList(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i) + .getItemName(); + } + session.close(); + return notNullDescItems; + } + + // Adding more than one expression in one cr + public String[] twoCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + Predicate[] predicates = new Predicate[2]; + predicates[0] = cb.isNull(root.get("itemDescription")); + predicates[1] = cb.like(root.get("itemName"), "chair%"); + cr.select(root) + .where(predicates); + // cr.add(Restrictions.isNull("itemDescription")); + // cr.add(Restrictions.like("itemName", "chair%")); + Query query = session.createQuery(cr); + final List notNullItemsList = query.getResultList(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i) + .getItemName(); + } + session.close(); + return notNullDescItems; + } + + // To get items matching with the above defined conditions joined + // with Logical AND + public String[] andLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + Predicate greaterThanPrice = cb.gt(root.get("itemPrice"), 1000); + Predicate chairItems = cb.like(root.get("itemName"), "Chair%"); + cr.select(root) + .where(cb.and(greaterThanPrice, chairItems)); + // final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + // final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + // final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); + // cr.add(andExample); + Query query = session.createQuery(cr); + final List andItemsList = query.getResultList(); + final String andItems[] = new String[andItemsList.size()]; + for (int i = 0; i < andItemsList.size(); i++) { + andItems[i] = andItemsList.get(i) + .getItemName(); + } + session.close(); + return andItems; + } + + // To get items matching with the above defined conditions joined + // with Logical OR + public String[] orLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + Predicate greaterThanPrice = cb.gt(root.get("itemPrice"), 1000); + Predicate chairItems = cb.like(root.get("itemName"), "Chair%"); + cr.select(root) + .where(cb.or(greaterThanPrice, chairItems)); + Query query = session.createQuery(cr); + final List orItemsList = query.getResultList(); + final String orItems[] = new String[orItemsList.size()]; + for (int i = 0; i < orItemsList.size(); i++) { + orItems[i] = orItemsList.get(i) + .getItemName(); + } + session.close(); + return orItems; + } + + // Sorting example + public String[] sortingCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root); + cr.orderBy(cb.asc(root.get("itemName")), cb.desc(root.get("itemPrice"))); + // cr.addOrder(Order.asc("itemName")); + // cr.addOrder(Order.desc("itemPrice")).list(); + Query query = session.createQuery(cr); + final List sortedItemsList = query.getResultList(); + final String sortedItems[] = new String[sortedItemsList.size()]; + for (int i = 0; i < sortedItemsList.size(); i++) { + sortedItems[i] = sortedItemsList.get(i) + .getItemName(); + } + session.close(); + return sortedItems; + } + + // Set projections Row Count + public Long[] projectionRowCount() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Long.class); + final Root root = cr.from(Item.class); + cr.select(cb.count(root)); + Query query = session.createQuery(cr); + final List itemProjected = query.getResultList(); + // session.createCriteria(Item.class).setProjection(Projections.rowCount()).list(); + final Long projectedRowCount[] = new Long[itemProjected.size()]; + for (int i = 0; i < itemProjected.size(); i++) { + projectedRowCount[i] = itemProjected.get(i); + } + session.close(); + return projectedRowCount; + } + + // Set projections average of itemPrice + public Double[] projectionAverage() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Double.class); + final Root root = cr.from(Item.class); + cr.select(cb.avg(root.get("itemPrice"))); + Query query = session.createQuery(cr); + final List avgItemPriceList = query.getResultList(); + // session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + + final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; + for (int i = 0; i < avgItemPriceList.size(); i++) { + avgItemPrice[i] = (Double) avgItemPriceList.get(i); + } + session.close(); + return avgItemPrice; + } + +} diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/import.sql b/persistence-modules/spring-hibernate-5/src/main/resources/import.sql new file mode 100644 index 0000000000..ae008f29bc --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/resources/import.sql @@ -0,0 +1,31 @@ +insert into item (item_id, item_name, item_desc, item_price) +values(1,'item One', 'test 1', 35.12); + +insert into item (item_id, item_name, item_desc, item_price) +values(2,'Pogo stick', 'Pogo stick', 466.12); +insert into item (item_id, item_name, item_desc, item_price) +values(3,'Raft', 'Raft', 345.12); + +insert into item (item_id, item_name, item_desc, item_price) +values(4,'Skate Board', 'Skating', 135.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(5,'Umbrella', 'Umbrella for Rain', 619.25); + +insert into item (item_id, item_name, item_desc, item_price) +values(6,'Glue', 'Glue for home', 432.73); + +insert into item (item_id, item_name, item_desc, item_price) +values(7,'Paint', 'Paint for Room', 1311.40); + +insert into item (item_id, item_name, item_desc, item_price) +values(8,'Red paint', 'Red paint for room', 1135.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(9,'Household Chairs', 'Chairs for house', 25.71); + +insert into item (item_id, item_name, item_desc, item_price) +values(10,'Office Chairs', 'Chairs for office', 395.98); + +insert into item (item_id, item_name, item_desc, item_price) +values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36); diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java similarity index 99% rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index 2275bf14f2..723b097305 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -43,7 +43,6 @@ public class HibernateCriteriaIntegrationTest { } session.close(); assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); - } @Test diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java similarity index 100% rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java similarity index 100% rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java diff --git a/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..af4618d0f3 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.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 com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-hibernate4/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml b/persistence-modules/spring-hibernate-5/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml similarity index 100% rename from spring-hibernate4/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml rename to persistence-modules/spring-hibernate-5/src/test/resources/com/baeldung/hibernate/criteria/model/Item.hbm.xml diff --git a/spring-hibernate4/src/test/resources/criteria.cfg.xml b/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml similarity index 85% rename from spring-hibernate4/src/test/resources/criteria.cfg.xml rename to persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml index 726e9acb3f..bc4fed9680 100644 --- a/spring-hibernate4/src/test/resources/criteria.cfg.xml +++ b/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml @@ -10,8 +10,8 @@ sa org.hibernate.dialect.H2Dialect - update - true + create-drop + false \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/import.sql b/persistence-modules/spring-hibernate-5/src/test/resources/import.sql new file mode 100644 index 0000000000..087d62d331 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/resources/import.sql @@ -0,0 +1,21 @@ +insert into item (item_id, item_name, item_desc, item_price) values(1,'item One', 'test 1', 35.12); + +insert into item (item_id, item_name, item_desc, item_price) values(2,'Pogo stick', 'Pogo stick', 466.12); + +insert into item (item_id, item_name, item_desc, item_price) values(3,'Raft', 'Raft', 345.12); + +insert into item (item_id, item_name, item_desc, item_price) values(4,'Skate Board', 'Skating', 135.71); + +insert into item (item_id, item_name, item_desc, item_price) values(5,'Umbrella', 'Umbrella for Rain', 619.25); + +insert into item (item_id, item_name, item_desc, item_price) values(6,'Glue', 'Glue for home', 432.73); + +insert into item (item_id, item_name, item_desc, item_price) values(7,'Paint', 'Paint for Room', 1311.40); + +insert into item (item_id, item_name, item_desc, item_price) values(8,'Red paint', 'Red paint for room', 1135.71); + +insert into item (item_id, item_name, item_desc, item_price) values(9,'Household Chairs', 'Chairs for house', 25.71); + +insert into item (item_id, item_name, item_desc, item_price) values(10,'Office Chairs', 'Chairs for office', 395.98); + +insert into item (item_id, item_name, item_desc, item_price) values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36); diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index 02d4306ecb..299a5a1e51 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -9,20 +9,16 @@ - [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) -- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) - [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) -- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) - [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source) -- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) - [A Guide to Hibernate with Spring 4](http://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) - [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys) - [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring) -- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) -- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) +- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java index 78c4116c67..ec0d4bca3c 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java @@ -78,9 +78,9 @@ public class PersistenceJPAConfig { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false"); + + return hibernateProperties; } diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java index 1c8ce5400f..cf6e69eb39 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java @@ -5,7 +5,7 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class[] getRootConfigClasses() { - return new Class[] { PersistenceJNDIConfig.class }; + return new Class[] { PersistenceJPAConfig.class }; } @Override diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java deleted file mode 100644 index 7e2efc72bc..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.baeldung.extended.persistence.dao; - -import org.baeldung.inmemory.persistence.model.Student; - -public interface ExtendedStudentRepository extends ExtendedRepository { -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepository.java new file mode 100644 index 0000000000..114cf48c7c --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepository.java @@ -0,0 +1,9 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.Book; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface BookRepository extends JpaRepository, BookRepositoryCustom, JpaSpecificationExecutor { + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryCustom.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryCustom.java new file mode 100644 index 0000000000..b939907572 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryCustom.java @@ -0,0 +1,11 @@ +package org.baeldung.persistence.dao; + +import java.util.List; + +import org.baeldung.persistence.model.Book; + +public interface BookRepositoryCustom { + + List findBooksByAuthorNameAndTitle(String authorName, String title); + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryImpl.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryImpl.java new file mode 100644 index 0000000000..6e9aa998d7 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookRepositoryImpl.java @@ -0,0 +1,45 @@ +package org.baeldung.persistence.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import org.baeldung.persistence.model.Book; +import org.springframework.stereotype.Repository; + +@Repository +public class BookRepositoryImpl implements BookRepositoryCustom { + + private EntityManager em; + + public BookRepositoryImpl(EntityManager em) { + this.em = em; + } + + @Override + public List findBooksByAuthorNameAndTitle(String authorName, String title) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Book.class); + + Root book = cq.from(Book.class); + List predicates = new ArrayList<>(); + + if (authorName != null) { + predicates.add(cb.equal(book.get("author"), authorName)); + } + if (title != null) { + predicates.add(cb.like(book.get("title"), "%" + title + "%")); + } + cq.where(predicates.toArray(new Predicate[0])); + + TypedQuery query = em.createQuery(cq); + return query.getResultList(); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookService.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookService.java new file mode 100644 index 0000000000..88b769e9bf --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookService.java @@ -0,0 +1,25 @@ +package org.baeldung.persistence.dao; + +import static org.baeldung.persistence.dao.BookSpecifications.hasAuthor; +import static org.baeldung.persistence.dao.BookSpecifications.titleContains; +import static org.springframework.data.jpa.domain.Specifications.where; + +import java.util.List; + +import org.baeldung.persistence.model.Book; +import org.springframework.stereotype.Service; + +@Service +public class BookService { + + private BookRepository bookRepository; + + public BookService(BookRepository bookRepository) { + this.bookRepository = bookRepository; + } + + public List query(String author, String title) { + return bookRepository.findAll(where(hasAuthor(author)).and(titleContains(title))); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookSpecifications.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookSpecifications.java new file mode 100644 index 0000000000..ed9540060d --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/BookSpecifications.java @@ -0,0 +1,16 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.Book; +import org.springframework.data.jpa.domain.Specification; + +public class BookSpecifications { + + public static Specification hasAuthor(String author) { + return (book, cq, cb) -> cb.equal(book.get("author"), author); + } + + public static Specification titleContains(String title) { + return (book, cq, cb) -> cb.like(book.get("title"), "%" + title + "%"); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Book.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Book.java new file mode 100644 index 0000000000..754bd179d1 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Book.java @@ -0,0 +1,36 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Book { + + @Id + private Long id; + + private String title; + + private String author; + + public Long getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java deleted file mode 100644 index f84a10cf76..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/User.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.baeldung.persistence.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "users") -public class User { - - @Id - @GeneratedValue - private Integer id; - private String name; - private Integer status; - - public User() { - } - - public User(String name, Integer status) { - this.name = name; - this.status = status; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java deleted file mode 100644 index e250a291bc..0000000000 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.persistence.multiple.dao.user; - -import org.baeldung.persistence.multiple.model.user.User; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface UserRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java index 079888155e..7aff5f51d0 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java @@ -1,10 +1,6 @@ package org.baeldung.persistence.multiple.model.user; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import javax.persistence.*; @Entity @Table(schema = "spring_jpa_user") diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java index 61904198f5..6fb9de4a47 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java @@ -1,15 +1,8 @@ package org.baeldung.persistence.multiple.model.user; +import javax.persistence.*; import java.util.List; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; - @Entity @Table(schema = "spring_jpa_user") public class User { diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence.xml b/persistence-modules/spring-jpa/src/main/resources/persistence.xml index 65bad29cdc..6304fa0a65 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence.xml +++ b/persistence-modules/spring-jpa/src/main/resources/persistence.xml @@ -21,8 +21,6 @@ ${hibernate.hbm2ddl.auto} ${hibernate.dialect} - ${hibernate.cache.use_second_level_cache} - ${hibernate.cache.use_query_cache} diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java index aa2dfb5293..beaa51f5f9 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java @@ -8,7 +8,6 @@ import org.junit.runners.Suite; FooPaginationPersistenceIntegrationTest.class ,FooServicePersistenceIntegrationTest.class ,FooServiceSortingIntegrationTest.class - ,JpaMultipleDBIntegrationTest.class ,FooServiceSortingWitNullsManualIntegrationTest.class }) // @formatter:on public class PersistenceTestSuite { diff --git a/pom.xml b/pom.xml index 1be2bb6120..b5fcc5f3ca 100644 --- a/pom.xml +++ b/pom.xml @@ -43,9 +43,15 @@ org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + org.hamcrest hamcrest-core @@ -70,6 +76,14 @@ ${mockito.version} test + + org.apache.maven.surefire + surefire-logger-api + ${maven-surefire-plugin.version} + + test + true + @@ -98,6 +112,23 @@ **/*LiveTest.java
    + + + org.junit.platform + junit-platform-surefire-provider + ${junit-platform.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + + org.apache.maven.plugins @@ -187,6 +218,10 @@ + + maven-war-plugin + ${maven-war-plugin.version} + @@ -255,7 +290,7 @@ - default + default-first @@ -286,6 +321,7 @@ parent-spring-4 parent-spring-5 parent-java + parent-kotlin asm atomix apache-cayenne @@ -296,6 +332,7 @@ annotations apache-cxf apache-fop + apache-geode apache-poi apache-tika apache-thrift @@ -307,21 +344,26 @@ azure bootique cdi + java-strings core-java core-java-collections core-java-io core-java-8 + java-streams core-java-persistence core-kotlin + kotlin-libraries core-groovy core-scala core-java-concurrency + core-java-concurrency-collections couchbase deltaspike dozer ethereum ejb + ejb/ejb-client feign flips testing-modules/gatling @@ -358,17 +400,18 @@ javafx jgroups jee-7 - jhipster/jhipster-monolithic + jee-7-security + jhipster jjwt - jpa-storedprocedure jsf json-path json jsoup testing-modules/junit-5 - jws + libraries libraries-data + libraries-security libraries-server linkrest logging-modules/log-mdc @@ -400,13 +443,18 @@ testing-modules/rest-testing resteasy rxjava + rxjava-2 spring-swagger-codegen testing-modules/selenium-junit-testng persistence-modules/solr spark-java spring-4 spring-5 + spring-5-data-reactive spring-5-reactive + spring-data-5-reactive/spring-5-data-reactive-redis + spring-5-reactive-security + spring-5-reactive-client spring-5-mvc spring-5-security spring-activiti @@ -418,20 +466,24 @@ spring-batch spring-bom spring-boot + spring-boot-client spring-boot-keycloak spring-boot-bootstrap spring-boot-admin + spring-boot-camel spring-boot-ops spring-boot-persistence spring-boot-security spring-boot-mvc - spring-boot-vue + spring-boot-vue spring-boot-logging-log4j2 spring-cloud-data-flow spring-cloud + spring-cloud-bus spring-core spring-cucumber spring-ejb + spring-ejb/spring-ejb-client spring-aop persistence-modules/spring-data-cassandra spring-data-couchbase-2 @@ -474,9 +526,318 @@ spring-rest-angular spring-rest-full spring-rest-query-language + + + spring-resttemplate + + + + + + default-second + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + + + + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-thymeleaf + spring-userservice + spring-zuul + spring-remoting + spring-reactor + spring-vertx + spring-jinq + spring-rest-embedded-tomcat + testing-modules/testing + testing-modules/testng + video-tutorials + xml + xmlunit-2 + struts-2 + apache-velocity + apache-solrj + rabbitmq + vertx + persistence-modules/spring-data-gemfire + mybatis + spring-drools + drools + persistence-modules/liquibase + spring-boot-property-exp + testing-modules/mockserver + testing-modules/test-containers + undertow + vaadin + vertx-and-rxjava + saas + deeplearning4j + lucene + vraptor + persistence-modules/java-cockroachdb + spring-security-thymeleaf + persistence-modules/java-jdbi + jersey + java-spi + performance-tests + twilio + spring-boot-ctx-fluent + java-ee-8-security-api + spring-webflux-amqp + antlr + maven-archetype + optaplanner + apache-meecrowave + spring-reactive-kotlin + jnosql + spring-boot-angular-ecommerce + cdi-portable-extension + jta + + java-websocket + activejdbc + animal-sniffer-mvn-plugin + apache-avro + apache-bval + apache-shiro + apache-spark + asciidoctor + checker-plugin + + + core-java-sun + custom-pmd + dagger + data-structures + dubbo + flyway + + + jni + jooby + + + + ratpack + rest-with-spark-java + spring-boot-autoconfiguration + spring-boot-custom-starter + spring-boot-jasypt + spring-custom-aop + spring-data-rest-querydsl + spring-groovy + spring-mobile + spring-mustache + spring-mvc-simple + spring-mybatis + spring-rest-hal-browser + spring-rest-shell + spring-rest-template + spring-roo + spring-security-stormpath + sse-jaxrs + static-analysis + stripe + + Twitter4J + wicket + xstream + cas/cas-secured-app + cas/cas-server + + + + + + + + + + + + + + + + + spring-boot-custom-starter/greeter + spring-boot-h2/spring-boot-h2-database + + + + + flyway-cdi-extension + + spring-security-acl + spring-security-cache-control + spring-security-client/spring-security-jsp-authentication + spring-security-client/spring-security-jsp-authorize + spring-security-client/spring-security-jsp-config + spring-security-client/spring-security-mvc + spring-security-client/spring-security-thymeleaf-authentication + spring-security-client/spring-security-thymeleaf-authorize + spring-security-client/spring-security-thymeleaf-config + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-openid + + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-rest + spring-security-sso + spring-security-x509 + + + + + + spring-context + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*SpringContextIntegrationTest.java + + + + + + + + + spring-5 + spring-5-data-reactive + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-security + spring-5-security + spring-activiti + spring-akka + spring-all + spring-aop + spring-apache-camel + spring-batch + spring-bom + spring-boot-admin/spring-boot-admin-client + spring-boot-admin/spring-boot-admin-server + spring-boot-bootstrap + spring-boot-bootstrap + spring-boot-camel + spring-boot-client + spring-boot-custom-starter + greeter-spring-boot-autoconfigure + greeter-spring-boot-sample-app + spring-boot-h2/spring-boot-h2-database + spring-boot-jasypt + spring-boot-keycloak + spring-boot-mvc + spring-boot-property-exp/property-exp-custom-config + spring-boot-property-exp/property-exp-default-config + spring-boot-vue + spring-cloud + spring-cloud/spring-cloud-archaius/basic-config + spring-cloud/spring-cloud-archaius/extra-configs + spring-cloud/spring-cloud-bootstrap/config + spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer + spring-cloud/spring-cloud-contract/spring-cloud-contract-producer + spring-cloud/spring-cloud-gateway + spring-cloud/spring-cloud-kubernetes/demo-backend + spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server + spring-cloud/spring-cloud-ribbon-client + spring-cloud/spring-cloud-security/auth-client + spring-cloud/spring-cloud-security/auth-resource + spring-cloud/spring-cloud-security/auth-server + spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit + spring-cloud/spring-cloud-task/springcloudtasksink + spring-cloud/spring-cloud-zookeeper + spring-cloud/spring-cloud-bus/spring-cloud-config-server + spring-cloud/spring-cloud-data-flow/log-sink + spring-cloud/spring-cloud-data-flow/time-processor + spring-cloud/spring-cloud-data-flow/time-source + spring-cucumber + spring-data-keyvalue + spring-data-rest + spring-dispatcher-servlet + spring-drools + spring-freemarker + spring-hibernate-3 + spring-hibernate4 + spring-integration + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-kafka + spring-katharsis + spring-ldap + spring-mobile + spring-mockito + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-velocity + spring-mvc-webflow + spring-protobuf + spring-quartz + remoting-hessian-burlap/spring-remoting-hessian-burlap-client + remoting-hessian-burlap/remoting-hessian-burlap-server + spring-reactor + spring-remoting/ + spring-remoting/remoting-http/remoting-http-server + spring-remoting/remoting-jms/remoting-jms-client + spring-remoting/remoting-rmi/remoting-rmi-server spring-rest + spring-rest-angular + spring-rest-embedded-tomcat + spring-rest-full spring-rest-simple + spring-resttemplate spring-security-acl + spring-security-angular spring-security-cache-control spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize @@ -490,70 +851,33 @@ spring-security-mvc-custom spring-security-mvc-digest-auth spring-security-mvc-ldap - spring-security-mvc-login spring-security-mvc-persisted-remember-me spring-security-mvc-session spring-security-mvc-socket - spring-security-openid - - spring-security-rest-basic-auth - spring-security-rest-custom spring-security-rest - spring-security-sso - spring-security-x509 - spring-session + spring-security-sso/spring-security-sso-auth-server + spring-security-sso/spring-security-sso-ui + spring-security-sso/spring-security-sso-ui-2 + spring-security-thymeleaf/spring-security-thymeleaf-authentication + spring-security-thymeleaf/spring-security-thymeleaf-authorize + spring-security-thymeleaf/spring-security-thymeleaf-config + spring-security-x509/spring-security-x509-basic-auth + spring-security-x509/spring-security-x509-client-auth + spring-session/spring-session-jdbc spring-sleuth spring-social-login spring-spel spring-state-machine + spring-swagger-codegen/spring-swagger-codegen-app spring-thymeleaf spring-userservice - spring-zuul - spring-reactor + spring-vault spring-vertx - spring-jinq - spring-rest-embedded-tomcat - testing-modules/testing - testing-modules/testng - video-tutorials - xml - xmlunit-2 - struts-2 - apache-velocity - apache-solrj - rabbitmq - vertx - persistence-modules/spring-data-gemfire - mybatis - spring-drools - drools - persistence-modules/liquibase - spring-boot-property-exp - testing-modules/mockserver - testing-modules/test-containers - undertow - vertx-and-rxjava - saas - deeplearning4j - lucene - vraptor - persistence-modules/java-cockroachdb - spring-security-thymeleaf - persistence-modules/java-jdbi - jersey - java-spi - performance-tests - twilio - spring-boot-ctx-fluent - java-ee-8-security-api - spring-webflux-amqp - antlr - maven-archetype - apache-meecrowave - spring-reactive-kotlin - jnosql - sse-jaxrs - spring-boot-angular-ecommerce + spring-zuul/spring-zuul-foos-resource + persistence-modules/spring-data-dynamodb + persistence-modules/spring-data-eclipselink + persistence-modules/spring-data-solr + persistence-modules/spring-hibernate-5 @@ -599,7 +923,7 @@ parent-spring-4 parent-spring-5 parent-java - + parent-kotlin @@ -788,7 +1122,79 @@ - + + java-websocket + activejdbc + animal-sniffer-mvn-plugin + apache-avro + apache-bval + apache-shiro + apache-spark + asciidoctor + checker-plugin + + + core-java-sun + custom-pmd + dagger + data-structures + dubbo + flyway + + + jni + jooby + + + + ratpack + rest-with-spark-java + spring-boot-autoconfiguration + spring-boot-custom-starter + spring-boot-jasypt + spring-custom-aop + spring-data-rest-querydsl + spring-groovy + spring-mobile + spring-mustache + spring-mvc-simple + spring-mybatis + spring-rest-hal-browser + spring-rest-shell + spring-rest-template + spring-roo + spring-security-stormpath + sse-jaxrs + static-analysis + stripe + + + wicket + xstream + cas/cas-secured-app + + + + + + + + + + + + + + jenkins/hello-world + + + + spring-boot-custom-starter/greeter + spring-boot-h2/spring-boot-h2-database + + + + @@ -834,7 +1240,7 @@ parent-spring-4 parent-spring-5 parent-java - + parent-kotlin asm atomix apache-cayenne @@ -856,10 +1262,12 @@ azure bootique cdi + java-strings core-java-collections core-java-io core-java-8 + java-streams core-groovy couchbase @@ -897,12 +1305,13 @@ javafx jgroups jee-7 + jee-7-security jjwt - jpa-storedprocedure jsf json-path json jsoup + jta testing-modules/junit-5 testing-modules/junit5-migration jws @@ -937,12 +1346,16 @@ testing-modules/rest-testing resteasy rxjava + rxjava-2 spring-swagger-codegen testing-modules/selenium-junit-testng persistence-modules/solr spark-java spring-4 + spring-5-data-reactive spring-5-reactive + spring-5-reactive-security + spring-5-reactive-client spring-5-mvc spring-5-security spring-activiti @@ -956,15 +1369,18 @@ spring-boot-keycloak spring-boot-bootstrap spring-boot-admin + spring-boot-camel spring-boot-persistence spring-boot-security spring-boot-mvc spring-boot-logging-log4j2 spring-cloud-data-flow spring-cloud + spring-cloud-bus spring-core spring-cucumber spring-ejb + spring-ejb/spring-ejb-client spring-aop persistence-modules/spring-data-dynamodb @@ -1005,6 +1421,7 @@ spring-rest-full spring-rest-query-language spring-rest + spring-resttemplate spring-rest-simple spring-security-acl spring-security-cache-control @@ -1038,8 +1455,10 @@ spring-thymeleaf spring-userservice spring-zuul + spring-remoting spring-reactor spring-vertx + spring-vault spring-jinq spring-rest-embedded-tomcat testing-modules/testing @@ -1061,6 +1480,7 @@ testing-modules/mockserver testing-modules/test-containers undertow + vaadin vertx-and-rxjava saas deeplearning4j @@ -1160,21 +1580,23 @@ parent-spring-4 parent-spring-5 parent-java - + parent-kotlin libraries geotools - jhipster/jhipster-monolithic + jhipster testing-modules/gatling spring-boot spring-boot-ops spring-5 core-kotlin + kotlin-libraries core-java google-web-toolkit spring-security-mvc-custom hibernate5 spring-data-elasticsearch core-java-concurrency + core-java-concurrency-collections @@ -1202,7 +1624,7 @@ 4.12 1.3 - 2.8.9 + 2.21.0 1.7.21 1.1.7 @@ -1221,7 +1643,7 @@ 2.19.1 2.5 1.4 - 2.6 + 3.0.0 3.1.0 1.2 2.3.1 @@ -1229,7 +1651,8 @@ 1.2 2.5.0 1.3 - 5.0.2 + 1.2.0 + 5.2.0 0.3.1 2.5.1 0.0.1 diff --git a/ratpack/README.md b/ratpack/README.md index 02b91da0bd..dded42fab6 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -4,4 +4,4 @@ - [Ratpack Google Guice Integration](http://www.baeldung.com/ratpack-google-guice) - [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot) - [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix) - +- [Ratpack HTTP Client](https://www.baeldung.com/ratpack-http-client) diff --git a/ratpack/build.gradle b/ratpack/build.gradle index aeddd5f9f9..25af3ddb51 100644 --- a/ratpack/build.gradle +++ b/ratpack/build.gradle @@ -1,35 +1,35 @@ -buildscript { - repositories { - jcenter() - } - dependencies { - classpath "io.ratpack:ratpack-gradle:1.4.5" - classpath "com.h2database:h2:1.4.193" - } -} - -if (!JavaVersion.current().java8Compatible) { - throw new IllegalStateException("Must be built with Java 8 or higher") -} - -apply plugin: "io.ratpack.ratpack-java" -apply plugin: 'java' - -repositories { - jcenter() -} - -dependencies { - compile ratpack.dependency('hikari') - compile 'com.h2database:h2:1.4.193' - testCompile 'junit:junit:4.11' - runtime "org.slf4j:slf4j-simple:1.7.21" -} - -test { - testLogging { - events 'started', 'passed' - } -} - -mainClassName = "com.baeldung.Application" +buildscript { + repositories { + jcenter() + } + dependencies { + classpath "io.ratpack:ratpack-gradle:1.5.4" + classpath "com.h2database:h2:1.4.193" + } +} + +if (!JavaVersion.current().java8Compatible) { + throw new IllegalStateException("Must be built with Java 8 or higher") +} + +apply plugin: "io.ratpack.ratpack-java" +apply plugin: 'java' + +repositories { + jcenter() +} + +dependencies { + compile ratpack.dependency('hikari') + compile 'com.h2database:h2:1.4.193' + testCompile 'junit:junit:4.11' + runtime "org.slf4j:slf4j-simple:1.7.21" +} + +test { + testLogging { + events 'started', 'passed' + } +} + +mainClassName = "com.baeldung.Application" diff --git a/ratpack/pom.xml b/ratpack/pom.xml index bbde3d1cd7..7de11e6955 100644 --- a/ratpack/pom.xml +++ b/ratpack/pom.xml @@ -35,6 +35,17 @@ io.ratpack ratpack-hystrix ${ratpack.version} + + + com.netflix.hystrix + hystrix-core + + + + + com.netflix.hystrix + hystrix-core + ${hystrix.version} io.ratpack @@ -76,10 +87,11 @@ 1.8 1.8 - 1.4.6 + 1.5.4 4.5.3 4.4.6 1.4.193 + 1.5.12 diff --git a/ratpack/src/main/java/com/baeldung/Application.java b/ratpack/src/main/java/com/baeldung/Application.java index 7f46b241ea..4a391d04a1 100644 --- a/ratpack/src/main/java/com/baeldung/Application.java +++ b/ratpack/src/main/java/com/baeldung/Application.java @@ -1,49 +1,81 @@ -package com.baeldung; - -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.filter.RequestValidatorFilter; -import com.baeldung.model.Employee; - -import ratpack.guice.Guice; -import ratpack.hikari.HikariModule; -import ratpack.http.MutableHeaders; -import ratpack.jackson.Jackson; -import ratpack.http.MutableHeaders; -import ratpack.server.RatpackServer; - -public class Application { - - public static void main(String[] args) throws Exception { - - List employees = new ArrayList(); - employees.add(new Employee(1L, "Mr", "John Doe")); - employees.add(new Employee(2L, "Mr", "White Snow")); - - - RatpackServer.start( - server -> server.registry(Guice.registry(bindings -> bindings.module(HikariModule.class, config -> { - config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); - config.addDataSourceProperty("URL", - "jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'"); - }))).handlers(chain -> chain - .all( - // ctx -> { - // MutableHeaders headers = - // ctx.getResponse().getHeaders(); - // headers.set("Access-Control-Allow-Origin","*"); - // headers.set("Accept-Language", "en-us"); - // headers.set("Accept-Charset", "UTF-8"); - // ctx.next(); - // } - new RequestValidatorFilter()) - .get(ctx -> ctx.render("Welcome to baeldung ratpack!!!")) - .get("data/employees", ctx -> ctx.render(Jackson.json(employees))) - .get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens().get("name") + "!!!")) - .post(":amount", ctx -> ctx - .render(" Amount $" + ctx.getPathTokens().get("amount") + " added successfully !!!")))); - } - -} - +package com.baeldung; + +import com.baeldung.filter.RequestValidatorFilter; +import com.baeldung.handler.EmployeeHandler; +import com.baeldung.handler.RedirectHandler; +import com.baeldung.model.Employee; +import com.baeldung.repository.EmployeeRepository; +import com.baeldung.repository.EmployeeRepositoryImpl; +import com.zaxxer.hikari.HikariConfig; +import io.netty.buffer.PooledByteBufAllocator; +import ratpack.func.Action; +import ratpack.func.Function; +import ratpack.guice.BindingsSpec; +import ratpack.guice.Guice; +import ratpack.handling.Chain; +import ratpack.hikari.HikariModule; +import ratpack.http.client.HttpClient; +import ratpack.jackson.Jackson; +import ratpack.registry.Registry; +import ratpack.server.RatpackServer; +import ratpack.server.RatpackServerSpec; +import ratpack.server.ServerConfig; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; + +public class Application { + + public static void main(String[] args) throws Exception { + + final Action hikariConfigAction = hikariConfig -> { + hikariConfig.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); + hikariConfig.addDataSourceProperty("URL", "jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'"); + }; + + final Action bindingsSpecAction = bindings -> bindings.module(HikariModule.class, hikariConfigAction); + final HttpClient httpClient = HttpClient.of(httpClientSpec -> { + httpClientSpec.poolSize(10) + .connectTimeout(Duration.of(60, ChronoUnit.SECONDS)) + .maxContentLength(ServerConfig.DEFAULT_MAX_CONTENT_LENGTH) + .responseMaxChunkSize(16384) + .readTimeout(Duration.of(60, ChronoUnit.SECONDS)) + .byteBufAllocator(PooledByteBufAllocator.DEFAULT); + }); + final Function registryFunction = Guice.registry(bindingsSpecAction); + + final Action chainAction = chain -> chain.all(new RequestValidatorFilter()) + .get(ctx -> ctx.render("Welcome to baeldung ratpack!!!")) + .get("data/employees", ctx -> ctx.render(Jackson.json(createEmpList()))) + .get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens() + .get("name") + "!!!")) + .post(":amount", ctx -> ctx.render(" Amount $" + ctx.getPathTokens() + .get("amount") + " added successfully !!!")); + + final Action routerChainAction = routerChain -> { + routerChain.path("redirect", new RedirectHandler()) + .prefix("employee", empChain -> { + empChain.get(":id", new EmployeeHandler()); + }); + }; + final Action ratpackServerSpecAction = serverSpec -> serverSpec.registry(registryFunction) + .registryOf(registrySpec -> { + registrySpec.add(EmployeeRepository.class, new EmployeeRepositoryImpl()); + registrySpec.add(HttpClient.class, httpClient); + }) + .handlers(chain -> chain.insert(routerChainAction) + .insert(chainAction)); + + RatpackServer.start(ratpackServerSpecAction); + } + + private static List createEmpList() { + List employees = new ArrayList<>(); + employees.add(new Employee(1L, "Mr", "John Doe")); + employees.add(new Employee(2L, "Mr", "White Snow")); + return employees; + } + +} diff --git a/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java b/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java new file mode 100644 index 0000000000..9a6b79259c --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/handler/EmployeeHandler.java @@ -0,0 +1,20 @@ +package com.baeldung.handler; + +import com.baeldung.repository.EmployeeRepository; +import com.baeldung.model.Employee; +import ratpack.exec.Promise; +import ratpack.handling.Context; +import ratpack.handling.Handler; + +public class EmployeeHandler implements Handler { + @Override + public void handle(Context ctx) throws Exception { + EmployeeRepository repository = ctx.get(EmployeeRepository.class); + Long id = Long.valueOf(ctx.getPathTokens() + .get("id")); + Promise employeePromise = repository.findEmployeeById(id); + employeePromise.map(employee -> employee.getName()) + .then(name -> ctx.getResponse() + .send(name)); + } +} diff --git a/ratpack/src/main/java/com/baeldung/handler/FooHandler.java b/ratpack/src/main/java/com/baeldung/handler/FooHandler.java new file mode 100644 index 0000000000..d2c4dbdce5 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/handler/FooHandler.java @@ -0,0 +1,12 @@ +package com.baeldung.handler; + +import ratpack.handling.Context; +import ratpack.handling.Handler; + +public class FooHandler implements Handler { + @Override + public void handle(Context ctx) throws Exception { + ctx.getResponse() + .send("Hello Foo!"); + } +} diff --git a/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java b/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java new file mode 100644 index 0000000000..c95543a961 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/handler/RedirectHandler.java @@ -0,0 +1,23 @@ +package com.baeldung.handler; + +import ratpack.exec.Promise; +import ratpack.handling.Context; +import ratpack.handling.Handler; +import ratpack.http.client.HttpClient; +import ratpack.http.client.ReceivedResponse; + +import java.net.URI; + +public class RedirectHandler implements Handler { + @Override + public void handle(Context ctx) throws Exception { + HttpClient client = ctx.get(HttpClient.class); + URI uri = URI.create("http://localhost:5050/employee/1"); + Promise responsePromise = client.get(uri); + responsePromise.map(response -> response.getBody() + .getText() + .toUpperCase()) + .then(responseText -> ctx.getResponse() + .send(responseText)); + } +} \ No newline at end of file diff --git a/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java new file mode 100644 index 0000000000..de04c23da5 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.repository; + +import com.baeldung.model.Employee; +import ratpack.exec.Promise; + +public interface EmployeeRepository { + + Promise findEmployeeById(Long id) throws Exception; + +} diff --git a/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java new file mode 100644 index 0000000000..6d15012ccb --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/repository/EmployeeRepositoryImpl.java @@ -0,0 +1,25 @@ +package com.baeldung.repository; + +import com.baeldung.model.Employee; +import ratpack.exec.Promise; + +import java.util.HashMap; +import java.util.Map; + +public class EmployeeRepositoryImpl implements EmployeeRepository { + + private static final Map EMPLOYEE_MAP = new HashMap<>(); + + public EmployeeRepositoryImpl() { + EMPLOYEE_MAP.put(1L, new Employee(1L, "Ms", "Jane Doe")); + EMPLOYEE_MAP.put(2L, new Employee(2L, "Mr", "NY")); + } + + @Override + public Promise findEmployeeById(Long id) throws Exception { + return Promise.async(downstream -> { + Thread.sleep(500); + downstream.success(EMPLOYEE_MAP.get(id)); + }); + } +} diff --git a/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java b/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java new file mode 100644 index 0000000000..a97516dd74 --- /dev/null +++ b/ratpack/src/test/java/com/baeldung/AppHttpUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung; + +import com.baeldung.model.Employee; +import org.junit.Test; +import ratpack.exec.Promise; +import ratpack.func.Action; +import ratpack.handling.Chain; +import ratpack.handling.Handler; +import ratpack.registry.Registry; +import ratpack.test.embed.EmbeddedApp; +import ratpack.test.exec.ExecHarness; + +import static org.junit.Assert.assertEquals; + +public class AppHttpUnitTest { + + @Test + public void givenAnyUri_GetEmployeeFromSameRegistry() throws Exception { + Handler allHandler = ctx -> { + Long id = Long.valueOf(ctx.getPathTokens() + .get("id")); + Employee employee = new Employee(id, "Mr", "NY"); + ctx.next(Registry.single(Employee.class, employee)); + }; + Handler empNameHandler = ctx -> { + Employee employee = ctx.get(Employee.class); + ctx.getResponse() + .send("Name of employee with ID " + employee.getId() + " is " + employee.getName()); + }; + Handler empTitleHandler = ctx -> { + Employee employee = ctx.get(Employee.class); + ctx.getResponse() + .send("Title of employee with ID " + employee.getId() + " is " + employee.getTitle()); + }; + + Action chainAction = chain -> chain.prefix("employee/:id", empChain -> { + empChain.all(allHandler) + .get("name", empNameHandler) + .get("title", empTitleHandler); + }); + EmbeddedApp.fromHandlers(chainAction) + .test(testHttpClient -> { + assertEquals("Name of employee with ID 1 is NY", testHttpClient.get("employee/1/name") + .getBody() + .getText()); + assertEquals("Title of employee with ID 1 is Mr", testHttpClient.get("employee/1/title") + .getBody() + .getText()); + }); + } + + @Test + public void givenSyncDataSource_GetDataFromPromise() throws Exception { + String value = ExecHarness.yieldSingle(execution -> Promise.sync(() -> "Foo")) + .getValueOrThrow(); + assertEquals("Foo", value); + } +} diff --git a/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java b/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java index 56650ba306..e3060b8e02 100644 --- a/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java +++ b/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java @@ -37,14 +37,14 @@ public class ReactorIntegrationTest { Flux.just(1, 2, 3, 4) .log() .map(i -> i * 2) - .zipWith(Flux.range(0, Integer.MAX_VALUE).log(), (two, one) -> String.format("First Flux: %d, Second Flux: %d", one, two)) + .zipWith(Flux.range(0, Integer.MAX_VALUE).log(), (one, two) -> String.format("First Flux: %d, Second Flux: %d", one, two)) .subscribe(elements::add); assertThat(elements).containsExactly( - "First Flux: 0, Second Flux: 2", - "First Flux: 1, Second Flux: 4", - "First Flux: 2, Second Flux: 6", - "First Flux: 3, Second Flux: 8"); + "First Flux: 2, Second Flux: 0", + "First Flux: 4, Second Flux: 1", + "First Flux: 6, Second Flux: 2", + "First Flux: 8, Second Flux: 3"); } @Test diff --git a/rest-with-spark-java/src/test/java/com/baeldung/AppTest.java b/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java similarity index 96% rename from rest-with-spark-java/src/test/java/com/baeldung/AppTest.java rename to rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java index c7b88dd6d1..9e24879767 100644 --- a/rest-with-spark-java/src/test/java/com/baeldung/AppTest.java +++ b/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java @@ -16,16 +16,16 @@ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; -public class AppTest extends TestCase { +public class AppLiveTest extends TestCase { ObjectMapper mapper = new ObjectMapper(); - public AppTest( String testName ) { + public AppLiveTest( String testName ) { super( testName ); } public static Test suite() { - return new TestSuite( AppTest.class ); + return new TestSuite( AppLiveTest.class ); } public void testApp() throws IOException, ClassNotFoundException { diff --git a/resteasy/pom.xml b/resteasy/pom.xml index 867c1f4c1b..31a6ed485a 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -3,9 +3,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - resteasy-tutorial + resteasy 1.0 war + resteasy com.baeldung diff --git a/rxjava-2/README.md b/rxjava-2/README.md new file mode 100644 index 0000000000..78eb6e6428 --- /dev/null +++ b/rxjava-2/README.md @@ -0,0 +1,7 @@ +## Relevant articles: + +- [RxJava and Error Handling](http://www.baeldung.com/rxjava-error-handling) +- [RxJava 2 – Flowable](http://www.baeldung.com/rxjava-2-flowable) +- [RxJava 2 - Completable](http://www.baeldung.com/rxjava-completable) +- [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) +- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml new file mode 100644 index 0000000000..a18b096b6d --- /dev/null +++ b/rxjava-2/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + rxjava-2 + 1.0-SNAPSHOT + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} + + + com.jayway.awaitility + awaitility + ${awaitility.version} + + + org.assertj + assertj-core + ${assertj.version} + + + com.jakewharton.rxrelay2 + rxrelay + ${rxrelay.version} + + + + + 3.8.0 + 2.2.2 + 1.7.0 + 2.0.0 + + \ No newline at end of file diff --git a/rxjava/src/main/java/com/baeldung/rxjava/RandomRelay.java b/rxjava-2/src/main/java/com/baeldung/rxjava/RandomRelay.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/RandomRelay.java rename to rxjava-2/src/main/java/com/baeldung/rxjava/RandomRelay.java diff --git a/spring-data-5-reactive/src/main/resources/logback.xml b/rxjava-2/src/main/resources/logback.xml similarity index 100% rename from spring-data-5-reactive/src/main/resources/logback.xml rename to rxjava-2/src/main/resources/logback.xml diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java new file mode 100644 index 0000000000..6acda310a5 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java @@ -0,0 +1,112 @@ +package com.baeldung.rxjava; + +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Single; +import io.reactivex.observers.DisposableCompletableObserver; +import org.junit.Before; +import org.junit.Test; + +public class CompletableUnitTest { + + Completable first; + Completable second; + Completable error; + Throwable throwable = new RuntimeException(); + + @Before + public void setUpCompletables() { + first = Completable.fromSingle(Single.just(1)); + second = Completable.fromRunnable(() -> {}); + error = Single.error(throwable) + .ignoreElement(); + } + + @Test + public void whenCompletableConstructed_thenCompletedSuccessfully() { + Completable completed = Completable.complete(); + completed.subscribe(new DisposableCompletableObserver() { + @Override + public void onComplete() { + System.out.println("Completed!"); + } + + @Override + public void onError(Throwable e) { + e.printStackTrace(); + } + }); + Flowable flowable = Flowable.just("request received", "user logged in"); + Completable flowableCompletable = Completable.fromPublisher(flowable); + Completable singleCompletable = Single.just(1) + .ignoreElement(); + + completed.andThen(flowableCompletable) + .andThen(singleCompletable) + .test() + .assertComplete(); + } + + @Test + public void whenCombiningCompletables_thenCompletedSuccessfully() { + first.andThen(second) + .test() + .assertComplete(); + } + + @Test + public void whenCombinedWithError_thenCompletedWithError() { + first.andThen(second) + .andThen(error) + .test() + .assertError(throwable); + } + + @Test + public void whenCombinedWithNever_thenDoesNotComplete() { + first.andThen(second) + .andThen(Completable.never()) + .test() + .assertNotComplete(); + } + + @Test + public void whenMergedCompletables_thenCompletedSuccessfully() { + Completable.mergeArray(first, second) + .test() + .assertComplete(); + } + + @Test + public void whenMergedWithError_thenCompletedWithError() { + Completable.mergeArray(first, second, error) + .test() + .assertError(throwable); + } + + @Test + public void whenFlatMaped_thenCompletedSuccessfully() { + Completable allElementsCompletable = Flowable.just("request received", "user logged in") + .flatMapCompletable(message -> Completable + .fromRunnable(() -> System.out.println(message)) + ); + allElementsCompletable + .test() + .assertComplete(); + } + + @Test + public void whenAmbWithNever_thenCompletedSuccessfully() { + Completable.ambArray(first, Completable.never(), second) + .test() + .assertComplete(); + } + + @Test + public void whenAmbWithError_thenCompletedWithError() { + Completable.ambArray(error, first, second) + .test() + .assertError(throwable); + } + +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java rename to rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java rename to rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java rename to rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java rename to rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java rename to rxjava-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java new file mode 100644 index 0000000000..ade48a2cb9 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.rxjava.operators; + +import io.reactivex.Observable; +import io.reactivex.schedulers.TestScheduler; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.CoreMatchers.hasItems; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +public class RxFlatmapAndSwitchmapUnitTest { + @Test + public void givenObservable_whenFlatmap_shouldAssertAllItemsReturned() { + //given + List actualOutput = new ArrayList<>(); + final TestScheduler scheduler = new TestScheduler(); + final List keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books"); + + //when + Observable.fromIterable(keywordToSearch) + .flatMap(s -> Observable + .just(s + " FirstResult", s + " SecondResult") + .delay(10, TimeUnit.SECONDS, scheduler)) + .toList() + .doOnSuccess(s -> actualOutput.addAll(s)) + .subscribe(); + + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + + //then + assertThat(actualOutput, hasItems("b FirstResult", "b SecondResult", + "boo FirstResult", "boo SecondResult", + "bo FirstResult", "bo SecondResult", + "book FirstResult", "book SecondResult", + "books FirstResult", "books SecondResult")); + } + + @Test + public void givenObservable_whenSwitchmap_shouldAssertLatestItemReturned() { + //given + List actualOutput = new ArrayList<>(); + final TestScheduler scheduler = new TestScheduler(); + final List keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books"); + + //when + Observable.fromIterable(keywordToSearch) + .switchMap(s -> Observable + .just(s + " FirstResult", s + " SecondResult") + .delay(10, TimeUnit.SECONDS, scheduler)) + .toList() + .doOnSuccess(s -> actualOutput.addAll(s)) + .subscribe(); + + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + + //then + assertEquals(2, actualOutput.size()); + assertThat(actualOutput, hasItems("books FirstResult", "books SecondResult")); + } +} diff --git a/rxjava/README.md b/rxjava/README.md index 5c60e3bbce..f8a4ca1dbe 100644 --- a/rxjava/README.md +++ b/rxjava/README.md @@ -4,15 +4,12 @@ - [How to Test RxJava?](http://www.baeldung.com/rxjava-testing) - [Implementing Custom Operators in RxJava](http://www.baeldung.com/rxjava-custom-operators) - [Introduction to RxJava](http://www.baeldung.com/rx-java) -- [RxJava and Error Handling](http://www.baeldung.com/rxjava-error-handling) - [Observable Utility Operators in RxJava](http://www.baeldung.com/rxjava-observable-operators) - [Introduction to rxjava-jdbc](http://www.baeldung.com/rxjava-jdbc) - [Schedulers in RxJava](http://www.baeldung.com/rxjava-schedulers) - [Mathematical and Aggregate Operators in RxJava](http://www.baeldung.com/rxjava-math) - [Combining Observables in RxJava](http://www.baeldung.com/rxjava-combine-observables) -- [RxJava 2 – Flowable](http://www.baeldung.com/rxjava-2-flowable) - [RxJava StringObservable](http://www.baeldung.com/rxjava-string) -- [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) -- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) - [Filtering Observables in RxJava](http://www.baeldung.com/rxjava-filtering) - [RxJava One Observable, Multiple Subscribers](http://www.baeldung.com/rxjava-multiple-subscribers-observable) +- [Difference Between Flatmap and Switchmap in RxJava](https://www.baeldung.com/rxjava-flatmap-switchmap) diff --git a/rxjava/pom.xml b/rxjava/pom.xml index 49732c1ef4..b316001d87 100644 --- a/rxjava/pom.xml +++ b/rxjava/pom.xml @@ -20,12 +20,6 @@ ${rx.java.version} - - io.reactivex.rxjava2 - rxjava - ${rx.java2.version} - - io.reactivex rxjava-math @@ -59,22 +53,15 @@ assertj-core ${assertj.version} - - com.jakewharton.rxrelay2 - rxrelay - ${rxrelay.version} - 3.8.0 1.2.5 - 2.1.3 0.7.11 1.0.0 1.1.1 1.7.0 - 2.0.0 1.4.196 diff --git a/spring-4/README.md b/spring-4/README.md index 9855a9254d..4600a603ef 100644 --- a/spring-4/README.md +++ b/spring-4/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Guide to Flips For Spring](http://www.baeldung.com/guide-to-flips-for-spring/) - [A Guide to Flips for Spring](http://www.baeldung.com/flips-spring) +- [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) diff --git a/spring-4/pom.xml b/spring-4/pom.xml index d2632b5f55..78939bba95 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -3,7 +3,6 @@ 4.0.0 spring-4 spring-4 - 0.0.1-SNAPSHOT jar spring-4 @@ -19,6 +18,25 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.apache.tomcat + tomcat-jdbc + + + + + com.h2database + h2 + test + + + com.zaxxer + HikariCP + org.springframework.boot spring-boot-starter-test @@ -32,7 +50,6 @@ org.projectlombok lombok - ${lombok.version} provided @@ -54,10 +71,9 @@ - UTF-8 1.0.1 1.16.18 - 1.8 + 1.4.197 diff --git a/spring-4/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java b/spring-4/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java new file mode 100644 index 0000000000..0bd8637681 --- /dev/null +++ b/spring-4/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java @@ -0,0 +1,12 @@ +package com.baeldung.connectionpool; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationWithHikariConnectionPool { + + public static void main(String[] args) { + SpringApplication.run(ApplicationWithHikariConnectionPool.class, args); + } +} diff --git a/spring-4/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java b/spring-4/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java new file mode 100644 index 0000000000..0cc876d5b1 --- /dev/null +++ b/spring-4/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java @@ -0,0 +1,28 @@ +package com.baeldung.connectionpool; + +import static org.junit.Assert.*; + +import javax.sql.DataSource; + +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; + +@RunWith(SpringRunner.class) +@SpringBootTest( + // instead of setting this property, we can exclude the dependency to org.apache.tomcat:tomcat-jdbc in pom.xml + properties = "spring.datasource.type=com.zaxxer.hikari.HikariDataSource") +public class HikariIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void hikariConnectionPoolIsConfigured() { + assertEquals("com.zaxxer.hikari.HikariDataSource", dataSource.getClass() + .getName()); + } + +} diff --git a/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9dfac2bd9e --- /dev/null +++ b/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.flips.ApplicationConfig; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationConfig.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-5-reactive/README.md b/spring-5-data-reactive/README.md similarity index 100% rename from spring-data-5-reactive/README.md rename to spring-5-data-reactive/README.md diff --git a/spring-data-5-reactive/pom.xml b/spring-5-data-reactive/pom.xml similarity index 74% rename from spring-data-5-reactive/pom.xml rename to spring-5-data-reactive/pom.xml index 36ace53da2..5c723c6e29 100644 --- a/spring-data-5-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -2,9 +2,7 @@ 4.0.0 - com.baeldung spring-5-data-reactive - 0.0.1-SNAPSHOT jar @@ -44,11 +42,6 @@ reactor-test test - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - org.jetbrains.kotlin kotlin-test @@ -69,28 +62,6 @@ spring-boot-starter-test test - - - org.junit.jupiter - junit-jupiter-api - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - @@ -101,6 +72,7 @@ kotlin-maven-plugin + ${kotlin-maven-plugin.version} compile @@ -181,31 +153,13 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LiveTest.java - - - - UTF-8 - UTF-8 - 1.8 1.2.40 - 1.0.0 - 5.0.2 + 1.2.40 + diff --git a/spring-data-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java similarity index 100% rename from spring-data-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java diff --git a/spring-data-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/model/Account.java similarity index 100% rename from spring-data-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/model/Account.java diff --git a/spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java similarity index 100% rename from spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java diff --git a/spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java similarity index 100% rename from spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java diff --git a/spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java similarity index 100% rename from spring-data-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java diff --git a/spring-data-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java b/spring-5-data-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java similarity index 100% rename from spring-data-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java rename to spring-5-data-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/Application.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt similarity index 100% rename from spring-data-5-reactive/src/main/kotlin/com/baeldung/Application.kt rename to spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/Event.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/Event.kt similarity index 100% rename from spring-data-5-reactive/src/main/kotlin/com/baeldung/Event.kt rename to spring-5-data-reactive/src/main/kotlin/com/baeldung/Event.kt diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/EventRepository.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/EventRepository.kt similarity index 100% rename from spring-data-5-reactive/src/main/kotlin/com/baeldung/EventRepository.kt rename to spring-5-data-reactive/src/main/kotlin/com/baeldung/EventRepository.kt diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt similarity index 100% rename from spring-data-5-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt rename to spring-5-data-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt diff --git a/spring-data-5-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt similarity index 100% rename from spring-data-5-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt rename to spring-5-data-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt diff --git a/spring-data-spring-security/src/main/resources/logback.xml b/spring-5-data-reactive/src/main/resources/logback.xml similarity index 100% rename from spring-data-spring-security/src/main/resources/logback.xml rename to spring-5-data-reactive/src/main/resources/logback.xml diff --git a/spring-data-5-reactive/src/main/resources/static/index.html b/spring-5-data-reactive/src/main/resources/static/index.html similarity index 100% rename from spring-data-5-reactive/src/main/resources/static/index.html rename to spring-5-data-reactive/src/main/resources/static/index.html diff --git a/spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java similarity index 100% rename from spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java rename to spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java diff --git a/spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java similarity index 100% rename from spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java rename to spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java diff --git a/spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java similarity index 100% rename from spring-data-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java rename to spring-5-data-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java diff --git a/spring-data-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java similarity index 100% rename from spring-data-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java rename to spring-5-data-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java diff --git a/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ce4c172960 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.reactive.Spring5ReactiveApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index 71b7a19b43..fa9d48ab72 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -1,3 +1,5 @@ ### Relevant Articles: - [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin) -- [Spring MVC Streaming and SSE Request Processing](http://www.baeldung.com/spring-mvc-sse-streams) +- [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) +- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) +- [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 0408550c79..f5346a0fa0 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -82,11 +82,6 @@ spring-boot-starter-test test - - junit - junit - test - com.jayway.restassured rest-assured @@ -137,46 +132,11 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - - false - - **/*IntegrationTest.java - **/*IntTest.java - **/*LiveTest.java - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - + 2.9.0 1.1.2 - diff --git a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java index 41b5c1eed1..8251467122 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java @@ -1,7 +1,11 @@ package com.baeldung; +import javax.servlet.Filter; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.filter.DelegatingFilterProxy; +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @SpringBootApplication public class Spring5Application { @@ -10,4 +14,31 @@ public class Spring5Application { SpringApplication.run(Spring5Application.class, args); } + public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return null; + } + + @Override + protected Class[] getServletConfigClasses() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected String[] getServletMappings() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected javax.servlet.Filter[] getServletFilters() { + DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy(); + delegateFilterProxy.setTargetBeanName("loggingFilter"); + return new Filter[] { delegateFilterProxy }; + } + } + } diff --git a/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java b/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java new file mode 100644 index 0000000000..4aa33cd749 --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.filter; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component("loggingFilter") +public class CustomFilter implements Filter { + + private static Logger LOGGER = LoggerFactory.getLogger(CustomFilter.class); + + @Override + public void init(FilterConfig config) throws ServletException { + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletRequest req = (HttpServletRequest) request; + LOGGER.info("Request Info : " + req); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + // cleanup code, if necessary + } +} diff --git a/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java b/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java index ff1fb87393..c5f63486fe 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java +++ b/spring-5-mvc/src/main/java/com/baeldung/web/ResponseBodyEmitterController.java @@ -13,7 +13,7 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter @Controller public class ResponseBodyEmitterController { - private ExecutorService nonBlockingService = Executors.newSingleThreadExecutor(); + private ExecutorService nonBlockingService = Executors.newCachedThreadPool(); @GetMapping(Constants.API_RBE) public ResponseEntity handleRbe() { diff --git a/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java b/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java index b11c93fb08..00113c5ff7 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java +++ b/spring-5-mvc/src/main/java/com/baeldung/web/SseEmitterController.java @@ -1,12 +1,16 @@ package com.baeldung.web; -import com.baeldung.Constants; +import java.time.LocalTime; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; + import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter.SseEventBuilder; + +import com.baeldung.Constants; @Controller public class SseEmitterController { @@ -29,4 +33,27 @@ public class SseEmitterController { return emitter; } + @GetMapping("/stream-sse-mvc") + public SseEmitter streamSseMvc() { + SseEmitter emitter = new SseEmitter(); + ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor(); + + sseMvcExecutor.execute(() -> { + try { + for (int i = 0; true; i++) { + SseEventBuilder event = SseEmitter.event() + .data("SSE MVC - " + LocalTime.now() + .toString()) + .id(String.valueOf(i)) + .name("sse event - mvc"); + emitter.send(event); + Thread.sleep(1000); + } + } catch (Exception ex) { + emitter.completeWithError(ex); + } + }); + return emitter; + } + } diff --git a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml index bfcf43dad2..43c7143e5b 100644 --- a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml +++ b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml @@ -16,6 +16,14 @@ functional / + + loggingFilter + org.springframework.web.filter.DelegatingFilterProxy + + + loggingFilter + /* + \ No newline at end of file diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 9388ee83c1..6e39743ed0 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -3,16 +3,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-5-reactive-client - 0.0.1-SNAPSHOT jar spring-5-reactive-client spring 5 sample project about new features - parent-boot-2 com.baeldung + parent-boot-2 0.0.1-SNAPSHOT ../parent-boot-2 @@ -43,20 +41,6 @@ javax.json.bind javax.json.bind-api - - - - - - - - - - - - - - org.apache.geronimo.specs geronimo-json_1.1_spec @@ -102,37 +86,10 @@ test - - org.junit.jupiter - junit-jupiter-api - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - org.projectlombok lombok - - org.apache.commons - commons-lang3 - - @@ -145,54 +102,10 @@ JAR - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LiveTest.java - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - UTF-8 - UTF-8 - 1.8 - 1.0.0 - 5.0.0 - 2.20 - 5.0.2.RELEASE 1.0.1.RELEASE 1.1.3 1.0 diff --git a/spring-5-reactive-client/src/main/resources/logback.xml b/spring-5-reactive-client/src/main/resources/logback.xml index 8bbe8c1d67..7072369b8d 100644 --- a/spring-5-reactive-client/src/main/resources/logback.xml +++ b/spring-5-reactive-client/src/main/resources/logback.xml @@ -3,7 +3,7 @@ # Pattern of log message for console appender - %d{yyyy-MM-dd HH:mm:ss} %-5p %m%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7843a8968d --- /dev/null +++ b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.reactive.Spring5ReactiveTestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveTestApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} 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 8bbe8c1d67..7072369b8d 100644 --- a/spring-5-reactive-client/src/test/resources/logback-test.xml +++ b/spring-5-reactive-client/src/test/resources/logback-test.xml @@ -3,7 +3,7 @@ # Pattern of log message for console appender - %d{yyyy-MM-dd HH:mm:ss} %-5p %m%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/jsonb/.gitignore b/spring-5-reactive-security/.gitignore similarity index 100% rename from jsonb/.gitignore rename to spring-5-reactive-security/.gitignore diff --git a/spring-5-reactive-security/README.md b/spring-5-reactive-security/README.md new file mode 100644 index 0000000000..3395cf5562 --- /dev/null +++ b/spring-5-reactive-security/README.md @@ -0,0 +1,11 @@ +## Spring 5 Reactive Security Examples + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles + +- [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) +- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) +- [Guide to Spring 5 WebFlux](http://www.baeldung.com/spring-webflux) + diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml new file mode 100644 index 0000000000..3b64b9b3ac --- /dev/null +++ b/spring-5-reactive-security/pom.xml @@ -0,0 +1,135 @@ + + + 4.0.0 + + com.baeldung + spring-5-reactive-security + 0.0.1-SNAPSHOT + jar + spring-5-reactive-security + spring 5 security sample project about new features + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot + spring-boot-starter-webflux + + + org.projectreactor + reactor-spring + ${reactor-spring.version} + + + javax.json.bind + javax.json.bind-api + + + org.springframework.boot + spring-boot-starter-actuator + + + org.projectlombok + lombok + compile + + + org.apache.geronimo.specs + geronimo-json_1.1_spec + ${geronimo-json_1.1_spec.version} + + + org.apache.johnzon + johnzon-jsonb + + + + org.apache.commons + commons-lang3 + + + + + + org.springframework.boot + spring-boot-devtools + runtime + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + test + + + + io.reactivex.rxjava2 + rxjava + ${rxjava-version} + + + io.projectreactor + reactor-test + ${project-reactor-test} + test + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.webflux.EmployeeSpringApplication + JAR + + + + + + + 1.0.1.RELEASE + 2.1.12 + 1.1.3 + 1.0 + 1.0 + 4.1 + 3.1.6.RELEASE + + + diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/FeaturesEndpoint.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/InfoWebEndpointExtension.java diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java new file mode 100644 index 0000000000..f07ddfb0f7 --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.reactive.actuator; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class Spring5ReactiveApplication{ + + public static void main(String[] args) { + SpringApplication.run(Spring5ReactiveApplication.class, args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java similarity index 91% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java index 427fd70a6c..07f805fea4 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/WebSecurityConfig.java @@ -22,7 +22,7 @@ public class WebSecurityConfig { .authorizeExchange() .matchers(EndpointRequest.to( FeaturesEndpoint.class - )).permitAll().and().csrf().disable().build(); + )).permitAll().anyExchange().permitAll().and().csrf().disable().build(); } } diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java new file mode 100644 index 0000000000..76b697c1aa --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeFunctionalConfig.java @@ -0,0 +1,75 @@ +package com.baeldung.reactive.functional; + +import static org.springframework.web.reactive.function.BodyExtractors.toMono; +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RequestPredicates.POST; +import static org.springframework.web.reactive.function.server.RouterFunctions.route; +import static org.springframework.web.reactive.function.server.ServerResponse.ok; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.webflux.Employee; +import com.baeldung.webflux.EmployeeRepository; + +@Configuration +public class EmployeeFunctionalConfig { + + @Bean + EmployeeRepository employeeRepository() { + return new EmployeeRepository(); + } + + @Bean + RouterFunction getAllEmployeesRoute() { + return route(GET("/employees"), + req -> ok().body( + employeeRepository().findAllEmployees(), Employee.class)); + } + + @Bean + RouterFunction getEmployeeByIdRoute() { + return route(GET("/employees/{id}"), + req -> ok().body( + employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class)); + } + + @Bean + RouterFunction updateEmployeeRoute() { + return route(POST("/employees/update"), + req -> req.body(toMono(Employee.class)) + .doOnNext(employeeRepository()::updateEmployee) + .then(ok().build())); + } + + @Bean + RouterFunction composedRoutes() { + return + route(GET("/employees"), + req -> ok().body( + employeeRepository().findAllEmployees(), Employee.class)) + + .and(route(GET("/employees/{id}"), + req -> ok().body( + employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class))) + + .and(route(POST("/employees/update"), + req -> req.body(toMono(Employee.class)) + .doOnNext(employeeRepository()::updateEmployee) + .then(ok().build()))); + } + + @Bean + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http.csrf() + .disable() + .authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalApplication.java new file mode 100644 index 0000000000..1f2bd871fc --- /dev/null +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.reactive.functional; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EmployeeSpringFunctionalApplication { + + public static void main(String[] args) { + SpringApplication.run(EmployeeSpringFunctionalApplication.class, args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetController.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetController.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetController.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetController.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetService.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetService.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/security/GreetService.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/GreetService.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SecurityConfig.java similarity index 76% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SecurityConfig.java index 5ec3b6e241..225f78b3f7 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SecurityConfig.java @@ -8,6 +8,8 @@ import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.server.SecurityWebFilterChain; import com.baeldung.reactive.actuator.FeaturesEndpoint; @@ -35,19 +37,24 @@ public class SecurityConfig { @Bean public MapReactiveUserDetailsService userDetailsService() { - UserDetails user = User.withDefaultPasswordEncoder() - .username("user") - .password("password") + UserDetails user = User + .withUsername("user") + .password(passwordEncoder().encode("password")) .roles("USER") .build(); - UserDetails admin = User.withDefaultPasswordEncoder() - .username("admin") - .password("password") + UserDetails admin = User + .withUsername("admin") + .password(passwordEncoder().encode("password")) .roles("ADMIN") .build(); return new MapReactiveUserDetailsService(user, admin); } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/SpringSecurity5Application.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java similarity index 97% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/SpringSecurity5Application.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java index ca49ec6826..f2963c4fa5 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/SpringSecurity5Application.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive; +package com.baeldung.reactive.security; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/Employee.java similarity index 81% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/Employee.java index 6a03555654..bbdf85d293 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/Employee.java @@ -1,17 +1,17 @@ -package com.baeldung.reactive.webflux; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class Employee { - - private String id; - private String name; - - // standard getters and setters - -} +package com.baeldung.webflux; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Employee { + + private String id; + private String name; + + // standard getters and setters + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeConfig.java similarity index 93% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeConfig.java rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeConfig.java index 082be68698..6e73004650 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeConfig.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeConfig.java @@ -1,33 +1,33 @@ -package com.baeldung.reactive.webflux; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.reactive.HandlerMapping; -import org.springframework.web.reactive.config.EnableWebFlux; -import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; -import org.springframework.web.reactive.socket.WebSocketHandler; -import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; - -@Configuration -@EnableWebFlux -public class EmployeeConfig { - - @Bean - public HandlerMapping handlerMapping() { - Map map = new HashMap<>(); - map.put("/employee-feed", new EmployeeWebSocketHandler()); - - SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); - mapping.setUrlMap(map); - mapping.setOrder(10); - return mapping; - } - - @Bean - public WebSocketHandlerAdapter handlerAdapter() { - return new WebSocketHandlerAdapter(); - } -} +package com.baeldung.webflux; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.HandlerMapping; +import org.springframework.web.reactive.config.EnableWebFlux; +import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; +import org.springframework.web.reactive.socket.WebSocketHandler; +import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; + +@Configuration +@EnableWebFlux +public class EmployeeConfig { + + @Bean + public HandlerMapping handlerMapping() { + Map map = new HashMap<>(); + map.put("/employee-feed", new EmployeeWebSocketHandler()); + + SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); + mapping.setUrlMap(map); + mapping.setOrder(10); + return mapping; + } + + @Bean + public WebSocketHandlerAdapter handlerAdapter() { + return new WebSocketHandlerAdapter(); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeController.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeController.java similarity index 93% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeController.java rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeController.java index 98b16dafab..34e44afc8b 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeController.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeController.java @@ -1,38 +1,38 @@ -package com.baeldung.reactive.webflux; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -@RestController -@RequestMapping("/employees") -public class EmployeeController { - - private EmployeeRepository employeeRepository; - - public EmployeeController(EmployeeRepository employeeRepository) { - this.employeeRepository = employeeRepository; - } - - @GetMapping("/{id}") - private Mono getEmployeeById(@PathVariable String id) { - return employeeRepository.findEmployeeById(id); - } - - @GetMapping - private Flux getAllEmployees() { - return employeeRepository.findAllEmployees(); - } - - @PostMapping("/update") - private Mono updateEmployee(@RequestBody Employee employee) { - return employeeRepository.updateEmployee(employee); - } - -} +package com.baeldung.webflux; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RestController +@RequestMapping("/employees") +public class EmployeeController { + + private EmployeeRepository employeeRepository; + + public EmployeeController(EmployeeRepository employeeRepository) { + this.employeeRepository = employeeRepository; + } + + @GetMapping("/{id}") + private Mono getEmployeeById(@PathVariable String id) { + return employeeRepository.findEmployeeById(id); + } + + @GetMapping + private Flux getAllEmployees() { + return employeeRepository.findAllEmployees(); + } + + @PostMapping("/update") + private Mono updateEmployee(@RequestBody Employee employee) { + return employeeRepository.updateEmployee(employee); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeCreationEvent.java similarity index 89% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeCreationEvent.java index 7a66e1e147..d4f9a4fb02 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeCreationEvent.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.webflux; +package com.baeldung.webflux; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeRepository.java similarity index 95% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeRepository.java index a407c76fa8..d7f618f178 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeRepository.java @@ -1,64 +1,64 @@ -package com.baeldung.reactive.webflux; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.stereotype.Repository; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -@Repository -public class EmployeeRepository { - - static Map employeeData; - - static Map employeeAccessData; - - static - { - employeeData = new HashMap<>(); - employeeData.put("1",new Employee("1","Employee 1")); - employeeData.put("2",new Employee("2","Employee 2")); - employeeData.put("3",new Employee("3","Employee 3")); - employeeData.put("4",new Employee("4","Employee 4")); - employeeData.put("5",new Employee("5","Employee 5")); - employeeData.put("6",new Employee("6","Employee 6")); - employeeData.put("7",new Employee("7","Employee 7")); - employeeData.put("8",new Employee("8","Employee 8")); - employeeData.put("9",new Employee("9","Employee 9")); - employeeData.put("10",new Employee("10","Employee 10")); - - employeeAccessData=new HashMap<>(); - employeeAccessData.put("1", "Employee 1 Access Key"); - employeeAccessData.put("2", "Employee 2 Access Key"); - employeeAccessData.put("3", "Employee 3 Access Key"); - employeeAccessData.put("4", "Employee 4 Access Key"); - employeeAccessData.put("5", "Employee 5 Access Key"); - employeeAccessData.put("6", "Employee 6 Access Key"); - employeeAccessData.put("7", "Employee 7 Access Key"); - employeeAccessData.put("8", "Employee 8 Access Key"); - employeeAccessData.put("9", "Employee 9 Access Key"); - employeeAccessData.put("10", "Employee 10 Access Key"); - } - - public Mono findEmployeeById(String id) - { - return Mono.just(employeeData.get(id)); - } - - public Flux findAllEmployees() - { - return Flux.fromIterable(employeeData.values()); - } - - public Mono updateEmployee(Employee employee) - { - Employee existingEmployee=employeeData.get(employee.getId()); - if(existingEmployee!=null) - { - existingEmployee.setName(employee.getName()); - } - return Mono.just(existingEmployee); - } -} +package com.baeldung.webflux; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.stereotype.Repository; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Repository +public class EmployeeRepository { + + static Map employeeData; + + static Map employeeAccessData; + + static + { + employeeData = new HashMap<>(); + employeeData.put("1",new Employee("1","Employee 1")); + employeeData.put("2",new Employee("2","Employee 2")); + employeeData.put("3",new Employee("3","Employee 3")); + employeeData.put("4",new Employee("4","Employee 4")); + employeeData.put("5",new Employee("5","Employee 5")); + employeeData.put("6",new Employee("6","Employee 6")); + employeeData.put("7",new Employee("7","Employee 7")); + employeeData.put("8",new Employee("8","Employee 8")); + employeeData.put("9",new Employee("9","Employee 9")); + employeeData.put("10",new Employee("10","Employee 10")); + + employeeAccessData=new HashMap<>(); + employeeAccessData.put("1", "Employee 1 Access Key"); + employeeAccessData.put("2", "Employee 2 Access Key"); + employeeAccessData.put("3", "Employee 3 Access Key"); + employeeAccessData.put("4", "Employee 4 Access Key"); + employeeAccessData.put("5", "Employee 5 Access Key"); + employeeAccessData.put("6", "Employee 6 Access Key"); + employeeAccessData.put("7", "Employee 7 Access Key"); + employeeAccessData.put("8", "Employee 8 Access Key"); + employeeAccessData.put("9", "Employee 9 Access Key"); + employeeAccessData.put("10", "Employee 10 Access Key"); + } + + public Mono findEmployeeById(String id) + { + return Mono.just(employeeData.get(id)); + } + + public Flux findAllEmployees() + { + return Flux.fromIterable(employeeData.values()); + } + + public Mono updateEmployee(Employee employee) + { + Employee existingEmployee=employeeData.get(employee.getId()); + if(existingEmployee!=null) + { + existingEmployee.setName(employee.getName()); + } + return Mono.just(existingEmployee); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeSpringApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeSpringApplication.java similarity index 88% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeSpringApplication.java rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeSpringApplication.java index 54b23a18de..2652c36695 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeSpringApplication.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeSpringApplication.java @@ -1,17 +1,17 @@ -package com.baeldung.reactive.webflux; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class EmployeeSpringApplication { - - public static void main(String[] args) { - - SpringApplication.run(EmployeeSpringApplication.class, args); - - EmployeeWebClient employeeWebClient = new EmployeeWebClient(); - employeeWebClient.consume(); - } - -} +package com.baeldung.webflux; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EmployeeSpringApplication { + + public static void main(String[] args) { + + SpringApplication.run(EmployeeSpringApplication.class, args); + + EmployeeWebClient employeeWebClient = new EmployeeWebClient(); + employeeWebClient.consume(); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebClient.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebClient.java similarity index 91% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebClient.java rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebClient.java index 45d42ecda9..eb32408a7f 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebClient.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebClient.java @@ -1,28 +1,28 @@ -package com.baeldung.reactive.webflux; - -import org.springframework.web.reactive.function.client.WebClient; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -public class EmployeeWebClient { - - WebClient client = WebClient.create("http://localhost:8080"); - - public void consume() { - - Mono employeeMono = client.get() - .uri("/employees/{id}", "1") - .retrieve() - .bodyToMono(Employee.class); - - employeeMono.subscribe(System.out::println); - - Flux employeeFlux = client.get() - .uri("/employees") - .retrieve() - .bodyToFlux(Employee.class); - - employeeFlux.subscribe(System.out::println); - } +package com.baeldung.webflux; + +import org.springframework.web.reactive.function.client.WebClient; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class EmployeeWebClient { + + WebClient client = WebClient.create("http://localhost:8080"); + + public void consume() { + + Mono employeeMono = client.get() + .uri("/employees/{id}", "1") + .retrieve() + .bodyToMono(Employee.class); + + employeeMono.subscribe(System.out::println); + + Flux employeeFlux = client.get() + .uri("/employees") + .retrieve() + .bodyToFlux(Employee.class); + + employeeFlux.subscribe(System.out::println); + } } \ No newline at end of file diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSecurityConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSecurityConfig.java similarity index 71% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSecurityConfig.java rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSecurityConfig.java index 7922e6ba44..75475a0f08 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSecurityConfig.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSecurityConfig.java @@ -1,38 +1,46 @@ -package com.baeldung.reactive.webflux; - -import org.springframework.context.annotation.Bean; -import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; -import org.springframework.security.config.web.server.ServerHttpSecurity; -import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.web.server.SecurityWebFilterChain; - -@EnableWebFluxSecurity -public class EmployeeWebSecurityConfig { - - @Bean - public MapReactiveUserDetailsService userDetailsService() { - UserDetails user = User.withDefaultPasswordEncoder() - .username("admin") - .password("password") - .roles("ADMIN") - .build(); - return new MapReactiveUserDetailsService(user); - } - - @Bean - public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http.csrf() - .disable() - .authorizeExchange() - .pathMatchers(HttpMethod.POST, "/employees/update") - .hasRole("ADMIN") - .pathMatchers("/**") - .permitAll() - .and() - .httpBasic(); - return http.build(); - } -} +package com.baeldung.webflux; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@EnableWebFluxSecurity +public class EmployeeWebSecurityConfig { + + @Bean + public MapReactiveUserDetailsService userDetailsService() { + UserDetails user = User + .withUsername("admin") + .password(passwordEncoder().encode("password")) + .roles("ADMIN") + .build(); + return new MapReactiveUserDetailsService(user); + } + + @Bean + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http.csrf() + .disable() + .authorizeExchange() + .pathMatchers(HttpMethod.POST, "/employees/update") + .hasRole("ADMIN") + .pathMatchers("/**") + .permitAll() + .and() + .httpBasic(); + return http.build(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketClient.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketClient.java similarity index 94% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketClient.java rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketClient.java index 4571cadc47..feb1eb62fb 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketClient.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketClient.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.webflux; +package com.baeldung.webflux; import java.net.URI; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java similarity index 94% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java rename to spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java index c696bc8215..40b7b760ee 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java @@ -1,39 +1,39 @@ -package com.baeldung.reactive.webflux; - -import static java.time.LocalDateTime.now; -import static java.util.UUID.randomUUID; - -import java.time.Duration; - -import org.springframework.stereotype.Component; -import org.springframework.web.reactive.socket.WebSocketHandler; -import org.springframework.web.reactive.socket.WebSocketSession; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -@Component("EmployeeWebSocketHandler") -public class EmployeeWebSocketHandler implements WebSocketHandler { - - ObjectMapper om = new ObjectMapper(); - - @Override - public Mono handle(WebSocketSession webSocketSession) { - - Flux employeeCreationEvent = Flux.generate(sink -> { - EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString()); - try { - sink.next(om.writeValueAsString(event)); - } catch (JsonProcessingException e) { - sink.error(e); - } - }); - - return webSocketSession.send(employeeCreationEvent - .map(webSocketSession::textMessage) - .delayElements(Duration.ofSeconds(1))); - } -} +package com.baeldung.webflux; + +import static java.time.LocalDateTime.now; +import static java.util.UUID.randomUUID; + +import java.time.Duration; + +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.socket.WebSocketHandler; +import org.springframework.web.reactive.socket.WebSocketSession; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Component("EmployeeWebSocketHandler") +public class EmployeeWebSocketHandler implements WebSocketHandler { + + ObjectMapper om = new ObjectMapper(); + + @Override + public Mono handle(WebSocketSession webSocketSession) { + + Flux employeeCreationEvent = Flux.generate(sink -> { + EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString()); + try { + sink.next(om.writeValueAsString(event)); + } catch (JsonProcessingException e) { + sink.error(e); + } + }); + + return webSocketSession.send(employeeCreationEvent + .map(webSocketSession::textMessage) + .delayElements(Duration.ofSeconds(1))); + } +} diff --git a/spring-5-reactive-security/src/main/resources/application.properties b/spring-5-reactive-security/src/main/resources/application.properties new file mode 100644 index 0000000000..234834b894 --- /dev/null +++ b/spring-5-reactive-security/src/main/resources/application.properties @@ -0,0 +1,5 @@ +logging.level.root=INFO + +management.endpoints.web.exposure.include.=* + +info.app.name=Spring Boot 2 actuator Application diff --git a/spring-5-reactive-security/src/main/resources/files/hello.txt b/spring-5-reactive-security/src/main/resources/files/hello.txt new file mode 100644 index 0000000000..b6fc4c620b --- /dev/null +++ b/spring-5-reactive-security/src/main/resources/files/hello.txt @@ -0,0 +1 @@ +hello \ No newline at end of file diff --git a/spring-5-reactive-security/src/main/resources/files/test/test.txt b/spring-5-reactive-security/src/main/resources/files/test/test.txt new file mode 100644 index 0000000000..30d74d2584 --- /dev/null +++ b/spring-5-reactive-security/src/main/resources/files/test/test.txt @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/client/src/main/resources/logback.xml b/spring-5-reactive-security/src/main/resources/logback.xml similarity index 100% rename from spring-remoting/remoting-hessian-burlap/client/src/main/resources/logback.xml rename to spring-5-reactive-security/src/main/resources/logback.xml diff --git a/spring-5-reactive-security/src/main/resources/static/client-websocket.html b/spring-5-reactive-security/src/main/resources/static/client-websocket.html new file mode 100644 index 0000000000..3f840e8bd4 --- /dev/null +++ b/spring-5-reactive-security/src/main/resources/static/client-websocket.html @@ -0,0 +1,34 @@ + + + + +Baeldung: Spring 5 Reactive Client WebSocket (Browser) + + + +
    + + + \ No newline at end of file diff --git a/spring-5-reactive-security/src/main/webapp/WEB-INF/web.xml b/spring-5-reactive-security/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..bfcf43dad2 --- /dev/null +++ b/spring-5-reactive-security/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + Spring Functional Application + + + functional + com.baeldung.functional.RootServlet + 1 + true + + + functional + / + + + + \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java similarity index 95% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java rename to spring-5-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java index 3020e86723..94979a18ca 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/actuator/ActuatorInfoIntegrationTest.java @@ -9,8 +9,6 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.reactive.Spring5ReactiveApplication; - import java.io.IOException; import static org.junit.Assert.assertEquals; diff --git a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java new file mode 100644 index 0000000000..6e73e8072c --- /dev/null +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java @@ -0,0 +1,98 @@ +package com.baeldung.reactive.functional; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +import com.baeldung.webflux.Employee; +import com.baeldung.webflux.EmployeeRepository; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class EmployeeSpringFunctionalIntegrationTest { + + @Autowired + private EmployeeFunctionalConfig config; + + @MockBean + private EmployeeRepository employeeRepository; + + @Test + public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { + WebTestClient client = WebTestClient + .bindToRouterFunction(config.getEmployeeByIdRoute()) + .build(); + + Employee employee = new Employee("1", "Employee 1"); + + given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); + + client.get() + .uri("/employees/1") + .exchange() + .expectStatus() + .isOk() + .expectBody(Employee.class) + .isEqualTo(employee); + } + + @Test + public void whenGetAllEmployees_thenCorrectEmployees() { + WebTestClient client = WebTestClient + .bindToRouterFunction(config.getAllEmployeesRoute()) + .build(); + + List employeeList = new ArrayList<>(); + + Employee employee1 = new Employee("1", "Employee 1"); + Employee employee2 = new Employee("2", "Employee 2"); + + employeeList.add(employee1); + employeeList.add(employee2); + + Flux employeeFlux = Flux.fromIterable(employeeList); + given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); + + client.get() + .uri("/employees") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Employee.class) + .isEqualTo(employeeList); + } + + @Test + public void whenUpdateEmployee_thenEmployeeUpdated() { + WebTestClient client = WebTestClient + .bindToRouterFunction(config.updateEmployeeRoute()) + .build(); + + Employee employee = new Employee("1", "Employee 1 Updated"); + + client.post() + .uri("/employees/update") + .body(Mono.just(employee), Employee.class) + .exchange() + .expectStatus() + .isOk(); + + verify(employeeRepository).updateEmployee(employee); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java similarity index 93% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java rename to spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java index e8c8c25723..3dc832d781 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java @@ -1,74 +1,76 @@ -package com.baeldung.reactive.webflux; - -import static org.mockito.BDDMockito.given; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.reactive.server.WebTestClient; - -import com.baeldung.reactive.Spring5ReactiveApplication; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes=Spring5ReactiveApplication.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class EmployeeControllerIntegrationTest { - - @Autowired - private WebTestClient testClient; - - @MockBean - private EmployeeRepository employeeRepository; - - @Test - public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { - - Employee employee = new Employee("1", "Employee 1 Name"); - - given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); - testClient.get() - .uri("/employees/1") - .exchange() - .expectStatus() - .isOk() - .expectBody(Employee.class) - .isEqualTo(employee); - } - - @Test - public void whenGetAllEmployees_thenCorrectEmployees() { - - List employeeList = new ArrayList<>(); - - Employee employee1 = new Employee("1", "Employee 1 Name"); - Employee employee2 = new Employee("2", "Employee 2 Name"); - Employee employee3 = new Employee("3", "Employee 3 Name"); - - employeeList.add(employee1); - employeeList.add(employee2); - employeeList.add(employee3); - - Flux employeeFlux = Flux.fromIterable(employeeList); - - given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); - testClient.get() - .uri("/employees") - .exchange() - .expectStatus() - .isOk() - .expectBodyList(Employee.class) - .hasSize(3) - .isEqualTo(employeeList); - } -} +package com.baeldung.reactive.webflux; + +import static org.mockito.BDDMockito.given; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +import com.baeldung.reactive.actuator.Spring5ReactiveApplication; +import com.baeldung.webflux.Employee; +import com.baeldung.webflux.EmployeeRepository; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes=Spring5ReactiveApplication.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class EmployeeControllerIntegrationTest { + + @Autowired + private WebTestClient testClient; + + @MockBean + private EmployeeRepository employeeRepository; + + @Test + public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { + + Employee employee = new Employee("1", "Employee 1 Name"); + + given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); + testClient.get() + .uri("/employees/1") + .exchange() + .expectStatus() + .isOk() + .expectBody(Employee.class) + .isEqualTo(employee); + } + + @Test + public void whenGetAllEmployees_thenCorrectEmployees() { + + List employeeList = new ArrayList<>(); + + Employee employee1 = new Employee("1", "Employee 1 Name"); + Employee employee2 = new Employee("2", "Employee 2 Name"); + Employee employee3 = new Employee("3", "Employee 3 Name"); + + employeeList.add(employee1); + employeeList.add(employee2); + employeeList.add(employee3); + + Flux employeeFlux = Flux.fromIterable(employeeList); + + given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); + testClient.get() + .uri("/employees") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Employee.class) + .hasSize(3) + .isEqualTo(employeeList); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/security/SecurityIntegrationTest.java similarity index 94% rename from spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java rename to spring-5-reactive-security/src/test/java/com/baeldung/security/SecurityIntegrationTest.java index a59ef57db8..423500e09c 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/security/SecurityIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.security; -import com.baeldung.reactive.SpringSecurity5Application; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -12,6 +11,8 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; +import com.baeldung.reactive.security.SpringSecurity5Application; + @RunWith(SpringRunner.class) @ContextConfiguration(classes = SpringSecurity5Application.class) public class SecurityIntegrationTest { diff --git a/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2bcd974510 --- /dev/null +++ b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.reactive.security.SpringSecurity5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSecurity5Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive-security/src/test/resources/baeldung-weekly.png b/spring-5-reactive-security/src/test/resources/baeldung-weekly.png new file mode 100644 index 0000000000..a1b7eebcab Binary files /dev/null and b/spring-5-reactive-security/src/test/resources/baeldung-weekly.png differ diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 0a7fe7a47e..7977fd820f 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -1,4 +1,4 @@ -## Spring REST Example Project +## Spring 5 Reactive Project ### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring @@ -7,12 +7,10 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) - [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) -- [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) - [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) -- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) - [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) - [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) - [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) - [Spring Webflux and CORS](http://www.baeldung.com/spring-webflux-cors) - [Handling Errors in Spring WebFlux](http://www.baeldung.com/spring-webflux-errors) -- [Guide to Spring 5 WebFlux](http://www.baeldung.com/spring-webflux) +- [Server-Sent Events in Spring](https://www.baeldung.com/spring-server-sent-events) diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index acc82be0d1..5f455c3906 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -39,24 +39,6 @@ javax.json.bind javax.json.bind-api - - org.springframework.boot - spring-boot-starter-actuator - - - - - - - - - - - - - - - org.projectlombok lombok @@ -101,32 +83,6 @@ test - - org.junit.jupiter - junit-jupiter-api - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - org.apache.commons - commons-lang3 - - io.reactivex.rxjava2 rxjava @@ -138,15 +94,12 @@ ${project-reactor-test} test - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.security - spring-security-test - test - + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + @@ -159,29 +112,10 @@ JAR - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LiveTest.java - - - - 1.0.0 - 5.0.2 - 2.20 1.0.1.RELEASE 2.1.12 1.1.3 @@ -189,6 +123,7 @@ 1.0 4.1 3.1.6.RELEASE + 1.2.0 diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java index 402b607b19..a1d5d87d5c 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java @@ -21,9 +21,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.io.ClassPathResource; import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; @@ -68,18 +65,6 @@ public class FunctionalSpringBootApplication { return registrationBean; } - @Configuration - @EnableWebSecurity - @Profile("!https") - static class SecurityConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(final HttpSecurity http) throws Exception { - http.authorizeRequests() - .anyRequest() - .permitAll(); - } - } - public static void main(String[] args) { SpringApplication.run(FunctionalSpringBootApplication.class, args); } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java new file mode 100644 index 0000000000..3997607ef0 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.reactive.serversentevents.consumer; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication +@EnableAsync +public class ConsumerSSEApplication { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(ConsumerSSEApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8082")); + app.run(args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java new file mode 100644 index 0000000000..69a6bc396c --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java @@ -0,0 +1,83 @@ +package com.baeldung.reactive.serversentevents.consumer.controller; + +import java.time.LocalTime; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.MediaType; +import org.springframework.http.codec.ServerSentEvent; +import org.springframework.scheduling.annotation.Async; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClient; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@RestController +@RequestMapping("/sse-consumer") +public class ClientController { + + private static Logger logger = LoggerFactory.getLogger(ClientController.class); + private WebClient client = WebClient.create("http://localhost:8081/sse-server"); + + @GetMapping("/launch-sse-client") + public String launchSSEFromSSEWebClient() { + consumeSSE(); + return "LAUNCHED EVENT CLIENT!!! Check the logs..."; + } + + @GetMapping("/launch-flux-client") + public String launchcFluxFromSSEWebClient() { + consumeFlux(); + return "LAUNCHED EVENT CLIENT!!! Check the logs..."; + } + + @GetMapping("/launch-sse-from-flux-endpoint-client") + public String launchFluxFromFluxWebClient() { + consumeSSEFromFluxEndpoint(); + return "LAUNCHED EVENT CLIENT!!! Check the logs..."; + } + + @Async + public void consumeSSE() { + ParameterizedTypeReference> type = new ParameterizedTypeReference>() { + }; + + Flux> eventStream = client.get() + .uri("/stream-sse") + .retrieve() + .bodyToFlux(type); + + eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error), + () -> logger.info("Completed!!!")); + } + + @Async + public void consumeFlux() { + Flux stringStream = client.get() + .uri("/stream-flux") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(String.class); + + stringStream.subscribe(content -> logger.info("Current time: {} - Received content: {} ", LocalTime.now(), content), error -> logger.error("Error retrieving content: {}", error), () -> logger.info("Completed!!!")); + } + + @Async + public void consumeSSEFromFluxEndpoint() { + ParameterizedTypeReference> type = new ParameterizedTypeReference>() { + }; + + Flux> eventStream = client.get() + .uri("/stream-flux") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(type); + + eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error), + () -> logger.info("Completed!!!")); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java new file mode 100644 index 0000000000..2750e6616d --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.reactive.serversentevents.server; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ServerSSEApplication { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(ServerSSEApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8081")); + app.run(args); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java new file mode 100644 index 0000000000..1ad8e848cf --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java @@ -0,0 +1,35 @@ +package com.baeldung.reactive.serversentevents.server.controllers; + +import java.time.Duration; +import java.time.LocalTime; + +import org.springframework.http.MediaType; +import org.springframework.http.codec.ServerSentEvent; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Flux; + +@RestController +@RequestMapping("/sse-server") +public class ServerController { + + @GetMapping("/stream-sse") + public Flux> streamEvents() { + return Flux.interval(Duration.ofSeconds(1)) + .map(sequence -> ServerSentEvent. builder() + .id(String.valueOf(sequence)) + .event("periodic-event") + .data("SSE - " + LocalTime.now() + .toString()) + .build()); + } + + @GetMapping(path = "/stream-flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux streamFlux() { + return Flux.interval(Duration.ofSeconds(1)) + .map(sequence -> "Flux - " + LocalTime.now() + .toString()); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java new file mode 100644 index 0000000000..8d16434920 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/util/CpuUtils.java @@ -0,0 +1,15 @@ +package com.baeldung.reactive.util; + +import com.sun.management.OperatingSystemMXBean; + +import java.lang.management.ManagementFactory; + +public class CpuUtils { + + private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); + + static Double getUsage() { + return (operatingSystemMXBean.getSystemCpuLoad() / operatingSystemMXBean.getAvailableProcessors()) * 100; + } + +} diff --git a/spring-5-reactive/src/main/resources/application.properties b/spring-5-reactive/src/main/resources/application.properties index 234834b894..92f3116f84 100644 --- a/spring-5-reactive/src/main/resources/application.properties +++ b/spring-5-reactive/src/main/resources/application.properties @@ -1,5 +1,2 @@ logging.level.root=INFO -management.endpoints.web.exposure.include.=* - -info.app.name=Spring Boot 2 actuator Application diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java new file mode 100644 index 0000000000..53f4a3b1bb --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java @@ -0,0 +1,49 @@ +package com.baeldung.reactive.serversentsevents; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(JUnitPlatform.class) +@SpringBootTest +public class ServiceSentEventLiveTest { + + private WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:8081/sse-server") + .build(); + + @Test + public void whenSSEEndpointIsCalled_thenEventStreamingBegins() { + + Executable sseStreamingCall = () -> client.get() + .uri("/stream-sse") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM) + .expectBody(String.class); + + Assertions.assertThrows(IllegalStateException.class, sseStreamingCall, "Expected test to timeout and throw IllegalStateException, but it didn't"); + } + + @Test + public void whenFluxEndpointIsCalled_thenEventStreamingBegins() { + + Executable sseStreamingCall = () -> client.get() + .uri("/stream-flux") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM) + .expectBody(String.class); + + Assertions.assertThrows(IllegalStateException.class, sseStreamingCall, "Expected test to timeout and throw IllegalStateException, but it didn't"); + } +} diff --git a/spring-5-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ce4c172960 --- /dev/null +++ b/spring-5-reactive/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.reactive.Spring5ReactiveApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-security/README.md b/spring-5-security/README.md index 94a8f83281..55fa7ab042 100644 --- a/spring-5-security/README.md +++ b/spring-5-security/README.md @@ -4,4 +4,5 @@ - [Extra Login Fields with Spring Security](http://www.baeldung.com/spring-security-extra-login-fields) - [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer) - [New Password Storage In Spring Security 5](http://www.baeldung.com/spring-security-5-password-storage) - +- [Default Password Encoder in Spring Security 5](https://www.baeldung.com/spring-security-5-default-password-encoder) +- [Extracting Principal and Authorities using Spring Security OAuth](https://www.baeldung.com/spring-security-oauth-principal-authorities-extractor) diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index 7024e6f873..1435019c24 100644 --- a/spring-5-security/pom.xml +++ b/spring-5-security/pom.xml @@ -76,44 +76,7 @@ JAR - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LiveTest.java - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - \ No newline at end of file diff --git a/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerTest.java b/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java similarity index 97% rename from spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerTest.java rename to spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java index 7a8ea7b248..9d08cb7cfa 100644 --- a/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerTest.java +++ b/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java @@ -14,7 +14,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = InMemoryAuthApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class InMemoryAuthControllerTest { +public class InMemoryAuthControllerIntegrationTest { @Autowired private TestRestTemplate template; diff --git a/spring-5-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..967f67e760 --- /dev/null +++ b/spring-5-security/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.dsl.CustomConfigurerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CustomConfigurerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5/README.md b/spring-5/README.md index 47bae09862..d3c1decbc7 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -12,4 +12,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs) - [Spring ResponseStatusException](http://www.baeldung.com/spring-response-status-exception) - [Spring Assert Statements](http://www.baeldung.com/spring-assert) -- [Spring Security 5 – OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) +- [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) + diff --git a/spring-5/pom.xml b/spring-5/pom.xml index e37833ff94..293edb5bda 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -1,5 +1,6 @@ - 4.0.0 com.baeldung @@ -41,18 +42,6 @@ javax.json.bind javax.json.bind-api - - - - - - - - - - - - org.apache.geronimo.specs geronimo-json_1.1_spec @@ -85,45 +74,21 @@ org.springframework spring-test - - org.springframework.boot - spring-boot-starter-test - test - org.springframework.security spring-security-test test - org.apache.commons commons-collections4 ${commons-collections4.version} test - org.junit.jupiter junit-jupiter-api - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - org.springframework.restdocs @@ -147,22 +112,6 @@ JAR - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LiveTest.java - - - org.asciidoctor asciidoctor-maven-plugin @@ -186,17 +135,35 @@ + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + methods + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + - 1.0.0 - 5.0.2.RELEASE - 1.0.1.RELEASE 1.0 1.5.6 4.1 ${project.build.directory}/generated-snippets + 2.21.0 + diff --git a/spring-5/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java b/spring-5/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java new file mode 100644 index 0000000000..0bd8637681 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/connectionpool/ApplicationWithHikariConnectionPool.java @@ -0,0 +1,12 @@ +package com.baeldung.connectionpool; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationWithHikariConnectionPool { + + public static void main(String[] args) { + SpringApplication.run(ApplicationWithHikariConnectionPool.class, args); + } +} diff --git a/spring-5/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java b/spring-5/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java new file mode 100644 index 0000000000..d91cca85ee --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/connectionpool/HikariIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.connectionpool; + +import static org.junit.Assert.*; + +import javax.sql.DataSource; + +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; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class HikariIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void hikariConnectionPoolIsConfigured() { + assertEquals("com.zaxxer.hikari.HikariDataSource", dataSource.getClass() + .getName()); + } + +} diff --git a/spring-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..75b3df4978 --- /dev/null +++ b/spring-5/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.Spring5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5/src/test/resources/logback-test.xml b/spring-5/src/test/resources/logback-test.xml index 84f8e4706a..424ab87f79 100644 --- a/spring-5/src/test/resources/logback-test.xml +++ b/spring-5/src/test/resources/logback-test.xml @@ -1,5 +1,15 @@ - - + + + # Pattern of log message for console appender + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 1b9e831a29..0a19f483c1 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -2,9 +2,7 @@ 4.0.0 - com.example spring-activiti - 0.0.1-SNAPSHOT jar spring-activiti Demo project for Spring Boot @@ -44,33 +42,6 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - - - com.example.activitiwithspring.ActivitiWithSpringApplication UTF-8 diff --git a/spring-activiti/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-activiti/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ae37e77f86 --- /dev/null +++ b/spring-activiti/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.example.activitiwithspring.ActivitiWithSpringApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ActivitiWithSpringApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-all/pom.xml b/spring-all/pom.xml index c4c4cf7963..bab2e431ec 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -45,6 +45,15 @@ spring-shell ${org.springframework.shell.version} + + org.springframework + spring-websocket + + + org.springframework + spring-messaging + + org.springframework @@ -190,7 +199,24 @@ - + + + dev + + true + + + dev + + + + prod + + prod + + + + org.baeldung.sample.App diff --git a/spring-all/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java b/spring-all/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java index eb5543e3db..2d1905ee9c 100644 --- a/spring-all/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java +++ b/spring-all/src/main/java/org/baeldung/profiles/SpringProfilesConfig.java @@ -2,9 +2,11 @@ package org.baeldung.profiles; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; @Configuration @ComponentScan("org.baeldung.profiles") +@PropertySource(value = "classpath:application.properties") public class SpringProfilesConfig { } diff --git a/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java b/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java index 73df386aff..9257a3aa3a 100644 --- a/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java +++ b/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java @@ -13,21 +13,36 @@ import org.springframework.web.bind.annotation.RequestMapping; public class ScopesController { public static final Logger LOG = LoggerFactory.getLogger(ScopesController.class); - @Resource(name = "requestMessage") - HelloMessageGenerator requestMessage; + @Resource(name = "requestScopedBean") + HelloMessageGenerator requestScopedBean; - @Resource(name = "sessionMessage") - HelloMessageGenerator sessionMessage; + @Resource(name = "sessionScopedBean") + HelloMessageGenerator sessionScopedBean; - @RequestMapping("/scopes") - public String getScopes(final Model model) { - LOG.info("Request Message:" + requestMessage.getMessage()); - LOG.info("Session Message" + sessionMessage.getMessage()); - requestMessage.setMessage("Good morning!"); - sessionMessage.setMessage("Good afternoon!"); - model.addAttribute("requestMessage", requestMessage.getMessage()); - model.addAttribute("sessionMessage", sessionMessage.getMessage()); + @Resource(name = "applicationScopedBean") + HelloMessageGenerator applicationScopedBean; + + @RequestMapping("/scopes/request") + public String getRequestScopeMessage(final Model model) { + model.addAttribute("previousMessage", requestScopedBean.getMessage()); + requestScopedBean.setMessage("Request Scope Message!"); + model.addAttribute("currentMessage", requestScopedBean.getMessage()); return "scopesExample"; } + @RequestMapping("/scopes/session") + public String getSessionScopeMessage(final Model model) { + model.addAttribute("previousMessage", sessionScopedBean.getMessage()); + sessionScopedBean.setMessage("Session Scope Message!"); + model.addAttribute("currentMessage", sessionScopedBean.getMessage()); + return "scopesExample"; + } + + @RequestMapping("/scopes/application") + public String getApplicationScopeMessage(final Model model) { + model.addAttribute("previousMessage", applicationScopedBean.getMessage()); + applicationScopedBean.setMessage("Application Scope Message!"); + model.addAttribute("currentMessage", applicationScopedBean.getMessage()); + return "scopesExample"; + } } diff --git a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java index fb34725508..b5fe494ee2 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java @@ -27,19 +27,25 @@ public class ScopesConfig { @Bean @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator requestMessage() { + public HelloMessageGenerator requestScopedBean() { return new HelloMessageGenerator(); } @Bean @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator sessionMessage() { + public HelloMessageGenerator sessionScopedBean() { return new HelloMessageGenerator(); } @Bean @Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator globalSessionMessage() { + public HelloMessageGenerator applicationScopedBean() { + return new HelloMessageGenerator(); + } + + @Bean + @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS) + public HelloMessageGenerator websocketScopedBean() { return new HelloMessageGenerator(); } diff --git a/spring-all/src/main/resources/application.properties b/spring-all/src/main/resources/application.properties new file mode 100644 index 0000000000..cbfe3f2df2 --- /dev/null +++ b/spring-all/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.profiles.active=@spring.profiles.active@ \ No newline at end of file diff --git a/spring-all/src/main/resources/logback.xml b/spring-all/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-all/src/main/resources/logback.xml +++ b/spring-all/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-all/src/main/webapp/WEB-INF/view/scopesExample.jsp b/spring-all/src/main/webapp/WEB-INF/view/scopesExample.jsp index 7974cf0220..0946f1b5ef 100644 --- a/spring-all/src/main/webapp/WEB-INF/view/scopesExample.jsp +++ b/spring-all/src/main/webapp/WEB-INF/view/scopesExample.jsp @@ -2,9 +2,9 @@ -

    Bean Scopes Examples

    -
    - Request Message: ${requestMessage }
    - Session Message: ${sessionMessage } +

    Bean Scopes Examples

    +
    Previous Message: ${previousMessage } +
    Current Message: ${currentMessage } +
    \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java b/spring-all/src/test/java/org/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java new file mode 100644 index 0000000000..929d088a14 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java @@ -0,0 +1,22 @@ +package org.baeldung.profiles; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringProfilesWithMavenPropertiesIntegrationTest { + + @Autowired + DatasourceConfig datasourceConfig; + + @Test + public void testSpringProfiles() { + Assert.assertTrue(datasourceConfig instanceof DevDatasourceConfig); + } +} \ No newline at end of file diff --git a/spring-amqp-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-amqp-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f134074cf8 --- /dev/null +++ b/spring-amqp-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.springamqpsimple.SpringAmqpApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringAmqpApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-amqp/pom.xml b/spring-amqp/pom.xml index 065fce7d35..e08a4243b3 100755 --- a/spring-amqp/pom.xml +++ b/spring-amqp/pom.xml @@ -2,10 +2,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - springamqp + spring-amqp 0.1-SNAPSHOT jar - springamqp + spring-amqp Introduction to Spring-AMQP diff --git a/spring-aop/src/main/resources/logback.xml b/spring-aop/src/main/resources/logback.xml index 3245e94f08..7c15f603a0 100644 --- a/spring-aop/src/main/resources/logback.xml +++ b/spring-aop/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..cf1ac7de89 --- /dev/null +++ b/spring-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-apache-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-apache-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..efd0603c76 --- /dev/null +++ b/spring-apache-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.camel.main.App; + +public class SpringContextIntegrationTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-batch/repository.sqlite b/spring-batch/repository.sqlite new file mode 100644 index 0000000000..4456ef63cc Binary files /dev/null and b/spring-batch/repository.sqlite differ diff --git a/spring-batch/src/main/resources/logback.xml b/spring-batch/src/main/resources/logback.xml index 0313fb5008..91d4292b8e 100644 --- a/spring-batch/src/main/resources/logback.xml +++ b/spring-batch/src/main/resources/logback.xml @@ -3,7 +3,7 @@ - %d{yyyy-MM-dd HH:mm:ss} [%thread] %level %logger{35} - %msg%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-batch/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c3a9f74759 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.baeldung.batch.App; +import org.junit.Test; + +public class SpringContextIntegrationTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-bom/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-bom/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6dee4b808e --- /dev/null +++ b/spring-bom/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.spring.bom.HelloWorldApp; + +public class SpringContextIntegrationTest { + + @Test + public final void testMain() throws Exception { + HelloWorldApp.main(null); + } +} diff --git a/spring-boot-admin/spring-boot-admin-client/pom.xml b/spring-boot-admin/spring-boot-admin-client/pom.xml index fcbbb11cd7..ea03d6ef6d 100644 --- a/spring-boot-admin/spring-boot-admin-client/pom.xml +++ b/spring-boot-admin/spring-boot-admin-client/pom.xml @@ -46,6 +46,7 @@ org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} @@ -59,6 +60,7 @@ 1.5.4 + 2.0.4.RELEASE
    diff --git a/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..1f1fae17bc --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.springbootadminclient.SpringBootAdminClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootAdminClientApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/pom.xml b/spring-boot-admin/spring-boot-admin-server/pom.xml index 50228034c1..d8e7bb5574 100644 --- a/spring-boot-admin/spring-boot-admin-server/pom.xml +++ b/spring-boot-admin/spring-boot-admin-server/pom.xml @@ -76,6 +76,7 @@ org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} @@ -83,6 +84,7 @@ 1.5.4 1.5.4 + 2.0.4.RELEASE diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4c151d97df --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.springbootadminserver.SpringBootAdminServerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootAdminServerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-angular-ecommerce/README.md b/spring-boot-angular-ecommerce/README.md index 933059bc45..c6564643e2 100644 --- a/spring-boot-angular-ecommerce/README.md +++ b/spring-boot-angular-ecommerce/README.md @@ -1,2 +1,2 @@ ### Relevant Articles: -- [A Simple E-Commerce Implementation with Spring]() +- [A Simple E-Commerce Implementation with Spring](https://www.baeldung.com/spring-angular-ecommerce) diff --git a/spring-boot-angular-ecommerce/src/main/frontend/package.json b/spring-boot-angular-ecommerce/src/main/frontend/package.json index 28e716b9a6..958e9f1023 100644 --- a/spring-boot-angular-ecommerce/src/main/frontend/package.json +++ b/spring-boot-angular-ecommerce/src/main/frontend/package.json @@ -5,6 +5,9 @@ "ng": "ng", "start": "ng serve --proxy-config proxy-conf.json", "build": "ng build", + "postbuild": "npm run deploy", + "predeploy": "rimraf ../resources/static/ && mkdirp ../resources/static", + "deploy": "copyfiles -f dist/** ../resources/static", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" diff --git a/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4f595916f7 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.ecommerce.EcommerceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = EcommerceApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java index 4f4f6fb6af..d6fc1836c7 100644 --- a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java @@ -1,10 +1,27 @@ package com.baeldung.autoconfiguration; +import java.util.Arrays; +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureOrder; -import org.springframework.boot.autoconfigure.condition.*; +import org.springframework.boot.autoconfigure.condition.ConditionMessage; import org.springframework.boot.autoconfigure.condition.ConditionMessage.Style; -import org.springframework.context.annotation.*; +import org.springframework.boot.autoconfigure.condition.ConditionOutcome; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; +import org.springframework.boot.autoconfigure.condition.SpringBootCondition; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotatedTypeMetadata; @@ -14,11 +31,6 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.util.ClassUtils; -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; -import java.util.Arrays; -import java.util.Properties; - @Configuration @ConditionalOnClass(DataSource.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) diff --git a/spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..136ea2481f --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.autoconfiguration.example.AutoconfigurationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AutoconfigurationApplication.class) +@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index 519b36ce4f..08fdb1bdc9 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -2,3 +2,5 @@ - [Bootstrap a Simple Application using Spring Boot](http://www.baeldung.com/spring-boot-start) - [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) - [Thin JARs with Spring Boot](http://www.baeldung.com/spring-boot-thin-jar) +- [Deploying a Spring Boot Application to Cloud Foundry](https://www.baeldung.com/spring-boot-app-deploy-to-cloud-foundry) +- [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine) diff --git a/spring-boot-bootstrap/cloudfoundry/manifest.yml b/spring-boot-bootstrap/cloudfoundry/manifest.yml new file mode 100755 index 0000000000..80fce8ff4b --- /dev/null +++ b/spring-boot-bootstrap/cloudfoundry/manifest.yml @@ -0,0 +1,10 @@ +--- +applications: +- name: spring-boot-bootstrap + memory: 768M + random-route: true + path: ../target/spring-boot-bootstrap-cf.jar + env: + SPRING_PROFILES_ACTIVE: cloud,mysql + services: + - spring-bootstrap-db diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 5868694e5b..b5bcc587b1 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -1,6 +1,6 @@ + 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 spring-boot-bootstrap @@ -14,6 +14,17 @@ 0.0.1-SNAPSHOT ../parent-boot-2 + + + + org.springframework.cloud + spring-cloud-dependencies + Finchley.SR1 + pom + import + + + @@ -28,10 +39,22 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.boot + spring-boot-starter-cloud-connectors + com.h2database h2 + + mysql + mysql-connector-java + org.springframework.boot spring-boot-starter-security @@ -55,6 +78,82 @@ + + cloud-gcp + + + org.springframework.cloud + spring-cloud-gcp-starter + 1.0.0.RELEASE + + + org.springframework.cloud + spring-cloud-gcp-starter-sql-mysql + 1.0.0.RELEASE + + + + ${project.name}-gcp + + + src/main/resources + + **/logback.xml + + + + + + com.google.cloud.tools + appengine-maven-plugin + 1.3.2 + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + cloudfoundry + + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.boot + spring-boot-starter-cloud-connectors + + + + ${project.name}-cf + + + src/main/resources + + **/logback.xml + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/config/*.java + + + + + + autoconfiguration @@ -112,7 +211,19 @@ - + + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/*.java + + + + + 4.0.0 diff --git a/spring-boot-bootstrap/src/main/appengine/app.yaml b/spring-boot-bootstrap/src/main/appengine/app.yaml new file mode 100644 index 0000000000..a65ec6533a --- /dev/null +++ b/spring-boot-bootstrap/src/main/appengine/app.yaml @@ -0,0 +1,19 @@ +runtime: java +env: flex +runtime_config: + jdk: openjdk8 +env_variables: + SPRING_PROFILES_ACTIVE: "gcp,mysql" +handlers: +- url: /.* + script: this field is required, but ignored +resources: + cpu: 2 + memory_gb: 2 + disk_size_gb: 10 + volumes: + - name: ramdisk1 + volume_type: tmpfs + size_gb: 0.5 +manual_scaling: + instances: 1 diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java b/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java new file mode 100755 index 0000000000..b9f9598ca3 --- /dev/null +++ b/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java @@ -0,0 +1,19 @@ +package org.baeldung.cloud.config; + +import org.springframework.cloud.config.java.AbstractCloudConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import javax.sql.DataSource; + +@Configuration +@Profile("cloud") +public class CloudDataSourceConfig extends AbstractCloudConfig { + + @Bean + public DataSource dataSource() { + return connectionFactory().dataSource(); + } + +} diff --git a/spring-boot-bootstrap/src/main/resources/application-gcp.properties b/spring-boot-bootstrap/src/main/resources/application-gcp.properties new file mode 100644 index 0000000000..3dd11eeb8c --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/application-gcp.properties @@ -0,0 +1,3 @@ +spring.cloud.gcp.sql.instance-connection-name=baeldung-spring-boot-bootstrap:europe-west2:baeldung-spring-boot-bootstrap-db +spring.cloud.gcp.sql.database-name=baeldung_bootstrap_db +spring.cloud.gcp.logging.enabled=true \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/application-local.properties b/spring-boot-bootstrap/src/main/resources/application-local.properties new file mode 100644 index 0000000000..8c1c677988 --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/application-local.properties @@ -0,0 +1,20 @@ +server.port = 8081 + +spring.application.name = Bootstrap Spring Boot + +spring.thymeleaf.cache = false +spring.thymeleaf.enabled=true +spring.thymeleaf.prefix=classpath:/templates/ +spring.thymeleaf.suffix=.html + +spring.security.user.name=john +spring.security.user.password=123 + +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +server.error.path=/error +server.error.whitelabel.enabled=false \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/application-mysql.properties b/spring-boot-bootstrap/src/main/resources/application-mysql.properties new file mode 100644 index 0000000000..a1823b5d7f --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/application-mysql.properties @@ -0,0 +1 @@ +spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/application.properties b/spring-boot-bootstrap/src/main/resources/application.properties index e50268d32c..d83166d843 100644 --- a/spring-boot-bootstrap/src/main/resources/application.properties +++ b/spring-boot-bootstrap/src/main/resources/application.properties @@ -1,19 +1,12 @@ -server.port = 8081 - -spring.application.name = Bootstrap Spring Boot - +server.port=${port:8080} +spring.application.name = Bootstrap Spring Cloud spring.thymeleaf.cache = false spring.thymeleaf.enabled=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html -spring.security.user.name=john -spring.security.user.password=123 - -spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE -spring.datasource.username=sa -spring.datasource.password= - server.error.path=/error -server.error.whitelabel.enabled=false \ No newline at end of file +server.error.whitelabel.enabled=false + +spring.jpa.generate-ddl=true +spring.jpa.hibernate.ddl-auto=update \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/logback-gcp.xml b/spring-boot-bootstrap/src/main/resources/logback-gcp.xml new file mode 100644 index 0000000000..9a9c1c633d --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/logback-gcp.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/spring-cloud-bootstrap.properties b/spring-boot-bootstrap/src/main/resources/spring-cloud-bootstrap.properties new file mode 100644 index 0000000000..6ba0b5ffcc --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/spring-cloud-bootstrap.properties @@ -0,0 +1 @@ +spring.cloud.appId=baeldung-spring-boot-bootstrap diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringCloudRestConfigIntegrationTest.java b/spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 85% rename from spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringCloudRestConfigIntegrationTest.java rename to spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 8cc30a32ab..9ae417a546 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringCloudRestConfigIntegrationTest.java +++ b/spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -7,9 +7,9 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class SpringCloudRestConfigIntegrationTest { +public class SpringContextIntegrationTest { + @Test public void contextLoads() { } - } diff --git a/camel-api/README.md b/spring-boot-camel/README.md similarity index 100% rename from camel-api/README.md rename to spring-boot-camel/README.md diff --git a/camel-api/pom.xml b/spring-boot-camel/pom.xml similarity index 90% rename from camel-api/pom.xml rename to spring-boot-camel/pom.xml index f04e8e34f7..19a0bec809 100644 --- a/camel-api/pom.xml +++ b/spring-boot-camel/pom.xml @@ -38,6 +38,12 @@ spring-boot-starter-web ${spring-boot-starter.version} + + org.springframework.boot + spring-boot-starter-test + ${spring-boot-starter.version} + test + diff --git a/camel-api/src/main/java/com/baeldung/camel/Application.java b/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java similarity index 100% rename from camel-api/src/main/java/com/baeldung/camel/Application.java rename to spring-boot-camel/src/main/java/com/baeldung/camel/Application.java diff --git a/camel-api/src/main/java/com/baeldung/camel/ExampleServices.java b/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java similarity index 100% rename from camel-api/src/main/java/com/baeldung/camel/ExampleServices.java rename to spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java diff --git a/camel-api/src/main/java/com/baeldung/camel/MyBean.java b/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java similarity index 100% rename from camel-api/src/main/java/com/baeldung/camel/MyBean.java rename to spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java diff --git a/camel-api/src/main/resources/application.properties b/spring-boot-camel/src/main/resources/application.properties similarity index 100% rename from camel-api/src/main/resources/application.properties rename to spring-boot-camel/src/main/resources/application.properties diff --git a/camel-api/src/main/resources/application.yml b/spring-boot-camel/src/main/resources/application.yml similarity index 100% rename from camel-api/src/main/resources/application.yml rename to spring-boot-camel/src/main/resources/application.yml diff --git a/camel-api/src/main/resources/logback.xml b/spring-boot-camel/src/main/resources/logback.xml similarity index 100% rename from camel-api/src/main/resources/logback.xml rename to spring-boot-camel/src/main/resources/logback.xml diff --git a/spring-boot-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6eee0abf1e --- /dev/null +++ b/spring-boot-camel/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.camel.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/javaxval/bin/.gitignore b/spring-boot-client/.gitignore similarity index 78% rename from javaxval/bin/.gitignore rename to spring-boot-client/.gitignore index 55a6bcf596..da7c2c5c0a 100644 --- a/javaxval/bin/.gitignore +++ b/spring-boot-client/.gitignore @@ -1,6 +1,5 @@ +/target/ +.settings/ .classpath .project -.settings/ -target/ - diff --git a/spring-boot-client/README.MD b/spring-boot-client/README.MD new file mode 100644 index 0000000000..8db48089a5 --- /dev/null +++ b/spring-boot-client/README.MD @@ -0,0 +1,7 @@ +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot) +- [A Java Client for a WebSockets API](http://www.baeldung.com/websockets-api-java-spring-client) \ No newline at end of file diff --git a/spring-boot-client/pom.xml b/spring-boot-client/pom.xml new file mode 100644 index 0000000000..fc89931f79 --- /dev/null +++ b/spring-boot-client/pom.xml @@ -0,0 +1,141 @@ + + 4.0.0 + com.baeldung + spring-boot-client + 0.0.1-SNAPSHOT + war + spring-boot-client + This is simple boot client application for Spring boot actuator test + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + org.junit.platform + junit-platform-launcher + ${junit-platform.version} + test + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter + + + com.google.guava + guava + ${guava.version} + + + org.springframework + spring-websocket + + + org.springframework + spring-messaging + + + + + + spring-boot-client + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + pl.project13.maven + git-commit-id-plugin + ${git-commit-id-plugin.version} + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + 18.0 + 1.2.0 + 2.2.4 + + + \ No newline at end of file diff --git a/spring-boot-client/src/main/java/org/baeldung/boot/Application.java b/spring-boot-client/src/main/java/org/baeldung/boot/Application.java new file mode 100644 index 0000000000..c1b6558b26 --- /dev/null +++ b/spring-boot-client/src/main/java/org/baeldung/boot/Application.java @@ -0,0 +1,14 @@ +package org.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +@SpringBootApplication +public class Application { + private static ApplicationContext applicationContext; + + public static void main(String[] args) { + applicationContext = SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/client/Details.java b/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/client/Details.java rename to spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java b/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java rename to spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java b/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/websocket/client/Message.java rename to spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java b/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java rename to spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java b/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java rename to spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java diff --git a/spring-boot-client/src/main/resources/logback.xml b/spring-boot-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/spring-boot-client/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java rename to spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java diff --git a/spring-boot-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..97debc5b63 --- /dev/null +++ b/spring-boot-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.boot.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java b/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java similarity index 91% rename from spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java rename to spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java index 37fc202e8a..71fb330663 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java @@ -1,23 +1,24 @@ package org.baeldung.boot.client; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.client.MockRestServiceServer; - import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; -import org.baeldung.boot.client.Details; -import org.baeldung.boot.client.DetailsServiceClient; +import org.baeldung.boot.Application; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.MockRestServiceServer; + +import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) @RestClientTest(DetailsServiceClient.class) public class DetailsServiceClientIntegrationTest { diff --git a/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c9f7220ab9 --- /dev/null +++ b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.parent.App; + +public class SpringContextIntegrationTest { + + @Test + public final void testMain() throws Exception { + App.main(new String[] {}); + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml index 9c2d85da86..5862bdd6c8 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml @@ -40,6 +40,13 @@ ${greeter.version} true + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9c8d825ea4 --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +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.greeter.autoconfigure.GreeterAutoConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = GreeterAutoConfiguration.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..23f285238b --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.greeter.sample.GreeterSampleApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GreeterSampleApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-h2/README.md b/spring-boot-h2/README.md new file mode 100644 index 0000000000..af5f395440 --- /dev/null +++ b/spring-boot-h2/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Access the Same In-Memory H2 Database in Multiple Spring Boot Applications](https://www.baeldung.com/spring-boot-access-h2-database-multiple-apps) diff --git a/spring-boot-h2/spring-boot-h2-database/.gitignore b/spring-boot-h2/spring-boot-h2-database/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/vaadin-spring/pom.xml b/spring-boot-h2/spring-boot-h2-database/pom.xml similarity index 51% rename from vaadin-spring/pom.xml rename to spring-boot-h2/spring-boot-h2-database/pom.xml index 09f79f2676..94f2293c34 100644 --- a/vaadin-spring/pom.xml +++ b/spring-boot-h2/spring-boot-h2-database/pom.xml @@ -1,22 +1,29 @@ - + 4.0.0 - com.baeldung - vaadin-spring - 0.1.0 + com.baeldung.h2db + spring-boot-h2-database + 0.0.1-SNAPSHOT + jar + + Demo Spring Boot applications that starts H2 in memory database - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + + UTF-8 + UTF-8 1.8 + + com.mycorp.starter.HelloWorldApplication @@ -24,15 +31,11 @@ org.springframework.boot spring-boot-starter-data-jpa - - com.vaadin - vaadin-spring-boot-starter - + com.h2database h2 - org.springframework.boot spring-boot-starter-test @@ -40,18 +43,6 @@ - - - - com.vaadin - vaadin-bom - 10.0.1 - pom - import - - - - @@ -60,5 +51,4 @@ - diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java new file mode 100644 index 0000000000..87a191554b --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java @@ -0,0 +1,14 @@ +package com.baeldung.h2db.auto.configuration; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication(scanBasePackages = "com.baeldung.h2db.auto-configuration") +public class AutoConfigurationDemo { + + public static void main(String[] args) { + SpringApplication.run(AutoConfigurationDemo.class, args); + } + +} diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java new file mode 100644 index 0000000000..7402312e1c --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java @@ -0,0 +1,53 @@ +package com.baeldung.h2db.demo.client; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Arrays; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +@SpringBootApplication +@ComponentScan("com.baeldung.h2db.demo.client") +public class ClientSpringBootApp { + + @Autowired + private JdbcTemplate jdbcTemplate; + + public static void main(String[] args) { + System.setProperty("spring.datasource.url","jdbc:h2:tcp://localhost:9091/mem:mydb"); + SpringApplication.run(ClientSpringBootApp.class, args); + } + + @PostConstruct + private void initDb() { + System.out.println("****** Inserting more sample data in the table: Employees ******"); + String sqlStatements[] = { + "insert into employees(first_name, last_name) values('Donald','Trump')", + "insert into employees(first_name, last_name) values('Barack','Obama')" + }; + + Arrays.asList(sqlStatements).stream().forEach(sql -> { + System.out.println(sql); + jdbcTemplate.execute(sql); + }); + + System.out.println(String.format("****** Fetching from table: %s ******", "Employees")); + jdbcTemplate.query("select id,first_name,last_name from employees", + new RowMapper() { + @Override + public Object mapRow(ResultSet rs, int i) throws SQLException { + System.out.println(String.format("id:%s,first_name:%s,last_name:%s", + rs.getString("id"), + rs.getString("first_name"), + rs.getString("last_name"))); + return null; + } + }); + } +} diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java new file mode 100644 index 0000000000..e75b42a934 --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java @@ -0,0 +1,61 @@ +package com.baeldung.h2db.demo.server; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Arrays; +import javax.annotation.PostConstruct; +import org.h2.tools.Server; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +@SpringBootApplication +@ComponentScan("com.baeldung.h2db.demo.server") +public class SpringBootApp { + + @Autowired + private JdbcTemplate jdbcTemplate; + + public static void main(String[] args) { + SpringApplication.run(SpringBootApp.class, args); + } + + @PostConstruct + private void initDb() { + System.out.println(String.format("****** Creating table: %s, and Inserting test data ******", "Employees")); + + String sqlStatements[] = { + "drop table employees if exists", + "create table employees(id serial,first_name varchar(255),last_name varchar(255))", + "insert into employees(first_name, last_name) values('Eugen','Paraschiv')", + "insert into employees(first_name, last_name) values('Scott','Tiger')" + }; + + Arrays.asList(sqlStatements).stream().forEach(sql -> { + System.out.println(sql); + jdbcTemplate.execute(sql); + }); + + System.out.println(String.format("****** Fetching from table: %s ******", "Employees")); + jdbcTemplate.query("select id,first_name,last_name from employees", + new RowMapper() { + @Override + public Object mapRow(ResultSet rs, int i) throws SQLException { + System.out.println(String.format("id:%s,first_name:%s,last_name:%s", + rs.getString("id"), + rs.getString("first_name"), + rs.getString("last_name"))); + return null; + } + }); + } + + @Bean(initMethod = "start", destroyMethod = "stop") + public Server inMemoryH2DatabaseServer() throws SQLException { + return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9091"); + } +} diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties b/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties new file mode 100644 index 0000000000..5e425a3550 --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.datasource.url=jdbc:h2:mem:mydb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=create +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console +debug=true \ No newline at end of file diff --git a/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f48199d4e8 --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.h2db.demo.ClientSpringBootApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ClientSpringBootApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-jasypt/pom.xml b/spring-boot-jasypt/pom.xml index 8b7a475824..de0df92678 100644 --- a/spring-boot-jasypt/pom.xml +++ b/spring-boot-jasypt/pom.xml @@ -4,11 +4,9 @@ 4.0.0 com.example.jasypt - JasyptDemo - 0.0.1-SNAPSHOT + spring-boot-jasypt jar - - JasyptDemo + spring-boot-jasypt Demo project for Spring Boot @@ -53,9 +51,6 @@ - UTF-8 - UTF-8 - 1.8 2.0.0 diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java similarity index 94% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java rename to spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java index 58c2dc7bb2..c24cfe6efa 100644 --- a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.jasypt.Main; @RunWith(SpringRunner.class) @SpringBootTest(classes = {Main.class}) -public class CustomJasyptTest { +public class CustomJasyptIntegrationTest { @Autowired ApplicationContext appCtx; diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java similarity index 95% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java rename to spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java index f9b66b5044..e8dda73b4a 100644 --- a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleIntegrationTest.java @@ -13,7 +13,7 @@ import com.baeldung.jasypt.simple.PropertyServiceForJasyptSimple; @RunWith(SpringRunner.class) @SpringBootTest -public class JasyptSimpleTest { +public class JasyptSimpleIntegrationTest { @Autowired ApplicationContext appCtx; diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java similarity index 95% rename from spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java rename to spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java index d246c21036..5f5d409ab9 100644 --- a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.jasypt.starter.PropertyServiceForJasyptStarter; @RunWith(SpringRunner.class) @SpringBootTest -public class JasyptWithStarterTest { +public class JasyptWithStarterIntegrationTest { @Autowired ApplicationContext appCtx; diff --git a/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..dce3819a26 --- /dev/null +++ b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.jasypt.Main; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Main.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7367568611 --- /dev/null +++ b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.keycloak.SpringBoot; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBoot.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-logging-log4j2/README.md b/spring-boot-logging-log4j2/README.md index 7676bd1919..305957ed8d 100644 --- a/spring-boot-logging-log4j2/README.md +++ b/spring-boot-logging-log4j2/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Logging in Spring Boot](http://www.baeldung.com/spring-boot-logging) +- [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml new file mode 100644 index 0000000000..c3bad74352 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + disabling-console-jul + + + com.baeldung + disabling-console-logging + 0.0.1-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.slf4j + jul-to-slf4j + + + org.slf4j + slf4j-simple + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java new file mode 100644 index 0000000000..c9187e9ace --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java @@ -0,0 +1,11 @@ +package com.baeldung.springbootlogging.disablingconsole.jul.properties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DisablingConsoleJulApp { + public static void main(String[] args) { + SpringApplication.run(DisablingConsoleJulApp.class, args); + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java new file mode 100644 index 0000000000..e33089ed36 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java @@ -0,0 +1,19 @@ +package com.baeldung.springbootlogging.disablingconsole.jul.properties.controllers; + +import java.time.LocalTime; +import java.util.logging.Logger; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class DisabledConsoleRestController { + + private static final Logger LOG = Logger.getLogger(DisabledConsoleRestController.class.getName()); + + @GetMapping("/disabled-console-jul-properties") + public String logTime() { + LOG.info("Current time: " + LocalTime.now()); + return "finished!"; + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/application.properties b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/application.properties new file mode 100644 index 0000000000..d81eed95d3 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/application.properties @@ -0,0 +1 @@ +logging.file=true \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/logging.properties b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/logging.properties new file mode 100644 index 0000000000..0136354868 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/logging.properties @@ -0,0 +1,4 @@ +handlers= java.util.logging.FileHandler + +java.util.logging.FileHandler.pattern=baeldung.log +java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml new file mode 100644 index 0000000000..f9b34ec7d9 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml @@ -0,0 +1,42 @@ + + 4.0.0 + disabling-console-log4j2 + + + com.baeldung + disabling-console-logging + 0.0.1-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java new file mode 100644 index 0000000000..ae59f3b3e1 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java @@ -0,0 +1,11 @@ +package com.baeldung.springbootlogging.disablingconsole.log4j2.xml; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DisablingConsoleLog4j2App { + public static void main(String[] args) { + SpringApplication.run(DisablingConsoleLog4j2App.class, args); + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java new file mode 100644 index 0000000000..f6485b63d4 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java @@ -0,0 +1,20 @@ +package com.baeldung.springbootlogging.disablingconsole.log4j2.xml.controllers; + +import java.time.LocalTime; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class DisabledConsoleRestController { + + private static final Logger LOG = LoggerFactory.getLogger(DisabledConsoleRestController.class); + + @GetMapping("/disabled-console-log4j2-xml") + public String logTime() { + LOG.info("Current time: {}", LocalTime.now()); + return "finished!"; + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/resources/log4j2.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..20975f40d9 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/pom.xml new file mode 100644 index 0000000000..6f2170390b --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/pom.xml @@ -0,0 +1,9 @@ + + 4.0.0 + + com.baeldung + disabling-console-logging + 0.0.1-SNAPSHOT + + disabling-console-logback + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java new file mode 100644 index 0000000000..9b38d42477 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java @@ -0,0 +1,11 @@ +package com.baeldung.springbootlogging.disablingconsole.logback.xml; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DisablingConsoleLogbackApp { + public static void main(String[] args) { + SpringApplication.run(DisablingConsoleLogbackApp.class, args); + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java new file mode 100644 index 0000000000..e1d6b1d45e --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java @@ -0,0 +1,20 @@ +package com.baeldung.springbootlogging.disablingconsole.logback.xml.controllers; + +import java.time.LocalTime; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class DisabledConsoleRestController { + + private static final Logger LOG = LoggerFactory.getLogger(DisabledConsoleRestController.class); + + @GetMapping("/disabled-console-logback-xml") + public String logTime() { + LOG.info("Current time: {}", LocalTime.now()); + return "finished!"; + } +} diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/application.properties b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/application.properties new file mode 100644 index 0000000000..70c2f97194 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/application.properties @@ -0,0 +1,7 @@ +logging.file=disabled-console.log + +### we could potentially 'disable' console logging by setting a blank log pattern: +#logging.pattern.console= + +### or disable the logs completely by setting the root logging level as 'OFF': +#logging.level.root=OFF diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/logback-spring.xml b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/logback-spring.xml new file mode 100644 index 0000000000..5c751e994f --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/logback-spring.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/pom.xml b/spring-boot-logging-log4j2/disabling-console-logging/pom.xml new file mode 100644 index 0000000000..39a4a40f12 --- /dev/null +++ b/spring-boot-logging-log4j2/disabling-console-logging/pom.xml @@ -0,0 +1,19 @@ + + 4.0.0 + disabling-console-logging + pom + Projects for Disabling Spring Boot Console Logging tutorials + + + com.baeldung + spring-boot-logging-log4j2 + 0.0.1-SNAPSHOT + + + + disabling-console-logback + disabling-console-log4j2 + disabling-console-jul + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml index 61f949b820..7caf1e8690 100644 --- a/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/pom.xml @@ -3,11 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-boot-logging-log4j2 - 0.0.1-SNAPSHOT - jar - Demo project for Spring Boot Logging with Log4J2 + pom + Projects for Spring Boot Logging tutorials parent-boot-2 @@ -20,16 +18,6 @@ org.springframework.boot spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.springframework.boot - spring-boot-starter-log4j2 @@ -38,6 +26,11 @@ test + + + spring-boot-logging-log4j2-app + disabling-console-logging + @@ -48,10 +41,4 @@ - - UTF-8 - UTF-8 - 1.8 - - diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml new file mode 100644 index 0000000000..571794167e --- /dev/null +++ b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + + spring-boot-logging-log4j2-app + jar + Demo project for Spring Boot Logging with Log4J2 + + + spring-boot-logging-log4j2 + com.baeldung + 0.0.1-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + diff --git a/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LoggingController.java b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/LoggingController.java similarity index 100% rename from spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LoggingController.java rename to spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/LoggingController.java diff --git a/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java similarity index 100% rename from spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java rename to spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/application.properties b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-logging-log4j2/src/main/resources/log4j2-spring.xml b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/log4j2-spring.xml similarity index 100% rename from spring-boot-logging-log4j2/src/main/resources/log4j2-spring.xml rename to spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/log4j2-spring.xml diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2d46b21ba5 --- /dev/null +++ b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.springbootlogging.SpringBootLoggingApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootLoggingApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-mvc/README.md b/spring-boot-mvc/README.md index d1987e105f..b46dbe3bae 100644 --- a/spring-boot-mvc/README.md +++ b/spring-boot-mvc/README.md @@ -1,3 +1,10 @@ ### Relevant Articles: - [Guide to the Favicon in Spring Boot](http://www.baeldung.com/spring-boot-favicon) +- [Custom Validation MessageSource in Spring Boot](https://www.baeldung.com/spring-custom-validation-message-source) +- [Spring Boot Annotations](http://www.baeldung.com/spring-boot-annotations) +- [Spring Scheduling Annotations](http://www.baeldung.com/spring-scheduling-annotations) +- [Spring Web Annotations](http://www.baeldung.com/spring-mvc-annotations) +- [Spring Core Annotations](http://www.baeldung.com/spring-core-annotations) +- [Display RSS Feed with Spring MVC](http://www.baeldung.com/spring-mvc-rss-feed) + diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index d0fce26bb5..65d23ebfc6 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -2,12 +2,10 @@ 4.0.0 - com.baeldung spring-boot-mvc - 0.0.1-SNAPSHOT jar spring-boot-mvc - Demo project for Spring Boot + Module For Spring Boot MVC parent-boot-2 @@ -21,6 +19,16 @@ org.springframework.boot spring-boot-starter-web + + org.apache.tomcat.embed + tomcat-embed-jasper + + + + org.glassfish + javax.faces + 2.3.7 + org.springframework.boot @@ -32,6 +40,13 @@ org.springframework.boot spring-boot-starter-validation + + + + com.rometools + rome + ${rome.version} + @@ -39,14 +54,18 @@ org.springframework.boot spring-boot-maven-plugin + + com.baeldung.springbootmvc.SpringBootMvcApplication + JAR + - UTF-8 - UTF-8 - 1.8 + + 1.10.0 + com.baeldung.springbootmvc.SpringBootMvcApplication diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Bike.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Bike.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Bike.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Bike.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Biker.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Biker.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Biker.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Biker.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Car.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Car.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Car.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Car.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CarMechanic.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CarMechanic.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/CarMechanic.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/CarMechanic.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CarUtility.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CarUtility.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/CarUtility.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/CarUtility.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomException.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomException.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/CustomException.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomException.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseWithBuilderController.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseWithBuilderController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseWithBuilderController.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseWithBuilderController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Driver.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Driver.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Driver.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Driver.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Engine.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Engine.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Engine.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Engine.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Vehicle.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/Vehicle.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/Vehicle.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/Vehicle.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleController.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleController.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRepository.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRepository.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRepository.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRepository.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRestController.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRestController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRestController.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleRestController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleService.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleService.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleService.java rename to spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleService.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java new file mode 100644 index 0000000000..030216b747 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanA.java @@ -0,0 +1,12 @@ +package com.baeldung.nosuchbeandefinitionexception; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class BeanA { + + @Autowired + BeanB dependency; + +} \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java new file mode 100644 index 0000000000..f0cc263504 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/BeanB.java @@ -0,0 +1,5 @@ +package com.baeldung.nosuchbeandefinitionexception; + +public class BeanB { + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java new file mode 100644 index 0000000000..8709cf85ac --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/nosuchbeandefinitionexception/NoSuchBeanDefinitionDemoApp.java @@ -0,0 +1,12 @@ +package com.baeldung.nosuchbeandefinitionexception; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class NoSuchBeanDefinitionDemoApp { + + public static void main(String[] args) { + SpringApplication.run(NoSuchBeanDefinitionDemoApp.class, args); + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/rss/RssFeedApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedApplication.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/rss/RssFeedApplication.java rename to spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedApplication.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/rss/RssFeedController.java b/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/rss/RssFeedController.java rename to spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/rss/RssFeedView.java b/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedView.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/rss/RssFeedView.java rename to spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedView.java diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java new file mode 100644 index 0000000000..5b4250d5e3 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/JsfApplication.java @@ -0,0 +1,31 @@ +package com.baeldung.springbootmvc.jsfapplication; + +import javax.faces.webapp.FacesServlet; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +import com.baeldung.springbootmvc.jsfapplication.controller.JsfController; +import com.baeldung.springbootmvc.jsfapplication.model.TodoDao; +import com.baeldung.springbootmvc.jsfapplication.service.TodoService; + +@SpringBootApplication +@ComponentScan(basePackageClasses = { JsfController.class, TodoDao.class, TodoService.class }) +public class JsfApplication extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(JsfApplication.class, args); + } + + @Bean + public ServletRegistrationBean servletRegistrationBean() { + FacesServlet servlet = new FacesServlet(); + ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.jsf"); + return servletRegistrationBean; + } + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java new file mode 100644 index 0000000000..a9d21175c7 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/controller/JsfController.java @@ -0,0 +1,19 @@ +package com.baeldung.springbootmvc.jsfapplication.controller; + +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Scope(value = "session") +@Component(value = "jsfController") +public class JsfController { + + public String loadTodoPage() { + checkPermission(); + return "/todo.xhtml"; + } + + private void checkPermission() { + // Details omitted + } + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java new file mode 100644 index 0000000000..0b97c5a78e --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Dao.java @@ -0,0 +1,17 @@ +package com.baeldung.springbootmvc.jsfapplication.model; + +import java.util.Collection; +import java.util.Optional; + +public interface Dao { + + Optional get(int id); + + Collection getAll(); + + int save(T t); + + void update(T t); + + void delete(T t); +} \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java new file mode 100644 index 0000000000..7aa8480f43 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/Todo.java @@ -0,0 +1,32 @@ +package com.baeldung.springbootmvc.jsfapplication.model; + +public class Todo { + + private int id; + private String message; + private int priority; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java new file mode 100644 index 0000000000..96d44474af --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java @@ -0,0 +1,48 @@ +package com.baeldung.springbootmvc.jsfapplication.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Component; + +@Component +public class TodoDao implements Dao { + + private List todoList = new ArrayList<>(); + + @Override + public Optional get(int id) { + return Optional.ofNullable(todoList.get(id)); + } + + @Override + public Collection getAll() { + return todoList.stream() + .filter(Objects::nonNull) + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); + } + + @Override + public int save(Todo todo) { + todoList.add(todo); + int index = todoList.size() - 1; + todo.setId(index); + return index; + } + + @Override + public void update(Todo todo) { + todoList.set(todo.getId(), todo); + } + + @Override + public void delete(Todo todo) { + todoList.set(todo.getId(), null); + } + +} \ No newline at end of file diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java new file mode 100644 index 0000000000..89af3c66b9 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/service/TodoService.java @@ -0,0 +1,50 @@ +package com.baeldung.springbootmvc.jsfapplication.service; + +import java.util.Collection; +import java.util.Comparator; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import com.baeldung.springbootmvc.jsfapplication.model.Dao; +import com.baeldung.springbootmvc.jsfapplication.model.Todo; + +@Scope(value = "session") +@Component(value = "todoService") +public class TodoService { + + @Autowired + private Dao todoDao; + private Todo todo = new Todo(); + + public void save() { + todoDao.save(todo); + todo = new Todo(); + } + + public Collection getAllTodo() { + return todoDao.getAll(); + } + + public Collection getAllTodoSortedByPriority() { + return todoDao.getAll() + .stream() + .sorted(Comparator.comparingInt(Todo::getId)) + .collect(Collectors.toList()); + } + + public int saveTodo(Todo todo) { + validate(todo); + return todoDao.save(todo); + } + + private void validate(Todo todo) { + // Details omitted + } + + public Todo getTodo() { + return todo; + } +} diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml b/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml new file mode 100644 index 0000000000..9e31a2e09d --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/WEB-INF/faces-config.xml @@ -0,0 +1,9 @@ + + + + org.springframework.web.jsf.el.SpringBeanFacesELResolver + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml b/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..e0cd4d8850 --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + + Faces Servlet + javax.faces.webapp.FacesServlet + 1 + + + Faces Servlet + *.jsf + + + com.sun.faces.forceLoadConfiguration + true + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/index.xhtml b/spring-boot-mvc/src/main/webapp/index.xhtml new file mode 100644 index 0000000000..40042b812c --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/index.xhtml @@ -0,0 +1,20 @@ + + + + + TO-DO application + + +
    +

    Welcome in the TO-DO application!

    +

    + This is a static message rendered from xhtml. + + + +

    +
    +
    +
    \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/todo.xhtml b/spring-boot-mvc/src/main/webapp/todo.xhtml new file mode 100644 index 0000000000..426e101908 --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/todo.xhtml @@ -0,0 +1,38 @@ + + + + + TO-DO application + + +
    +
    + List of TO-DO items +
    + + + Message + #{item.message} + + + Priority + #{item.priority} + + +
    +
    +
    + Add new to-do item: +
    + + + + + + + +
    +
    +
    \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/rss/RssFeedUnitTest.java b/spring-boot-mvc/src/test/java/com/baeldung/rss/RssFeedUnitTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/rss/RssFeedUnitTest.java rename to spring-boot-mvc/src/test/java/com/baeldung/rss/RssFeedUnitTest.java diff --git a/spring-boot-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6ed93e8c44 --- /dev/null +++ b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.springbootmvc.SpringBootMvcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootMvcApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 223fe72bd5..57779c3f8e 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-boot-ops - 0.0.1-SNAPSHOT war spring-boot-ops Demo project for Spring Boot @@ -19,10 +17,6 @@ - - org.springframework.boot spring-boot-starter-web @@ -95,13 +89,8 @@ - ${artifactId} + ${project.artifactId} - - org.springframework.boot - spring-boot-maven-plugin - - org.springframework.boot spring-boot-maven-plugin diff --git a/spring-boot-persistence/README.MD b/spring-boot-persistence/README.MD index 3fe6eb62c8..6cf172426a 100644 --- a/spring-boot-persistence/README.MD +++ b/spring-boot-persistence/README.MD @@ -1,3 +1,6 @@ ### Relevant Articles: - [Spring Boot with Multiple SQL Import Files](http://www.baeldung.com/spring-boot-sql-import-files) +- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source) +- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) +- [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool) diff --git a/spring-boot-persistence/pom.xml b/spring-boot-persistence/pom.xml index 60e6689e31..08989edfa9 100644 --- a/spring-boot-persistence/pom.xml +++ b/spring-boot-persistence/pom.xml @@ -1,53 +1,75 @@ - + + 4.0.0 + com.baeldung spring-boot-persistence - 0.0.1-SNAPSHOT - jar - spring-boot-persistence - This is a simple Spring Data Repositories test - + 0.1.0 + parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 - + org.springframework.boot spring-boot-starter-data-jpa + + + com.zaxxer + HikariCP + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.apache.tomcat + tomcat-jdbc + ${tomcat-jdbc.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} com.h2database h2 - - - org.springframework.boot - spring-boot-starter + ${h2database.version} + runtime - + + + UTF-8 + 1.8 + 8.0.12 + 9.0.10 + 1.4.197 + + spring-boot-persistence - - src/main/resources - true - + + src/main/resources + true + - org.apache.maven.plugins - maven-war-plugin - - - pl.project13.maven - git-commit-id-plugin + org.springframework.boot + spring-boot-maven-plugin - - \ No newline at end of file + diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java b/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java similarity index 73% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java rename to spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java index 439c6cb602..ef90714347 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java +++ b/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java @@ -1,11 +1,10 @@ -package org.baeldung.config; +package com.baeldung.boot.config; import java.util.Properties; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; -import org.baeldung.extended.persistence.dao.ExtendedRepositoryImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -19,10 +18,10 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = "org.baeldung.extended.persistence.dao", repositoryBaseClass = ExtendedRepositoryImpl.class) -@PropertySource("persistence-student-h2.properties") +@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.repository" }) +@PropertySource("classpath:persistence-generic-entity.properties") @EnableTransactionManagement -public class StudentJPAH2Config { +public class H2JpaConfig { @Autowired private Environment env; @@ -42,15 +41,15 @@ public class StudentJPAH2Config { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.inmemory.persistence.model" }); + em.setPackagesToScan(new String[] { "org.baeldung.boot.domain" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; } @Bean - JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { - JpaTransactionManager transactionManager = new JpaTransactionManager(); + JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager; } @@ -61,9 +60,8 @@ public class StudentJPAH2Config { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); return hibernateProperties; } + } diff --git a/spring-boot-persistence/src/main/java/com/baeldung/domain/Country.java b/spring-boot-persistence/src/main/java/com/baeldung/domain/Country.java new file mode 100644 index 0000000000..e6a88c7121 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/domain/Country.java @@ -0,0 +1,36 @@ +package com.baeldung.domain; + +import static javax.persistence.GenerationType.IDENTITY; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Country { + + @Id + @GeneratedValue(strategy = IDENTITY) + private Integer id; + + @Column(nullable = false) + private String name; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java new file mode 100644 index 0000000000..ff37442cd4 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java @@ -0,0 +1,22 @@ +package com.baeldung.tomcatconnectionpool.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@SpringBootApplication +@EnableAutoConfiguration +@ComponentScan(basePackages={"com.baeldung.tomcatconnectionpool.application"}) +@EnableJpaRepositories(basePackages="com.baeldung.tomcatconnectionpool.application.repositories") +@EnableTransactionManagement +@EntityScan(basePackages="com.baeldung.tomcatconnectionpool.application.entities") +public class SpringBootConsoleApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootConsoleApplication.class); + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java new file mode 100644 index 0000000000..4003d5aca9 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java @@ -0,0 +1,53 @@ +package com.baeldung.tomcatconnectionpool.application.entities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "customers") +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + @Column(name = "first_name") + private String firstName; + @Column(name = "last_name") + private String lastName; + + public Customer() {} + + public Customer(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public long getId() { + return id; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + @Override + public String toString() { + return "Customer{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + '}'; + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java new file mode 100644 index 0000000000..770906439c --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.tomcatconnectionpool.application.repositories; + +import com.baeldung.tomcatconnectionpool.application.entities.Customer; +import java.util.List; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends CrudRepository { + + List findByLastName(String lastName); +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java new file mode 100644 index 0000000000..9666bac5a5 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java @@ -0,0 +1,37 @@ +package com.baeldung.tomcatconnectionpool.application.runners; + +import com.baeldung.tomcatconnectionpool.application.entities.Customer; +import com.baeldung.tomcatconnectionpool.application.repositories.CustomerRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +@Component +public class CommandLineCrudRunner implements CommandLineRunner { + + private static final Logger logger = LoggerFactory.getLogger(CommandLineCrudRunner.class); + + @Autowired + private CustomerRepository customerRepository; + + @Override + public void run(String... args) throws Exception { + customerRepository.save(new Customer("John", "Doe")); + customerRepository.save(new Customer("Jennifer", "Wilson")); + + logger.info("Customers found with findAll():"); + customerRepository.findAll().forEach(c -> logger.info(c.toString())); + + logger.info("Customer found with findById(1L):"); + Customer customer = customerRepository.findById(1L) + .orElseGet(() -> new Customer("Non-existing customer", "")); + logger.info(customer.toString()); + + logger.info("Customer found with findByLastName('Wilson'):"); + customerRepository.findByLastName("Wilson").forEach(c -> { + logger.info(c.toString()); + }); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/domain/GenericEntity.java rename to spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java rename to spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java diff --git a/spring-boot-persistence/src/main/resources/application.properties b/spring-boot-persistence/src/main/resources/application.properties index e69de29bb2..303ce33c25 100644 --- a/spring-boot-persistence/src/main/resources/application.properties +++ b/spring-boot-persistence/src/main/resources/application.properties @@ -0,0 +1,16 @@ +spring.datasource.tomcat.initial-size=15 +spring.datasource.tomcat.max-wait=20000 +spring.datasource.tomcat.max-active=50 +spring.datasource.tomcat.max-idle=15 +spring.datasource.tomcat.min-idle=8 +spring.datasource.tomcat.default-auto-commit=true +spring.datasource.url=jdbc:h2:mem:test +spring.datasource.username=root +spring.datasource.password= +spring.datasource.driver-class-name=org.h2.Driver + +spring.jpa.show-sql=false +spring.jpa.hibernate.ddl-auto=update +spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect +spring.jpa.properties.hibernate.id.new_generator_mappings=false diff --git a/spring-boot-persistence/src/main/resources/data.sql b/spring-boot-persistence/src/main/resources/data.sql new file mode 100644 index 0000000000..feef02b6cf --- /dev/null +++ b/spring-boot-persistence/src/main/resources/data.sql @@ -0,0 +1,10 @@ +insert into users values (1, 'Alex', 1); +insert into users values (2, 'Bob', 1); +insert into users values (3, 'John', 0); +insert into users values (4, 'Harry', 0); +insert into users values (5, 'Smith', 1); + +INSERT INTO country (name) VALUES ('India'); +INSERT INTO country (name) VALUES ('Brazil'); +INSERT INTO country (name) VALUES ('USA'); +INSERT INTO country (name) VALUES ('Italy'); \ No newline at end of file diff --git a/spring-boot-persistence/src/main/resources/persistence-generic-entity.properties b/spring-boot-persistence/src/main/resources/persistence-generic-entity.properties new file mode 100644 index 0000000000..b19304cb1f --- /dev/null +++ b/spring-boot-persistence/src/main/resources/persistence-generic-entity.properties @@ -0,0 +1,8 @@ +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass=sa + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop diff --git a/spring-boot-persistence/src/main/resources/schema.sql b/spring-boot-persistence/src/main/resources/schema.sql new file mode 100644 index 0000000000..4cfc8a7927 --- /dev/null +++ b/spring-boot-persistence/src/main/resources/schema.sql @@ -0,0 +1,15 @@ +drop table if exists USERS; +drop table if exists country; + +create table USERS( + ID int not null AUTO_INCREMENT, + NAME varchar(100) not null, + STATUS int, + PRIMARY KEY ( ID ) +); + +CREATE TABLE country ( + id INTEGER NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + PRIMARY KEY (id) +); \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java similarity index 91% rename from spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java rename to spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java index 290cfbe081..6479e90113 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java +++ b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java @@ -1,7 +1,8 @@ -package org.baeldung; +package com.baeldung; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; -import org.baeldung.boot.Application; -import org.baeldung.boot.config.H2JpaConfig; import org.baeldung.boot.domain.GenericEntity; import org.baeldung.boot.repository.GenericEntityRepository; import org.junit.Test; @@ -10,8 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import com.baeldung.boot.config.H2JpaConfig; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = { Application.class, H2JpaConfig.class }) diff --git a/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java new file mode 100644 index 0000000000..eef9ebe953 --- /dev/null +++ b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.baeldung.boot.domain.GenericEntity; +import org.baeldung.boot.repository.GenericEntityRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringBootJPAIntegrationTest { + @Autowired + private GenericEntityRepository genericEntityRepository; + + @Test + public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() { + GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test")); + GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null); + assertNotNull(foundEntity); + assertEquals(genericEntity.getValue(), foundEntity.getValue()); + } +} \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java similarity index 95% rename from spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java rename to spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java index 128a05f103..4c68f1d4a0 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java +++ b/spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java @@ -1,6 +1,8 @@ -package org.baeldung; +package com.baeldung; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; -import org.baeldung.boot.Application; import org.baeldung.boot.domain.GenericEntity; import org.baeldung.boot.repository.GenericEntityRepository; import org.baeldung.config.H2TestProfileJPAConfig; @@ -11,9 +13,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - @RunWith(SpringRunner.class) @SpringBootTest(classes = { Application.class, H2TestProfileJPAConfig.class }) @ActiveProfiles("test") diff --git a/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java new file mode 100644 index 0000000000..c68e137fb0 --- /dev/null +++ b/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.tomcatconnectionpool.test.application; + +import javax.sql.DataSource; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.*; +import org.springframework.boot.test.context.SpringBootTest; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringBootTomcatConnectionPoolIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenTomcatConnectionPoolInstance_whenCheckedPoolClassName_thenCorrect() { + assertThat(dataSource.getClass().getName()).isEqualTo("org.apache.tomcat.jdbc.pool.DataSource"); + } +} diff --git a/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java b/spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java similarity index 94% rename from spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java rename to spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java index d0b92a7a93..7f962e1417 100644 --- a/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java +++ b/spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = { "org.baeldung.repository", "org.baeldung.boot.repository", "org.baeldung.boot.boottest" }) +@EnableJpaRepositories(basePackages = { "org.baeldung.repository", "org.baeldung.boot.repository" }) @EnableTransactionManagement public class H2TestProfileJPAConfig { @@ -41,7 +41,7 @@ public class H2TestProfileJPAConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain", "org.baeldung.boot.boottest", "org.baeldung.model" }); + em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-boot-persistence/src/test/resources/application.properties b/spring-boot-persistence/src/test/resources/application.properties index a5d09db840..a5c1d983cf 100644 --- a/spring-boot-persistence/src/test/resources/application.properties +++ b/spring-boot-persistence/src/test/resources/application.properties @@ -13,4 +13,4 @@ hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql -spring.datasource.data=import_*_users.sql,import_articles.sql \ No newline at end of file +spring.datasource.data=import_*_users.sql \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml index 958a07a86b..ab22c5ad30 100644 --- a/spring-boot-property-exp/property-exp-custom-config/pom.xml +++ b/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -20,7 +20,14 @@ spring-boot-starter ${spring-boot.version} + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + diff --git a/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6dd3419d39 --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.propertyexpansion.SpringBootPropertyExpansionApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6dd3419d39 --- /dev/null +++ b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.propertyexpansion.SpringBootPropertyExpansionApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-security/README.md b/spring-boot-security/README.md index a79e7de610..30a3218672 100644 --- a/spring-boot-security/README.md +++ b/spring-boot-security/README.md @@ -9,3 +9,5 @@ ### Relevant Articles: - [Spring Boot Security Auto-Configuration](http://www.baeldung.com/spring-boot-security-autoconfiguration) +- [Spring Security for Spring Boot Integration Tests](https://www.baeldung.com/spring-security-integration-tests) +- [Introduction to Spring Security Taglibs](https://www.baeldung.com/spring-security-taglibs) diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index 12f51eec94..6bc013d1ed 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - com.baeldung spring-boot-security 0.0.1-SNAPSHOT jar @@ -28,10 +27,6 @@ - - - - org.springframework.boot spring-boot-starter-security @@ -44,6 +39,23 @@ org.springframework.boot spring-boot-starter-web + + + + org.springframework.security + spring-security-taglibs + + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + org.springframework.boot @@ -55,11 +67,6 @@ spring-security-test test - - org.springframework.security - spring-security-test - test - @@ -67,12 +74,14 @@ org.springframework.boot spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} 1.5.9.RELEASE + 2.0.4.RELEASE diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java new file mode 100644 index 0000000000..dccbace106 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/MethodSecurityConfigurer.java @@ -0,0 +1,13 @@ +package com.baeldung.integrationtesting; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; + +@Configuration +@EnableGlobalMethodSecurity( + prePostEnabled = true, + securedEnabled = true) +public class MethodSecurityConfigurer extends GlobalMethodSecurityConfiguration { + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java new file mode 100644 index 0000000000..18469e4752 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.integrationtesting; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SecuredApplication { + + public static void main(String[] args) { + SpringApplication.run(SecuredApplication.class, args); + } + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java new file mode 100644 index 0000000000..495c358784 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredController.java @@ -0,0 +1,21 @@ +package com.baeldung.integrationtesting; + +import java.util.Arrays; +import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SecuredController { + + @GetMapping("/public/hello") + public List publicHello() { + return Arrays.asList("Hello", "World", "from", "Public"); + } + + @GetMapping("/private/hello") + public List privateHello() { + return Arrays.asList("Hello", "World", "from", "Private"); + } + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java new file mode 100644 index 0000000000..25253f163a --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/SecuredService.java @@ -0,0 +1,13 @@ +package com.baeldung.integrationtesting; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +@Service +public class SecuredService { + + @PreAuthorize("authenticated") + public String sayHelloSecured() { + return "Hello user."; + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java new file mode 100644 index 0000000000..32a48ce612 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java @@ -0,0 +1,31 @@ +package com.baeldung.integrationtesting; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("spring") + .password("secret") + .roles("USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/private/**") + .hasRole("USER") + .antMatchers("/public/**") + .permitAll() + .and() + .httpBasic(); + } + + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java new file mode 100644 index 0000000000..eca093a76f --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java @@ -0,0 +1,14 @@ +package com.baeldung.springsecuritytaglibs; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/") +public class HomeController { + + @RequestMapping + public String home() { + return "home"; + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java new file mode 100644 index 0000000000..397ea47f96 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java @@ -0,0 +1,9 @@ +package com.baeldung.springsecuritytaglibs; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@PropertySource("classpath:application-taglibs.properties") +public class SpringBootSecurityTagLibsApplication { +} diff --git a/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/config/BasicAuthConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java similarity index 53% rename from spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/config/BasicAuthConfiguration.java rename to spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java index 3ed301439c..665dd0bce9 100644 --- a/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/config/BasicAuthConfiguration.java +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java @@ -1,7 +1,6 @@ -package com.baeldung.springbootsecurityrest.basicauth.config; +package com.baeldung.springsecuritytaglibs.config; import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @@ -9,26 +8,24 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration @EnableWebSecurity -public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter { +public class SpringBootSecurityTagLibsConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth - .inMemoryAuthentication() - .withUser("user") - .password("password") - .roles("USER"); + auth.inMemoryAuthentication() + .withUser("testUser") + .password("password") + .roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable() - .authorizeRequests() - .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() - .antMatchers("/login").permitAll() - .anyRequest() - .authenticated() - .and() - .httpBasic(); + // @formatter:off + http.csrf() + .and() + .authorizeRequests() + .antMatchers("/userManagement").hasRole("ADMIN") + .anyRequest().permitAll().and().httpBasic(); + // @formatter:on } -} +} \ No newline at end of file diff --git a/spring-boot-security/src/main/resources/application-taglibs.properties b/spring-boot-security/src/main/resources/application-taglibs.properties new file mode 100644 index 0000000000..218868405f --- /dev/null +++ b/spring-boot-security/src/main/resources/application-taglibs.properties @@ -0,0 +1,3 @@ +#jsp config +spring.mvc.view.prefix: /WEB-INF/views/ +spring.mvc.view.suffix: .jsp diff --git a/spring-boot-security/src/main/resources/application.properties b/spring-boot-security/src/main/resources/application.properties index c2b8d70dc6..e776132359 100644 --- a/spring-boot-security/src/main/resources/application.properties +++ b/spring-boot-security/src/main/resources/application.properties @@ -1,4 +1,4 @@ #spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration #security.user.password=password #security.oauth2.client.client-id=client -#security.oauth2.client.client-secret=secret +#security.oauth2.client.client-secret=secret \ No newline at end of file diff --git a/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp new file mode 100644 index 0000000000..80ecd61cb5 --- /dev/null +++ b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp @@ -0,0 +1,38 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> + + + + + +Home Page + + + + Login + + + + Logout + + + +

    + Welcome back, +

    + + Manage Users + +
    + + Text Field:
    + + + + Manage Users + +
    + + \ No newline at end of file diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java new file mode 100644 index 0000000000..c224058155 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerRestTemplateIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.integrationtesting; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SecuredControllerRestTemplateIntegrationTest { + + @Autowired + private TestRestTemplate template; + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + ResponseEntity result = template.getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + ResponseEntity result = template.withBasicAuth("spring", "secret") + .getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.OK, result.getStatusCode()); + } + +} diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java new file mode 100644 index 0000000000..ce9e6de917 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerSpringBootIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.integrationtesting; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SecuredControllerSpringBootIntegrationTest { + + @Autowired + private WebApplicationContext context; + + private MockMvc mvc; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isUnauthorized()); + } + + @WithMockUser("spring") + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java new file mode 100644 index 0000000000..7281648856 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredControllerWebMvcIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.integrationtesting; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.integrationtesting.SecuredController; + +@RunWith(SpringRunner.class) +@WebMvcTest(SecuredController.class) +public class SecuredControllerWebMvcIntegrationTest { + + @Autowired + private MockMvc mvc; + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isUnauthorized()); + } + + @WithMockUser(value = "spring") + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + mvc.perform(get("/private/hello") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java new file mode 100644 index 0000000000..816b05bd5a --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/integrationtesting/SecuredMethodSpringBootIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.integrationtesting; + +import static org.assertj.core.api.Assertions.assertThat; + +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.security.authentication.AuthenticationCredentialsNotFoundException; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.integrationtesting.SecuredService; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SecuredMethodSpringBootIntegrationTest { + + @Autowired + private SecuredService service; + + @Test(expected = AuthenticationCredentialsNotFoundException.class) + public void givenUnauthenticated_whenCallService_thenThrowsException() { + service.sayHelloSecured(); + } + + @WithMockUser(username="spring") + @Test + public void givenAuthenticated_whenCallServiceWithSecured_thenOk() { + assertThat(service.sayHelloSecured()).isNotBlank(); + } +} diff --git a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java new file mode 100644 index 0000000000..0585c06a59 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.springsecuritytaglibs; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class) +public class HomeControllerUnitTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception { + String body = this.restTemplate.withBasicAuth("testUser", "password") + .getForEntity("/", String.class) + .getBody(); + + // test + assertFalse(body.contains("Login")); + + // test + assertTrue(body.contains("Logout")); + + // test + assertTrue(body.contains("Manage Users")); + + // test + assertTrue(body.contains("testUser")); + + // test + assertTrue(body.contains("")); + + // test + assertTrue(body.contains(" + assertTrue(body.contains("")); + } + + @Test + public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception { + String body = this.restTemplate.getForEntity("/", String.class) + .getBody(); + + // test + assertTrue(body.contains("Login")); + + // test + assertFalse(body.contains("Logout")); + } +} diff --git a/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java b/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java similarity index 96% rename from spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java rename to spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java index 6364351eb3..567b239ed2 100644 --- a/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java +++ b/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java @@ -16,7 +16,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc -public class SpringBootMvcApplicationTests { +public class SpringBootMvcApplicationUnitTest { @Autowired private MockMvc mockMvc; diff --git a/spring-boot-vue/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-vue/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6ed93e8c44 --- /dev/null +++ b/spring-boot-vue/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.springbootmvc.SpringBootMvcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootMvcApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 1532889a5c..192c4f9fed 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -3,7 +3,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot) - [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) - [The @ServletComponentScan Annotation in Spring Boot](http://www.baeldung.com/spring-servletcomponentscan) - [Intro to Building an Application with Spring Boot](http://www.baeldung.com/intro-to-spring-boot) @@ -12,19 +11,15 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Using Custom Banners in Spring Boot](http://www.baeldung.com/spring-boot-custom-banners) - [Guide to Internationalization in Spring Boot](http://www.baeldung.com/spring-boot-internationalization) - [Create a Custom FailureAnalyzer with Spring Boot](http://www.baeldung.com/spring-boot-failure-analyzer) -- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source) - [Dynamic DTO Validation Config Retrieved from DB](http://www.baeldung.com/spring-dynamic-dto-validation) - [Custom Information in Spring Boot Info Endpoint](http://www.baeldung.com/spring-boot-info-actuator-custom) - [Using @JsonComponent in Spring Boot](http://www.baeldung.com/spring-boot-jsoncomponent) - [Testing in Spring Boot](http://www.baeldung.com/spring-boot-testing) - [Guide to @ConfigurationProperties in Spring Boot](http://www.baeldung.com/configuration-properties-in-spring-boot) - [How to Get All Spring-Managed Beans?](http://www.baeldung.com/spring-show-all-beans) -- [A Java Client for a WebSockets API](http://www.baeldung.com/websockets-api-java-spring-client) - [Spring Boot and Togglz Aspect](http://www.baeldung.com/spring-togglz) - [Getting Started with GraphQL and Spring Boot](http://www.baeldung.com/spring-graphql) - [Guide to Spring Type Conversions](http://www.baeldung.com/spring-type-conversions) -- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) -- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) - [An Introduction to Kong](http://www.baeldung.com/kong) - [Spring Boot Customize Whitelabel Error Page](http://www.baeldung.com/spring-boot-custom-error-page) - [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) @@ -36,3 +31,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Shutdown Callbacks](http://www.baeldung.com/spring-shutdown-callbacks) - [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb) - [Container Configuration in Spring Boot 2](http://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) +- [Introduction to Chaos Monkey](https://www.baeldung.com/spring-boot-chaos-monkey) +- [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) +- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index ef30600d45..0ea6b6156f 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -117,16 +117,6 @@ provided - - org.springframework - spring-websocket - - - - org.springframework - spring-messaging - - org.togglz togglz-spring-boot-starter @@ -149,6 +139,26 @@ rome ${rome.version} + + + de.codecentric + chaos-monkey-spring-boot + ${chaos.monkey.version} + + + + + + org.springframework.boot + spring-boot-starter-log4j + 1.3.8.RELEASE + + + org.graylog2 + gelfj + 1.1.16 + compile + @@ -170,6 +180,7 @@ pl.project13.maven git-commit-id-plugin + ${git-commit-id-plugin.version} @@ -219,9 +230,12 @@ 8.5.11 2.4.1.Final 1.9.0 + 2.0.0 3.6.0 3.2.0 18.0 + 1.2.0 + 2.2.4 - \ No newline at end of file + diff --git a/spring-boot/src/main/java/com/baeldung/chaosmonkey/SpringBootChaosMonkeyApp.java b/spring-boot/src/main/java/com/baeldung/chaosmonkey/SpringBootChaosMonkeyApp.java new file mode 100644 index 0000000000..16a0aea13b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/chaosmonkey/SpringBootChaosMonkeyApp.java @@ -0,0 +1,15 @@ +package com.baeldung.chaosmonkey; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Created by adi on 8/2/18. + */ +@SpringBootApplication(scanBasePackages = { "com.baeldung.chaosmonkey" }) +public class SpringBootChaosMonkeyApp { + + public static void main(String[] args) { + SpringApplication.run(SpringBootChaosMonkeyApp.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/chaosmonkey/controller/PermissionsController.java b/spring-boot/src/main/java/com/baeldung/chaosmonkey/controller/PermissionsController.java new file mode 100644 index 0000000000..6ceb117f4e --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/chaosmonkey/controller/PermissionsController.java @@ -0,0 +1,25 @@ +package com.baeldung.chaosmonkey.controller; + +import com.baeldung.chaosmonkey.service.PermissionsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * Created by adi on 8/2/18. + */ +@RestController +@RequestMapping("/permissions") +public class PermissionsController { + + @Autowired private PermissionsService permissionsService; + + @GetMapping + public List getAllPermissions() { + return permissionsService.getAllPermissions(); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/chaosmonkey/service/PermissionsService.java b/spring-boot/src/main/java/com/baeldung/chaosmonkey/service/PermissionsService.java new file mode 100644 index 0000000000..435e262901 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/chaosmonkey/service/PermissionsService.java @@ -0,0 +1,17 @@ +package com.baeldung.chaosmonkey.service; + +import org.springframework.stereotype.Service; + +import java.util.Arrays; +import java.util.List; + +/** + * Created by adi on 8/2/18. + */ +@Service +public class PermissionsService { + + public List getAllPermissions() { + return Arrays.asList("CREATE", "READ", "UPDATE", "DELETE"); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java b/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java new file mode 100644 index 0000000000..9ddcf12d4e --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java @@ -0,0 +1,5 @@ +package com.baeldung.componentscan; + +public class ExampleBean { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java new file mode 100644 index 0000000000..2377ed7a56 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java @@ -0,0 +1,38 @@ +package com.baeldung.componentscan.springapp; + +import org.springframework.context.annotation.FilterType; +import org.springframework.stereotype.Component; + +import com.baeldung.componentscan.ExampleBean; +import com.baeldung.componentscan.springapp.flowers.Rose; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan +//@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Rose.class)) +//@ComponentScan(basePackages = "com.baeldung.componentscan.springapp") +//@ComponentScan(basePackages = "com.baeldung.componentscan.springapp.animals") +//@ComponentScan (excludeFilters = @ComponentScan.Filter(type=FilterType.REGEX,pattern="com\\.baeldung\\.componentscan\\.springapp\\.flowers\\..*")) +public class SpringComponentScanApp { + + private static ApplicationContext applicationContext; + + @Bean + public ExampleBean exampleBean() { + return new ExampleBean(); + } + + public static void main(String[] args) { + applicationContext = new AnnotationConfigApplicationContext(SpringComponentScanApp.class); + + for (String beanName : applicationContext.getBeanDefinitionNames()) { + System.out.println(beanName); + } + } + +} \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java new file mode 100644 index 0000000000..5f5b482972 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springapp.animals; + +import org.springframework.stereotype.Component; + +@Component +public class Cat { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java new file mode 100644 index 0000000000..009162b57f --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springapp.animals; + +import org.springframework.stereotype.Component; + +@Component +public class Dog { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java new file mode 100644 index 0000000000..b777b073b9 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springapp.flowers; + +import org.springframework.stereotype.Component; + +@Component +public class Rose { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java new file mode 100644 index 0000000000..ba29a4e1f5 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java @@ -0,0 +1,37 @@ +package com.baeldung.componentscan.springbootapp; + +import org.springframework.boot.SpringApplication; +import org.springframework.context.annotation.FilterType; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +import com.baeldung.componentscan.ExampleBean; +import com.baeldung.componentscan.springbootapp.flowers.Rose; + +@SpringBootApplication +//@ComponentScan(basePackages = "com.baeldung.componentscan.springbootapp.animals") +//@ComponentScan ( excludeFilters = @ComponentScan.Filter(type=FilterType.REGEX,pattern="com\\.baeldung\\.componentscan\\.springbootapp\\.flowers\\..*")) +//@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Rose.class)) + +public class SpringBootComponentScanApp { + private static ApplicationContext applicationContext; + + @Bean + public ExampleBean exampleBean() { + return new ExampleBean(); + } + + public static void main(String[] args) { + applicationContext = SpringApplication.run(SpringBootComponentScanApp.class, args); + checkBeansPresence("cat", "dog", "rose", "exampleBean", "springBootApp"); + + } + + private static void checkBeansPresence(String... beans) { + for (String beanName : beans) { + System.out.println("Is " + beanName + " in ApplicationContext: " + applicationContext.containsBean(beanName)); + } + } +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java new file mode 100644 index 0000000000..7c43d6a24c --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springbootapp.animals; + +import org.springframework.stereotype.Component; + +@Component +public class Cat { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java new file mode 100644 index 0000000000..145430cb54 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springbootapp.animals; + +import org.springframework.stereotype.Component; + +@Component +public class Dog { + +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java new file mode 100644 index 0000000000..0ccf782685 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java @@ -0,0 +1,8 @@ +package com.baeldung.componentscan.springbootapp.flowers; + +import org.springframework.stereotype.Component; + +@Component +public class Rose { + +} diff --git a/spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java b/spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java new file mode 100644 index 0000000000..be49a0e927 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.graylog; + +import org.apache.log4j.Logger; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class GraylogDemoApplication { + + private final static Logger LOG = + Logger.getLogger(GraylogDemoApplication.class); + + public static void main(String[] args) { + SpringApplication.run(GraylogDemoApplication.class, args); + LOG.info("Hello from Spring Boot"); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/ConfigProperties.java b/spring-boot/src/main/java/com/baeldung/properties/ConfigProperties.java new file mode 100644 index 0000000000..863510738b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/ConfigProperties.java @@ -0,0 +1,117 @@ +package com.baeldung.properties; + +import java.util.List; +import java.util.Map; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.Pattern; + +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotBlank; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.validation.annotation.Validated; + +@Configuration +@PropertySource("classpath:configprops.properties") +@ConfigurationProperties(prefix = "mail") +@Validated +public class ConfigProperties { + + @Validated + public static class Credentials { + + @Length(max = 4, min = 1) + private String authMethod; + private String username; + private String password; + + public String getAuthMethod() { + return authMethod; + } + + public void setAuthMethod(String authMethod) { + this.authMethod = authMethod; + } + + 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; + } + } + + @NotBlank + private String host; + + @Min(1025) + @Max(65536) + private int port; + + @Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$") + private String from; + + private Credentials credentials; + private List defaultRecipients; + private Map additionalHeaders; + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public Credentials getCredentials() { + return credentials; + } + + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } + + public List getDefaultRecipients() { + return defaultRecipients; + } + + public void setDefaultRecipients(List defaultRecipients) { + this.defaultRecipients = defaultRecipients; + } + + public Map getAdditionalHeaders() { + return additionalHeaders; + } + + public void setAdditionalHeaders(Map additionalHeaders) { + this.additionalHeaders = additionalHeaders; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java new file mode 100644 index 0000000000..ee9671c755 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.properties; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class }) +public class ConfigPropertiesDemoApplication { + public static void main(String[] args) { + new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) + .run(); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/CustomJsonProperties.java b/spring-boot/src/main/java/com/baeldung/properties/CustomJsonProperties.java new file mode 100644 index 0000000000..084138ec6f --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/CustomJsonProperties.java @@ -0,0 +1,71 @@ +package com.baeldung.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "custom") +public class CustomJsonProperties { + + private String host; + + private int port; + + private boolean resend; + + private Person sender; + + public static class Person { + + private String name; + private String address; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public boolean isResend() { + return resend; + } + + public void setResend(boolean resend) { + this.resend = resend; + } + + public Person getSender() { + return sender; + } + + public void setSender(Person sender) { + this.sender = sender; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/JsonProperties.java b/spring-boot/src/main/java/com/baeldung/properties/JsonProperties.java new file mode 100644 index 0000000000..31b3be14b4 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/JsonProperties.java @@ -0,0 +1,64 @@ +package com.baeldung.properties; + +import java.util.LinkedHashMap; +import java.util.List; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +@Component +@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class) +@ConfigurationProperties +public class JsonProperties { + + private String host; + + private int port; + + private boolean resend; + + private List topics; + + private LinkedHashMap sender; + + public LinkedHashMap getSender() { + return sender; + } + + public void setSender(LinkedHashMap sender) { + this.sender = sender; + } + + public List getTopics() { + return topics; + } + + public void setTopics(List topics) { + this.topics = topics; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public boolean isResend() { + return resend; + } + + public void setResend(boolean resend) { + this.resend = resend; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java b/spring-boot/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java new file mode 100644 index 0000000000..0aee149123 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java @@ -0,0 +1,68 @@ +package com.baeldung.properties; + +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.Resource; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonPropertyContextInitializer implements ApplicationContextInitializer { + + private final static String CUSTOM_PREFIX = "custom."; + + @Override + @SuppressWarnings("unchecked") + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + try { + Resource resource = configurableApplicationContext.getResource("classpath:configprops.json"); + Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); + Set set = readValue.entrySet(); + List propertySources = convertEntrySet(set, Optional.empty()); + for (PropertySource propertySource : propertySources) { + configurableApplicationContext.getEnvironment() + .getPropertySources() + .addFirst(propertySource); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static List convertEntrySet(Set entrySet, Optional parentKey) { + return entrySet.stream() + .map((Map.Entry e) -> convertToPropertySourceList(e, parentKey)) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + } + + private static List convertToPropertySourceList(Map.Entry e, Optional parentKey) { + String key = parentKey.map(s -> s + ".") + .orElse("") + (String) e.getKey(); + Object value = e.getValue(); + return covertToPropertySourceList(key, value); + } + + @SuppressWarnings("unchecked") + private static List covertToPropertySourceList(String key, Object value) { + if (value instanceof LinkedHashMap) { + LinkedHashMap map = (LinkedHashMap) value; + Set entrySet = map.entrySet(); + return convertEntrySet(entrySet, Optional.ofNullable(key)); + } + String finalKey = CUSTOM_PREFIX + key; + return Collections.singletonList(new MapPropertySource(finalKey, Collections.singletonMap(finalKey, value))); + } + +} \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java b/spring-boot/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java new file mode 100644 index 0000000000..c14d3faea5 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java @@ -0,0 +1,21 @@ +package com.baeldung.properties; + +import java.io.IOException; +import java.util.Map; + +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.core.io.support.PropertySourceFactory; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonPropertySourceFactory implements PropertySourceFactory { + + @Override + public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException { + Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); + return new MapPropertySource("json-property", readValue); + } + +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java index cb0304fc41..395d68060b 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -1,13 +1,15 @@ package org.baeldung.properties; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.ComponentScan; -@EnableAutoConfiguration -@ComponentScan(basePackageClasses = ConfigProperties.class) +@SpringBootApplication +@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class }) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { - SpringApplication.run(ConfigPropertiesDemoApplication.class); + new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) + .run(); } + } diff --git a/spring-boot/src/main/java/org/baeldung/properties/CustomJsonProperties.java b/spring-boot/src/main/java/org/baeldung/properties/CustomJsonProperties.java new file mode 100644 index 0000000000..3fae8a8e98 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/CustomJsonProperties.java @@ -0,0 +1,71 @@ +package org.baeldung.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "custom") +public class CustomJsonProperties { + + private String host; + + private int port; + + private boolean resend; + + private Person sender; + + public static class Person { + + private String name; + private String address; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public boolean isResend() { + return resend; + } + + public void setResend(boolean resend) { + this.resend = resend; + } + + public Person getSender() { + return sender; + } + + public void setSender(Person sender) { + this.sender = sender; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/properties/JsonProperties.java b/spring-boot/src/main/java/org/baeldung/properties/JsonProperties.java new file mode 100644 index 0000000000..5c31cd1344 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/JsonProperties.java @@ -0,0 +1,64 @@ +package org.baeldung.properties; + +import java.util.LinkedHashMap; +import java.util.List; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +@Component +@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class) +@ConfigurationProperties +public class JsonProperties { + + private String host; + + private int port; + + private boolean resend; + + private List topics; + + private LinkedHashMap sender; + + public LinkedHashMap getSender() { + return sender; + } + + public void setSender(LinkedHashMap sender) { + this.sender = sender; + } + + public List getTopics() { + return topics; + } + + public void setTopics(List topics) { + this.topics = topics; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public boolean isResend() { + return resend; + } + + public void setResend(boolean resend) { + this.resend = resend; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/properties/JsonPropertyContextInitializer.java b/spring-boot/src/main/java/org/baeldung/properties/JsonPropertyContextInitializer.java new file mode 100644 index 0000000000..fd9b3f35a5 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/JsonPropertyContextInitializer.java @@ -0,0 +1,68 @@ +package org.baeldung.properties; + +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.Resource; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonPropertyContextInitializer implements ApplicationContextInitializer { + + private final static String CUSTOM_PREFIX = "custom."; + + @Override + @SuppressWarnings("unchecked") + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + try { + Resource resource = configurableApplicationContext.getResource("classpath:configprops.json"); + Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); + Set set = readValue.entrySet(); + List propertySources = convertEntrySet(set, Optional.empty()); + for (PropertySource propertySource : propertySources) { + configurableApplicationContext.getEnvironment() + .getPropertySources() + .addFirst(propertySource); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static List convertEntrySet(Set entrySet, Optional parentKey) { + return entrySet.stream() + .map((Map.Entry e) -> convertToPropertySourceList(e, parentKey)) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + } + + private static List convertToPropertySourceList(Map.Entry e, Optional parentKey) { + String key = parentKey.map(s -> s + ".") + .orElse("") + (String) e.getKey(); + Object value = e.getValue(); + return covertToPropertySourceList(key, value); + } + + @SuppressWarnings("unchecked") + private static List covertToPropertySourceList(String key, Object value) { + if (value instanceof LinkedHashMap) { + LinkedHashMap map = (LinkedHashMap) value; + Set entrySet = map.entrySet(); + return convertEntrySet(entrySet, Optional.ofNullable(key)); + } + String finalKey = CUSTOM_PREFIX + key; + return Collections.singletonList(new MapPropertySource(finalKey, Collections.singletonMap(finalKey, value))); + } + +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/properties/JsonPropertySourceFactory.java b/spring-boot/src/main/java/org/baeldung/properties/JsonPropertySourceFactory.java new file mode 100644 index 0000000000..9578179519 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/JsonPropertySourceFactory.java @@ -0,0 +1,21 @@ +package org.baeldung.properties; + +import java.io.IOException; +import java.util.Map; + +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.core.io.support.PropertySourceFactory; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonPropertySourceFactory implements PropertySourceFactory { + + @Override + public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException { + Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); + return new MapPropertySource("json-property", readValue); + } + +} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java index cba504b6c6..7335af2616 100644 --- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java @@ -24,8 +24,6 @@ public interface UserRepository extends JpaRepository { Optional findOneByName(String name); - Stream findAllByName(String name); - @Async CompletableFuture findOneByStatus(Integer status); diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 8c02e528ab..629e880940 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -43,3 +43,34 @@ servlet.mapping=/dispatcherExampleURL #spring.banner.image.invert= //TODO contactInfoType=email + +#chaos monkey for spring boot props +management.endpoint.chaosmonkey.enabled=true +management.endpoint.chaosmonkeyjmx.enabled=true + +spring.profiles.active=chaos-monkey +#Determine whether should execute or not +chaos.monkey.enabled=true +#How many requests are to be attacked. 1: attack each request; 5: each 5th request is attacked +chaos.monkey.assaults.level=1 +#Minimum latency in ms added to the request +chaos.monkey.assaults.latencyRangeStart=3000 +#Maximum latency in ms added to the request +chaos.monkey.assaults.latencyRangeEnd=15000 +#Latency assault active +chaos.monkey.assaults.latencyActive=true +#Exception assault active +chaos.monkey.assaults.exceptionsActive=false +#AppKiller assault active +chaos.monkey.assaults.killApplicationActive=false +#Controller watcher active +chaos.monkey.watcher.controller=false +#RestController watcher active +chaos.monkey.watcher.restController=false +#Service watcher active +chaos.monkey.watcher.service=true +#Repository watcher active +chaos.monkey.watcher.repository=false +#Component watcher active +chaos.monkey.watcher.component=false + diff --git a/spring-boot/src/main/resources/configprops.json b/spring-boot/src/main/resources/configprops.json new file mode 100644 index 0000000000..1602663775 --- /dev/null +++ b/spring-boot/src/main/resources/configprops.json @@ -0,0 +1,10 @@ +{ + "host" : "mailer@mail.com", + "port" : 9090, + "resend" : true, + "topics" : ["spring", "boot"], + "sender" : { + "name": "sender", + "address": "street" + } +} diff --git a/spring-boot/src/main/resources/log4j.xml b/spring-boot/src/main/resources/log4j.xml new file mode 100644 index 0000000000..61c1b7b229 --- /dev/null +++ b/spring-boot/src/main/resources/log4j.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot/src/main/resources/logback.xml b/spring-boot/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-boot/src/main/resources/logback.xml +++ b/spring-boot/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-boot/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java new file mode 100644 index 0000000000..3a4b6551b1 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.properties; + +import org.baeldung.properties.ConfigProperties; +import org.baeldung.properties.ConfigPropertiesDemoApplication; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigPropertiesDemoApplication.class) +@TestPropertySource("classpath:configprops-test.properties") +public class ConfigPropertiesIntegrationTest { + + @Autowired + private ConfigProperties properties; + + @Test + public void whenSimplePropertyQueriedthenReturnsProperty() throws Exception { + Assert.assertTrue("From address is read as null!", properties.getFrom() != null); + } + + @Test + public void whenListPropertyQueriedthenReturnsProperty() throws Exception { + Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients().size() == 2); + Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients().size() == 2); + } + + @Test + public void whenMapPropertyQueriedthenReturnsProperty() throws Exception { + Assert.assertTrue("Couldn't bind map property!", properties.getAdditionalHeaders() != null); + Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders().size() == 3); + } + + @Test + public void whenObjectPropertyQueriedthenReturnsProperty() throws Exception { + Assert.assertTrue("Couldn't bind map property!", properties.getCredentials() != null); + Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getAuthMethod().equals("SHA1")); + Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getUsername().equals("john")); + Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getPassword().equals("password")); + } +} diff --git a/spring-boot/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java new file mode 100644 index 0000000000..48c551d1dd --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.properties; + +import java.util.Arrays; + +import org.baeldung.properties.ConfigPropertiesDemoApplication; +import org.baeldung.properties.CustomJsonProperties; +import org.baeldung.properties.JsonProperties; +import org.baeldung.properties.JsonPropertyContextInitializer; +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ConfigPropertiesDemoApplication.class, initializers = JsonPropertyContextInitializer.class) +public class JsonPropertiesIntegrationTest { + + @Autowired + private JsonProperties jsonProperties; + + @Autowired + private CustomJsonProperties customJsonProperties; + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenLoadFlatValues() { + Assert.assertEquals("mailer@mail.com", jsonProperties.getHost()); + Assert.assertEquals(9090, jsonProperties.getPort()); + Assert.assertTrue(jsonProperties.isResend()); + } + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenLoadListValues() { + Assert.assertThat(jsonProperties.getTopics(), Matchers.is(Arrays.asList("spring", "boot"))); + } + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenNestedLoadedAsMap() { + Assert.assertEquals("sender", jsonProperties.getSender() + .get("name")); + Assert.assertEquals("street", jsonProperties.getSender() + .get("address")); + } + + @Test + public void whenLoadedIntoEnvironment_thenFlatValuesPopulated() { + Assert.assertEquals("mailer@mail.com", customJsonProperties.getHost()); + Assert.assertEquals(9090, customJsonProperties.getPort()); + Assert.assertTrue(customJsonProperties.isResend()); + } + + @Test + public void whenLoadedIntoEnvironment_thenValuesLoadedIntoClassObject() { + Assert.assertNotNull(customJsonProperties.getSender()); + Assert.assertEquals("sender", customJsonProperties.getSender() + .getName()); + Assert.assertEquals("street", customJsonProperties.getSender() + .getAddress()); + } + +} diff --git a/spring-boot/src/test/java/org/baeldung/properties/JsonPropertiesIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/properties/JsonPropertiesIntegrationTest.java new file mode 100644 index 0000000000..e3d4c62953 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/properties/JsonPropertiesIntegrationTest.java @@ -0,0 +1,59 @@ +package org.baeldung.properties; + +import java.util.Arrays; + +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ConfigPropertiesDemoApplication.class, initializers = JsonPropertyContextInitializer.class) +public class JsonPropertiesIntegrationTest { + + @Autowired + private JsonProperties jsonProperties; + + @Autowired + private CustomJsonProperties customJsonProperties; + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenLoadFlatValues() { + Assert.assertEquals("mailer@mail.com", jsonProperties.getHost()); + Assert.assertEquals(9090, jsonProperties.getPort()); + Assert.assertTrue(jsonProperties.isResend()); + } + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenLoadListValues() { + Assert.assertThat(jsonProperties.getTopics(), Matchers.is(Arrays.asList("spring", "boot"))); + } + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenNestedLoadedAsMap() { + Assert.assertEquals("sender", jsonProperties.getSender() + .get("name")); + Assert.assertEquals("street", jsonProperties.getSender() + .get("address")); + } + + @Test + public void whenLoadedIntoEnvironment_thenFlatValuesPopulated() { + Assert.assertEquals("mailer@mail.com", customJsonProperties.getHost()); + Assert.assertEquals(9090, customJsonProperties.getPort()); + Assert.assertTrue(customJsonProperties.isResend()); + } + + @Test + public void whenLoadedIntoEnvironment_thenValuesLoadedIntoClassObject() { + Assert.assertNotNull(customJsonProperties.getSender()); + Assert.assertEquals("sender", customJsonProperties.getSender() + .getName()); + Assert.assertEquals("street", customJsonProperties.getSender() + .getAddress()); + } + +} diff --git a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java index 72d204820e..04bb1170f8 100644 --- a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java @@ -52,30 +52,6 @@ public class UserRepositoryIntegrationTest { .getName()).isEqualTo(USER_NAME_ADAM); } - @Test - @Transactional - public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - userRepository.save(user3); - - User user4 = new User(); - user4.setName("SAMPLE"); - userRepository.save(user4); - - try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count()).isEqualTo(3l); - } - } - @Test public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException { User user = new User(); diff --git a/spring-cloud-bus/pom.xml b/spring-cloud-bus/pom.xml new file mode 100644 index 0000000000..d493c4e984 --- /dev/null +++ b/spring-cloud-bus/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + com.baeldung.spring.cloud + spring-cloud-bus + 1.0.0-SNAPSHOT + pom + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 + + + + spring-cloud-config-client + spring-cloud-config-server + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud-dependencies.version} + pom + import + + + + + + Brixton.SR7 + + + diff --git a/spring-cloud-bus/spring-cloud-config-client/pom.xml b/spring-cloud-bus/spring-cloud-config-client/pom.xml index bd9fb45587..b2b69303bf 100644 --- a/spring-cloud-bus/spring-cloud-config-client/pom.xml +++ b/spring-cloud-bus/spring-cloud-config-client/pom.xml @@ -1,76 +1,53 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + spring-cloud-config-client + jar - com.baeldung.spring.cloud - spring-cloud-config-client - 0.0.1-SNAPSHOT - jar + spring-cloud-config-client + Demo Spring Cloud Config Client - spring-cloud-config-client - Demo Spring Cloud Config Client + + spring-cloud-bus + com.baeldung.spring.cloud + 1.0.0-SNAPSHOT + - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 - + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.boot + spring-boot-starter-web + - - - org.springframework.cloud - spring-cloud-starter-config - - - org.springframework.boot - spring-boot-starter-web - + + org.springframework.boot + spring-boot-starter-test + test + - - org.springframework.boot - spring-boot-starter-test - test - + + org.springframework.boot + spring-boot-actuator + - - org.springframework.boot - spring-boot-actuator - + + org.springframework.cloud + spring-cloud-starter-bus-amqp + + - - org.springframework.cloud - spring-cloud-starter-bus-amqp - - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - UTF-8 - UTF-8 - 1.8 - Dalston.SR1 - + + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 56% rename from spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java rename to spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 2440b97aaf..c0298daeb1 100644 --- a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java +++ b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,13 +1,15 @@ -package com.baeldung.spring.cloud.kubernetes.backend; +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 -public class KubernetesBackendApplicationIntegrationTest { +@SpringBootTest(classes = SpringCloudConfigClientApplication.class) +public class SpringContextIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-bus/spring-cloud-config-server/pom.xml b/spring-cloud-bus/spring-cloud-config-server/pom.xml index 194289ea1e..f50b78ff18 100644 --- a/spring-cloud-bus/spring-cloud-config-server/pom.xml +++ b/spring-cloud-bus/spring-cloud-config-server/pom.xml @@ -1,77 +1,54 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + spring-cloud-config-server + jar - com.baeldung.spring.cloud - spring-cloud-config-server - 0.0.1-SNAPSHOT - jar + spring-cloud-config-server + Demo Spring Cloud Config Server - spring-cloud-config-server - Demo Spring Cloud Config Server + + spring-cloud-bus + com.baeldung.spring.cloud + 1.0.0-SNAPSHOT + - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 - + + + org.springframework.cloud + spring-cloud-config-server + - - - org.springframework.cloud - spring-cloud-config-server - + + org.springframework.boot + spring-boot-starter-security + - - org.springframework.boot - spring-boot-starter-security - + + org.springframework.boot + spring-boot-starter-test + test + - - org.springframework.boot - spring-boot-starter-test - test - + + org.springframework.cloud + spring-cloud-config-monitor + - - org.springframework.cloud - spring-cloud-config-monitor - + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + + - - org.springframework.cloud - spring-cloud-starter-stream-rabbit - - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - UTF-8 - UTF-8 - 1.8 - Dalston.SR1 - + + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientLiveTest.java b/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationIntegrationTest.java similarity index 81% rename from spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientLiveTest.java rename to spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationIntegrationTest.java index 364368713a..12e0928ad8 100644 --- a/spring-cloud-bus/spring-cloud-config-client/src/test/java/com/baeldung/SpringCloudConfigClientLiveTest.java +++ b/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class SpringCloudConfigClientLiveTest { +public class SpringCloudConfigServerApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c43bb9f067 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +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.SpringCloudConfigServerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudConfigServerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..b87ace74a4 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.JobConfiguration; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ContextConfiguration(classes = JobConfiguration.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..eb2a5c54ef --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +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 SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..28dbc9a8d8 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.DataFlowShellApplication; +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 = DataFlowShellApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java deleted file mode 100644 index 5ab3292388..0000000000 --- a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.spring.cloud; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class DataFlowShellApplicationIntegrationTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-data-flow/etl/README.MD b/spring-cloud-data-flow/etl/README.MD new file mode 100644 index 0000000000..0cbb460b01 --- /dev/null +++ b/spring-cloud-data-flow/etl/README.MD @@ -0,0 +1,9 @@ +# Overview +This is an example of a ETL stream pipeline, mixing a starter application with custom transform and sink. + +# Applications +JDBC Source - Application Starter distributed by default + +customer-transform - Custom application to transform the data + +customer-mongodb-sink - Custom application to sink the data diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml new file mode 100644 index 0000000000..468d8e17d0 --- /dev/null +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + com.customer + customer-mongodb-sink + jar + + customer-mongodb-sink + Example ETL Load Project + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../../parent-boot-2 + + + + UTF-8 + UTF-8 + 1.8 + Finchley.SR1 + + + + + org.springframework.cloud + spring-cloud-stream + + + org.springframework.cloud + spring-cloud-stream-binder-rabbit + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.cloud + spring-cloud-stream-test-support + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/Customer.java b/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/Customer.java new file mode 100644 index 0000000000..cf44aec5b7 --- /dev/null +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/Customer.java @@ -0,0 +1,27 @@ +package com.customer.customermongodbsink; + +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collection = "customer") +public class Customer { + + private Long id; + private String name; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} \ No newline at end of file diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/CustomerListener.java b/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/CustomerListener.java new file mode 100644 index 0000000000..c841daea8a --- /dev/null +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/CustomerListener.java @@ -0,0 +1,18 @@ +package com.customer.customermongodbsink; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.annotation.StreamListener; +import org.springframework.cloud.stream.messaging.Sink; + +@EnableBinding(Sink.class) +public class CustomerListener { + + @Autowired + private CustomerRepository repository; + + @StreamListener(Sink.INPUT) + public void save(Customer customer) { + repository.save(customer); + } +} diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/CustomerMongodbSinkApplication.java b/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/CustomerMongodbSinkApplication.java new file mode 100644 index 0000000000..2ef311457e --- /dev/null +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/CustomerMongodbSinkApplication.java @@ -0,0 +1,12 @@ +package com.customer.customermongodbsink; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CustomerMongodbSinkApplication { + + public static void main(String[] args) { + SpringApplication.run(CustomerMongodbSinkApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/CustomerRepository.java b/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/CustomerRepository.java new file mode 100644 index 0000000000..f921ff51cf --- /dev/null +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/java/com/customer/customermongodbsink/CustomerRepository.java @@ -0,0 +1,9 @@ +package com.customer.customermongodbsink; + +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends MongoRepository { + +} \ No newline at end of file diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/resources/application.properties b/spring-cloud-data-flow/etl/customer-mongodb-sink/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-cloud-data-flow/etl/customer-transform/pom.xml b/spring-cloud-data-flow/etl/customer-transform/pom.xml new file mode 100644 index 0000000000..bc4b648907 --- /dev/null +++ b/spring-cloud-data-flow/etl/customer-transform/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + com.customer + customer-transform + 0.0.1-SNAPSHOT + jar + + customer-transform + Example transform ETL step + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../../parent-boot-2 + + + + UTF-8 + UTF-8 + 1.8 + Finchley.SR1 + + + + + org.springframework.cloud + spring-cloud-stream-binder-rabbit + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.cloud + spring-cloud-stream-test-support + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud-data-flow/etl/customer-transform/src/main/java/com/customer/customertransform/Customer.java b/spring-cloud-data-flow/etl/customer-transform/src/main/java/com/customer/customertransform/Customer.java new file mode 100644 index 0000000000..f0e4d79388 --- /dev/null +++ b/spring-cloud-data-flow/etl/customer-transform/src/main/java/com/customer/customertransform/Customer.java @@ -0,0 +1,29 @@ +package com.customer.customertransform; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Customer { + + private Long id; + + private String name; + + @JsonProperty("customer_name") + public void setName(String name) { + this.name = name; + } + + @JsonProperty("name") + public String getName() { + return name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +} \ No newline at end of file diff --git a/spring-cloud-data-flow/etl/customer-transform/src/main/java/com/customer/customertransform/CustomerProcessorConfiguration.java b/spring-cloud-data-flow/etl/customer-transform/src/main/java/com/customer/customertransform/CustomerProcessorConfiguration.java new file mode 100644 index 0000000000..c99fcf55be --- /dev/null +++ b/spring-cloud-data-flow/etl/customer-transform/src/main/java/com/customer/customertransform/CustomerProcessorConfiguration.java @@ -0,0 +1,16 @@ +package com.customer.customertransform; + + +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.integration.annotation.Transformer; + +@EnableBinding(Processor.class) +public class CustomerProcessorConfiguration { + + @Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT) + public Customer convertToPojo(Customer payload) { + + return payload; + } +} \ No newline at end of file diff --git a/spring-cloud-data-flow/etl/customer-transform/src/main/java/com/customer/customertransform/CustomerTransformApplication.java b/spring-cloud-data-flow/etl/customer-transform/src/main/java/com/customer/customertransform/CustomerTransformApplication.java new file mode 100644 index 0000000000..8781f4da54 --- /dev/null +++ b/spring-cloud-data-flow/etl/customer-transform/src/main/java/com/customer/customertransform/CustomerTransformApplication.java @@ -0,0 +1,12 @@ +package com.customer.customertransform; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CustomerTransformApplication { + + public static void main(String[] args) { + SpringApplication.run(CustomerTransformApplication.class, args); + } +} diff --git a/spring-cloud-data-flow/etl/customer-transform/src/main/resources/application.properties b/spring-cloud-data-flow/etl/customer-transform/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-cloud-data-flow/etl/pom.xml b/spring-cloud-data-flow/etl/pom.xml new file mode 100644 index 0000000000..2b904f6e0d --- /dev/null +++ b/spring-cloud-data-flow/etl/pom.xml @@ -0,0 +1,20 @@ + + 4.0.0 + org.baeldung.spring.cloud + etl-spring-cloud-data-flow + 0.0.1-SNAPSHOT + pom + + + org.baeldung.spring.cloud + spring-cloud-data-flow + 0.0.1-SNAPSHOT + + + + customer-mongodb-sink + customer-transform + + + diff --git a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8dc814ddce --- /dev/null +++ b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.LogSinkApplication; +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 = LogSinkApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/pom.xml b/spring-cloud-data-flow/pom.xml index 5f24aa2cbd..5a007f3c7d 100644 --- a/spring-cloud-data-flow/pom.xml +++ b/spring-cloud-data-flow/pom.xml @@ -19,6 +19,7 @@ time-processor log-sink batch-job + etl diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..dcfeafa2bb --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.TimeProcessorApplication; +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 = TimeProcessorApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2c402824f0 --- /dev/null +++ b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.TimeSourceApplication; +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 = TimeSourceApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java deleted file mode 100644 index 6d71a785a3..0000000000 --- a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.spring.cloud; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class TimeSourceApplicationIntegrationTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/README.md b/spring-cloud/README.md index 31d9ffb684..16bc2d110a 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -27,3 +27,6 @@ - [An Intro to Spring Cloud Security](http://www.baeldung.com/spring-cloud-security) - [An Intro to Spring Cloud Task](http://www.baeldung.com/spring-cloud-task) - [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube) +- [Introduction to Netflix Archaius with Spring Cloud](https://www.baeldung.com/netflix-archaius-spring-cloud-integration) +- [An Intro to Spring Cloud Vault](https://www.baeldung.com/spring-cloud-vault) +- [Netflix Archaius with Various Database Configurations](https://www.baeldung.com/netflix-archaius-database-configurations) diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 373a12da9e..924ea2be36 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -25,12 +25,18 @@ spring-cloud-zookeeper spring-cloud-gateway spring-cloud-stream + spring-cloud-stream-starters/twitterhdfs spring-cloud-connectors-heroku spring-cloud-aws spring-cloud-consul spring-cloud-zuul-eureka-integration spring-cloud-contract spring-cloud-kubernetes + spring-cloud-archaius + spring-cloud-functions + spring-cloud-vault + spring-cloud-security + spring-cloud-task diff --git a/spring-cloud/spring-cloud-archaius/README.md b/spring-cloud/spring-cloud-archaius/README.md new file mode 100644 index 0000000000..9de26352e1 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/README.md @@ -0,0 +1,14 @@ +# Spring Cloud Archaius + +#### Basic Config +This service has the basic, out-of-the-box Spring Cloud Netflix Archaius configuration. + +#### Extra Configs +This service customizes some properties supported by Archaius. + +These properties are set up on the main method, since Archaius uses System properties, but they could be added as command line arguments when launching the app. + +#### Additional Sources +In this service we create a new AbstractConfiguration bean, setting up a new Configuration Properties source. + +These properties have precedence over all the other properties in the Archaius Composite Configuration. \ No newline at end of file diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml b/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml new file mode 100644 index 0000000000..1ae6d543fb --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + additional-sources-simple + 1.0.0-SNAPSHOT + jar + additional-sources-simple + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java new file mode 100644 index 0000000000..e1a1d106cf --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.archaius.additionalsources; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AdditionalSourcesSimpleApplication { + + public static void main(String[] args) { + SpringApplication.run(AdditionalSourcesSimpleApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java new file mode 100644 index 0000000000..f2d8ca2638 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.cloud.archaius.additionalsources.config; + +import org.apache.commons.configuration.AbstractConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.netflix.config.DynamicConfiguration; +import com.netflix.config.FixedDelayPollingScheduler; +import com.netflix.config.PolledConfigurationSource; +import com.netflix.config.sources.URLConfigurationSource; + +@Configuration +public class ApplicationPropertiesConfigurations { + + @Bean + public AbstractConfiguration addApplicationPropertiesSource() { + PolledConfigurationSource source = new URLConfigurationSource("classpath:other-config.properties"); + return new DynamicConfiguration(source, new FixedDelayPollingScheduler()); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..304369a036 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.cloud.archaius.additionalsources.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.four", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + properties.put(propertyFourWithDynamic.getName(), propertyFourWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties new file mode 100644 index 0000000000..bf55e89a27 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties new file mode 100644 index 0000000000..b104c0c488 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:config.properties +baeldung.archaius.properties.three=three FROM:config.properties diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties new file mode 100644 index 0000000000..00fe8ff2aa --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:other-config.properties +baeldung.archaius.properties.four=four FROM:other-config.properties diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java new file mode 100644 index 0000000000..f3a345d869 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java @@ -0,0 +1,54 @@ +package com.baeldung.spring.cloud.archaius.additionalsources; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusAdditionalSourcesLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:other-config.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:config.properties"); + map.put("baeldung.archaius.properties.four", "four FROM:other-config.properties"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e5ebbce1aa --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.archaius.additionalsources.AdditionalSourcesSimpleApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AdditionalSourcesSimpleApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/pom.xml b/spring-cloud/spring-cloud-archaius/basic-config/pom.xml new file mode 100644 index 0000000000..b5b091712d --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + basic-config + 1.0.0-SNAPSHOT + jar + basic-config + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java new file mode 100644 index 0000000000..e6e578eed3 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BasicArchaiusApplication { + + public static void main(String[] args) { + SpringApplication.run(BasicArchaiusApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..46b8f345f6 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java @@ -0,0 +1,70 @@ +package com.baeldung.spring.cloud.archaius.basic.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicIntProperty; +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + @Value("${baeldung.archaius.properties.one:not found!}") + private String propertyOneWithValue; + + @Value("${baeldung.archaius.properties.two:not found!}") + private String propertyTwoWithValue; + + @Value("${baeldung.archaius.properties.three:not found!}") + private String propertyThreeWithValue; + + @Value("${baeldung.archaius.properties.four:not found!}") + private String propertyFourWithValue; + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.four", "not found!"); + + private DynamicIntProperty intPropertyWithDynamic = DynamicPropertyFactory.getInstance() + .getIntProperty("baeldung.archaius.properties.int", 0); + + @GetMapping("/properties-from-value") + public Map getPropertiesFromValue() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithValue); + properties.put("baeldung.archaius.properties.two", propertyTwoWithValue); + properties.put("baeldung.archaius.properties.three", propertyThreeWithValue); + properties.put("baeldung.archaius.properties.four", propertyFourWithValue); + return properties; + } + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + properties.put(propertyFourWithDynamic.getName(), propertyFourWithDynamic.get()); + return properties; + } + + @GetMapping("/int-property") + public Map getIntPropertyFromDynamic() { + Map properties = new HashMap<>(); + properties.put(intPropertyWithDynamic.getName(), intPropertyWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/application.properties new file mode 100644 index 0000000000..1a35a22197 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8080 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties \ No newline at end of file diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/config.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/config.properties new file mode 100644 index 0000000000..86ae575d20 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/config.properties @@ -0,0 +1,4 @@ +baeldung.archaius.properties.one=one FROM:config.properties +baeldung.archaius.properties.three=three FROM:config.properties + +baeldung.archaius.properties.int=1 diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/other.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/other.properties new file mode 100644 index 0000000000..26796b7341 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/other.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:other.properties +baeldung.archaius.properties.four=four FROM:other.properties diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java new file mode 100644 index 0000000000..2948606c0b --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; + +import org.junit.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.cloud.context.environment.EnvironmentChangeEvent; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RunWith(JUnitPlatform.class) +@ExtendWith(SpringExtension.class) +@SpringBootTest +public class ArchaiusBasicConfigurationIntegrationTest { + + @Autowired + ConfigurableApplicationContext context; + + private DynamicStringProperty testPropertyWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.test.properties.one", "not found!"); + + @Test + public void givenIntialPropertyValue_whenPropertyChanges_thenArchaiusRetrievesNewValue() { + String initialValue = testPropertyWithDynamic.get(); + + TestPropertyValues.of("baeldung.archaius.test.properties.one=new-value") + .applyTo(context); + context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("baeldung.archaius.test.properties.one"))); + String finalValue = testPropertyWithDynamic.get(); + + assertThat(initialValue).isEqualTo("test-one"); + assertThat(finalValue).isEqualTo("new-value"); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java new file mode 100644 index 0000000000..70d43df60d --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java @@ -0,0 +1,74 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusBasicConfigurationLiveTest { + + private static final String BASE_URL = "http://localhost:8080"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:application.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:config.properties"); + map.put("baeldung.archaius.properties.four", "not found!"); + return map; + } + + private static final String VALUE_PROPERTIES_URL = "/properties-from-value"; + private static final Map EXPECTED_VALUE_PROPERTIES = createExpectedValueProperties(); + + private static Map createExpectedValueProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:application.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "not found!"); + map.put("baeldung.archaius.properties.four", "not found!"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenDefaultConfigurationSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestSpringVisibleProperties_thenEndpointDoesntRetrieveArchaiusProperties() { + Map initialResponse = this.exchangeAsMap(BASE_URL + VALUE_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_VALUE_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..16542981e8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.archaius.basic.BasicArchaiusApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BasicArchaiusApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/resources/config.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/test/resources/config.properties new file mode 100644 index 0000000000..1ceb5d1161 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/resources/config.properties @@ -0,0 +1,3 @@ +baeldung.archaius.test.properties.one=test-one +baeldung.archaius.test.properties.two=test-two +baeldung.archaius.test.properties.int=1 diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml b/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml new file mode 100644 index 0000000000..3ffbf8f619 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + dynamodb-config + jar + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + com.amazonaws + aws-java-sdk-dynamodb + ${aws.sdk.dynamo.version} + + + com.github.derjust + spring-data-dynamodb + ${spring.dynamo.version} + + + com.netflix.archaius + archaius-aws + ${archaius.version} + + + org.projectlombok + lombok + provided + + + + + 1.11.407 + 5.0.3 + 0.7.6 + + diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java new file mode 100644 index 0000000000..ee08f2b1fb --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.archaius.dynamosources; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DynamoSourcesApplication { + + public static void main(String[] args) { + SpringApplication.run(DynamoSourcesApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java new file mode 100644 index 0000000000..7b533e8021 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.config; + +import java.util.Arrays; + +import org.apache.commons.configuration.AbstractConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; +import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; +import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; +import com.amazonaws.services.dynamodbv2.util.TableUtils; +import com.baeldung.spring.cloud.archaius.dynamosources.dynamodb.ArchaiusProperties; +import com.baeldung.spring.cloud.archaius.dynamosources.dynamodb.ArchaiusPropertiesRepository; +import com.netflix.config.DynamicConfiguration; +import com.netflix.config.FixedDelayPollingScheduler; +import com.netflix.config.PolledConfigurationSource; +import com.netflix.config.sources.DynamoDbConfigurationSource; + +@Configuration +public class ApplicationPropertiesConfigurations { + + @Autowired + AmazonDynamoDB amazonDynamoDb; + + @Autowired + private ArchaiusPropertiesRepository repository; + + @Bean + public AbstractConfiguration addApplicationPropertiesSource() { + // Normally, the DB Table would be already created and populated. + // In this case, we'll do it just before creating the archaius config source that uses it + initDatabase(); + PolledConfigurationSource source = new DynamoDbConfigurationSource(amazonDynamoDb); + return new DynamicConfiguration(source, new FixedDelayPollingScheduler()); + } + + private void initDatabase() { + // Create the table + DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDb); + CreateTableRequest tableRequest = mapper.generateCreateTableRequest(ArchaiusProperties.class); + tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L)); + TableUtils.createTableIfNotExists(amazonDynamoDb, tableRequest); + + // Populate the table + ArchaiusProperties property = new ArchaiusProperties("baeldung.archaius.properties.one", "one FROM:dynamoDB"); + ArchaiusProperties property3 = new ArchaiusProperties("baeldung.archaius.properties.three", "three FROM:dynamoDB"); + repository.saveAll(Arrays.asList(property, property3)); + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java new file mode 100644 index 0000000000..8f12051a7f --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.config; + +import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.amazonaws.auth.AWSCredentialsProvider; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; + +@Configuration +@EnableDynamoDBRepositories(basePackages = "com.baeldung.spring.cloud.archaius.dynamosources.dynamodb") +public class DynamoDbConfiguration { + + @Value("${amazon.dynamodb.endpoint}") + private String amazonDynamoDBEndpoint; + + @Value("${aws.accessKeyId}") + private String amazonDynamoDBAccessKeyId; + + @Value("${aws.secretKey}") + private String amazonDynamoDBSecretKey; + + @Bean + public AmazonDynamoDB amazonDynamoDB() { + AmazonDynamoDB amazonDynamoDB = AmazonDynamoDBClientBuilder.standard() + .withCredentials(amazonAWSCredentials()) + .withEndpointConfiguration(setupEndpointConfiguration()) + .build(); + + return amazonDynamoDB; + } + + private AWSCredentialsProvider amazonAWSCredentials() { + return new AWSStaticCredentialsProvider(new BasicAWSCredentials(amazonDynamoDBAccessKeyId, amazonDynamoDBSecretKey)); + } + + private EndpointConfiguration setupEndpointConfiguration() { + return new EndpointConfiguration(amazonDynamoDBEndpoint, Regions.DEFAULT_REGION.getName()); + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..2ac5055fe3 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java new file mode 100644 index 0000000000..016f8433cf --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.dynamodb; + +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +@DynamoDBTable(tableName = "archaiusProperties") +public class ArchaiusProperties { + + @DynamoDBHashKey + @DynamoDBAttribute + private String key; + + @DynamoDBAttribute + private String value; +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java new file mode 100644 index 0000000000..fbcc953261 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.cloud.archaius.dynamosources.dynamodb; + +import org.springframework.data.repository.CrudRepository; + +public interface ArchaiusPropertiesRepository extends CrudRepository { + +} diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties new file mode 100644 index 0000000000..3823d2685f --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties @@ -0,0 +1,6 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties +amazon.dynamodb.endpoint=http://localhost:8000/ +aws.accessKeyId=key +aws.secretKey=key2 diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java new file mode 100644 index 0000000000..3802cb99cd --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.spring.cloud.archaius.dynamosources; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusDynamoDbLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:dynamoDB"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:dynamoDB"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml b/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml new file mode 100644 index 0000000000..2f3f2b084a --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + extra-configs + 1.0.0-SNAPSHOT + jar + extra-configs + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-netflix-archaius + + + + + + + org.springframework.cloud + spring-cloud-netflix + ${spring-cloud-dependencies.version} + pom + import + + + + + 2.0.1.RELEASE + + diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java new file mode 100644 index 0000000000..4747d875db --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.archaius.extraconfigs; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ExtraConfigsApplication { + + public static void main(String[] args) { + // System properties can be set as command line arguments too + System.setProperty("archaius.configurationSource.additionalUrls", "classpath:other-config-dir/extra.properties"); + System.setProperty("archaius.configurationSource.defaultFileName", "other.properties"); + SpringApplication.run(ExtraConfigsApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java new file mode 100644 index 0000000000..382c6b3a2c --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java @@ -0,0 +1,60 @@ +package com.baeldung.spring.cloud.archaius.extraconfigs.controllers; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + @Value("${baeldung.archaius.properties.one:not found!}") + private String propertyOneWithValue; + + @Value("${baeldung.archaius.properties.two:not found!}") + private String propertyTwoWithValue; + + @Value("${baeldung.archaius.properties.three:not found!}") + private String propertyThreeWithValue; + + @Value("${baeldung.archaius.properties.four:not found!}") + private String propertyFourWithValue; + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.four", "not found!"); + + @GetMapping("/properties-from-value") + public Map getPropertiesFromValue() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithValue); + properties.put("baeldung.archaius.properties.two", propertyTwoWithValue); + properties.put("baeldung.archaius.properties.three", propertyThreeWithValue); + properties.put("baeldung.archaius.properties.four", propertyFourWithValue); + return properties; + } + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithDynamic.get()); + properties.put("baeldung.archaius.properties.two", propertyTwoWithDynamic.get()); + properties.put("baeldung.archaius.properties.three", propertyThreeWithDynamic.get()); + properties.put("baeldung.archaius.properties.four", propertyFourWithDynamic.get()); + return properties; + } + +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/application.properties new file mode 100644 index 0000000000..1e36b134d4 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8081 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties new file mode 100644 index 0000000000..ea99914cc1 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:extra.properties +baeldung.archaius.properties.three=three FROM:extra.properties diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other.properties b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other.properties new file mode 100644 index 0000000000..26796b7341 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:other.properties +baeldung.archaius.properties.four=four FROM:other.properties diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java new file mode 100644 index 0000000000..232ca73352 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java @@ -0,0 +1,54 @@ +package com.baeldung.spring.cloud.archaius.extraconfigs; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusExtraConfigsLiveTest { + + private static final String BASE_URL = "http://localhost:8081"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:application.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:extra.properties"); + map.put("baeldung.archaius.properties.four", "four FROM:other.properties"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4c2531f490 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.archaius.extraconfigs.ExtraConfigsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ExtraConfigsApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml b/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml new file mode 100644 index 0000000000..bb283576d8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + jdbc-config + jar + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + + + diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java new file mode 100644 index 0000000000..ee7beec87b --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class JdbcSourcesApplication { + + public static void main(String[] args) { + SpringApplication.run(JdbcSourcesApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java new file mode 100644 index 0000000000..f3eed0c2b5 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig.config; + +import javax.sql.DataSource; + +import org.apache.commons.configuration.AbstractConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.netflix.config.DynamicConfiguration; +import com.netflix.config.FixedDelayPollingScheduler; +import com.netflix.config.PolledConfigurationSource; +import com.netflix.config.sources.JDBCConfigurationSource; + +@Configuration +public class ApplicationPropertiesConfigurations { + + @Autowired + DataSource h2DataSource; + + @Bean + public AbstractConfiguration addApplicationPropertiesSource() { + PolledConfigurationSource source = new JDBCConfigurationSource(h2DataSource, "select distinct key, value from properties", "key", "value"); + return new DynamicConfiguration(source, new FixedDelayPollingScheduler()); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..a793f39b29 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java new file mode 100644 index 0000000000..cc2783b506 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig.jdbc; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Properties { + + @Id + private String key; + + @SuppressWarnings("unused") + private String value; +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties new file mode 100644 index 0000000000..eca873f897 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties +spring.h2.console.enabled=true diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql new file mode 100644 index 0000000000..eb80126d48 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql @@ -0,0 +1,5 @@ +insert into properties +values('baeldung.archaius.properties.one', 'one FROM:jdbc_source'); + +insert into properties +values('baeldung.archaius.properties.three', 'three FROM:jdbc_source'); \ No newline at end of file diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java new file mode 100644 index 0000000000..91d5f5754e --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusJDBCSourceLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:jdbc_source"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:jdbc_source"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/pom.xml b/spring-cloud/spring-cloud-archaius/pom.xml new file mode 100644 index 0000000000..fd3e34e463 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + spring-cloud-archaius + Spring Cloud Archaius Pom parent + pom + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + basic-config + additional-sources-simple + extra-configs + jdbc-config + dynamodb-config + zookeeper-config + + + + + org.springframework.cloud + spring-cloud-starter-netflix-archaius + + + org.springframework.boot + spring-boot-starter-test + + + org.assertj + assertj-core + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + + + org.springframework.cloud + spring-cloud-netflix + ${spring-cloud-dependencies.version} + pom + import + + + + + + 2.0.1.RELEASE + 1.2.0 + + diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml new file mode 100644 index 0000000000..8f8ec99ad8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + zookeeper-config + jar + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-zookeeper-config + ${cloud.zookeeper.version} + + + org.apache.zookeeper + zookeeper + + + + + org.apache.zookeeper + zookeeper + ${zookeeper.version} + + + org.slf4j + slf4j-log4j12 + + + + + + + 2.0.0.RELEASE + 3.4.13 + + diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java new file mode 100644 index 0000000000..12119e3e29 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ZookeeperConfigApplication { + + public static void main(String[] args) { + SpringApplication.run(ZookeeperConfigApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java new file mode 100644 index 0000000000..59ef10aaf7 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java @@ -0,0 +1,58 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig.config; + +import org.apache.curator.framework.CuratorFramework; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +/** + * + * Ideally, we wouldn't need to initialize the zookeeper config values. + * Here we do it to verify that configurations are being retrieved. + * + */ +@Component +public class ZookeeperConfigsInitializer { + + private static final String CONFIG_BASE_NODE_PATH = "/config"; + private static final String APPLICATION_BASE_NODE_PATH = CONFIG_BASE_NODE_PATH + "/application"; + + @Autowired + CuratorFramework client; + + @EventListener + public void appReady(ApplicationReadyEvent event) throws Exception { + String pathOne = APPLICATION_BASE_NODE_PATH + "/baeldung.archaius.properties.one"; + String valueOne = "one FROM:zookeeper"; + String pathThree = APPLICATION_BASE_NODE_PATH + "/baeldung.archaius.properties.three"; + String valueThree = "three FROM:zookeeper"; + createBaseNodes(); + setValue(pathOne, valueOne); + setValue(pathThree, valueThree); + } + + private void setValue(String path, String value) throws Exception { + if (client.checkExists() + .forPath(path) == null) { + client.create() + .forPath(path, value.getBytes()); + } else { + client.setData() + .forPath(path, value.getBytes()); + } + } + + private void createBaseNodes() throws Exception { + if (client.checkExists() + .forPath(CONFIG_BASE_NODE_PATH) == null) { + client.create() + .forPath(CONFIG_BASE_NODE_PATH); + } + if (client.checkExists() + .forPath(APPLICATION_BASE_NODE_PATH) == null) { + client.create() + .forPath(APPLICATION_BASE_NODE_PATH); + } + } +} diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..c8a5e53ee4 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java @@ -0,0 +1,51 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + @Value("${baeldung.archaius.properties.one:not found!}") + private String propertyOneWithValue; + + @Value("${baeldung.archaius.properties.two:not found!}") + private String propertyTwoWithValue; + + @Value("${baeldung.archaius.properties.three:not found!}") + private String propertyThreeWithValue; + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + return properties; + } + + @GetMapping("/properties-from-value") + public Map getPropertiesFromValue() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithValue); + properties.put("baeldung.archaius.properties.two", propertyTwoWithValue); + properties.put("baeldung.archaius.properties.three", propertyThreeWithValue); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties new file mode 100644 index 0000000000..91ad18a932 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties +spring.application.name=zookeeper-config diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java new file mode 100644 index 0000000000..ff4358cb8f --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.spring.cloud.archaius.zookeeperconfig; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusZookeeperLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:zookeeper"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:zookeeper"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-aws/pom.xml b/spring-cloud/spring-cloud-aws/pom.xml index 773bf27fc2..6933845173 100644 --- a/spring-cloud/spring-cloud-aws/pom.xml +++ b/spring-cloud/spring-cloud-aws/pom.xml @@ -4,7 +4,6 @@ 4.0.0 com.baeldung.spring.cloud spring-cloud-aws - 0.0.1-SNAPSHOT jar Spring Cloud AWS Spring Cloud AWS Examples @@ -44,7 +43,6 @@ org.postgresql postgresql - @@ -59,27 +57,8 @@ - - - - maven-surefire-plugin - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - com.baeldung.spring.cloud.aws.SpringCloudAwsApplication - UTF-8 - UTF-8 - 1.8 Dalston.SR4 - diff --git a/spring-cloud/spring-cloud-aws/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..fcba9c4132 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.aws.InstanceProfileAwsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = InstanceProfileAwsApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6016788eab --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.bootstrap.config.ConfigApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/discovery/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6016788eab --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/discovery/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.bootstrap.config.ConfigApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..1e2db33395 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.bootstrap.discovery.DiscoveryApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = DiscoveryApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ef3bb5ef95 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.bootstrap.gateway.GatewayApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GatewayApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0ffc2410e3 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.bootstrap.svcbook.BookServiceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookServiceApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3589666f17 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.bootstrap.svcrating.RatingServiceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = RatingServiceApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4403d9e93b --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.bootstrap.zipkin.ZipkinApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ZipkinApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-config/client/pom.xml b/spring-cloud/spring-cloud-config/client/pom.xml index bd8c817256..800a496a82 100644 --- a/spring-cloud/spring-cloud-config/client/pom.xml +++ b/spring-cloud/spring-cloud-config/client/pom.xml @@ -15,18 +15,15 @@ org.springframework.cloud spring-cloud-starter-config - ${spring-cloud-starter-config.version} - + org.springframework.boot spring-boot-starter-web - ${org.springframework.boot.version} - + org.springframework.boot spring-boot-starter-test - ${org.springframework.boot.version} test @@ -40,8 +37,4 @@ - - 1.2.2.RELEASE - 1.4.2.RELEASE - diff --git a/spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java b/spring-cloud/spring-cloud-config/client/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 76% rename from spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java rename to spring-cloud/spring-cloud-config/client/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 9bca369c64..d727772cf9 100644 --- a/spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java +++ b/spring-cloud/spring-cloud-config/client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloud.config.client; +package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; @@ -6,10 +6,12 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import com.baeldung.spring.cloud.config.client.ConfigClient; + @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ConfigClient.class) @WebAppConfiguration -public class ConfigClientLiveTest { +public class SpringContextIntegrationTest { @Test public void contextLoads() { } diff --git a/spring-cloud/spring-cloud-config/server/pom.xml b/spring-cloud/spring-cloud-config/server/pom.xml index 61b27244b6..7bbb903cf9 100644 --- a/spring-cloud/spring-cloud-config/server/pom.xml +++ b/spring-cloud/spring-cloud-config/server/pom.xml @@ -15,23 +15,19 @@ org.springframework.cloud spring-cloud-config-server - ${spring-cloud-config-server.version} - + org.springframework.boot spring-boot-starter-security - ${org.springframework.boot.version} - + org.springframework.boot spring-boot-starter-web - ${org.springframework.boot.version} - + org.springframework.boot spring-boot-starter-test - ${org.springframework.boot.version} test @@ -41,14 +37,8 @@ org.springframework.boot spring-boot-maven-plugin - ${org.springframework.boot.version} - + - - 1.2.2.RELEASE - 1.4.2.RELEASE - - diff --git a/spring-cloud/spring-cloud-config/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-config/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..cd30392d4f --- /dev/null +++ b/spring-cloud/spring-cloud-config/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +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.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.cloud.config.server.ConfigServer; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = ConfigServer.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + @Test + public void contextLoads() { + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/pom.xml b/spring-cloud/spring-cloud-connectors-heroku/pom.xml index 875aa5ceaa..f00c9eb1fc 100644 --- a/spring-cloud/spring-cloud-connectors-heroku/pom.xml +++ b/spring-cloud/spring-cloud-connectors-heroku/pom.xml @@ -33,8 +33,7 @@ org.postgresql postgresql - ${postgresql.version} - + com.h2database h2 @@ -54,33 +53,8 @@ - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - true - - - - - Brixton.SR7 - 2.19.1 9.4-1201-jdbc4 - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-connectors-heroku/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a705f18bc6 --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.connectors.heroku.ConnectorsHerokuApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConnectorsHerokuApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-consul/pom.xml b/spring-cloud/spring-cloud-consul/pom.xml index 8181832bea..2a2714d597 100644 --- a/spring-cloud/spring-cloud-consul/pom.xml +++ b/spring-cloud/spring-cloud-consul/pom.xml @@ -25,6 +25,13 @@ spring-cloud-starter-consul-config ${spring-cloud-starter-consul.version} + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-cloud/spring-cloud-consul/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-consul/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6290ccc03e --- /dev/null +++ b/spring-cloud/spring-cloud-consul/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +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.spring.cloud.consul.discovery.DiscoveryClientApplication; +import com.baeldung.spring.cloud.consul.health.ServiceDiscoveryApplication; +import com.baeldung.spring.cloud.consul.properties.DistributedPropertiesApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { DiscoveryClientApplication.class, ServiceDiscoveryApplication.class, + DistributedPropertiesApplication.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..1c1192cc3f --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.springcloudcontractconsumer.SpringCloudContractConsumerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudContractConsumerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2b6703ae5c --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.springcloudcontractproducer.SpringCloudContractProducerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudContractProducerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml index c7822d51ee..8bc51adcab 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml @@ -28,6 +28,24 @@ spring-boot-starter-web ${spring-boot-starter-web.version} + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + + + org.springframework.boot + spring-boot-test + 1.5.10.RELEASE + test + + + org.springframework + spring-test + 4.0.5.RELEASE + test + diff --git a/spring-cloud/spring-cloud-functions/README.MD b/spring-cloud/spring-cloud-functions/README.MD new file mode 100644 index 0000000000..c766dd1dc6 --- /dev/null +++ b/spring-cloud/spring-cloud-functions/README.MD @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Serverless Functions with Spring Cloud Function](https://www.baeldung.com/spring-cloud-function) diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml new file mode 100644 index 0000000000..8b2b0ad385 --- /dev/null +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + com.baeldung.spring + cloudfunction-aws + 0.0.1-SNAPSHOT + jar + + cloudfunction-aws + Demo project for Spring Cloud Function + + + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + 1.0.1.RELEASE + 2.0.2 + + + + + org.springframework.cloud + spring-cloud-function-adapter-aws + ${spring-cloud-function.version} + + + + + org.springframework.cloud + spring-cloud-starter-function-web + 1.0.1.RELEASE + + + com.amazonaws + aws-lambda-java-events + ${aws-lambda-events.version} + provided + + + com.amazonaws + aws-lambda-java-core + 1.1.0 + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.springframework.boot.experimental + spring-boot-thin-layout + 1.0.10.RELEASE + + + + + org.apache.maven.plugins + maven-shade-plugin + + false + true + aws + + + + + + diff --git a/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java new file mode 100644 index 0000000000..34e97d3b6c --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionAwsApplication.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.cloudfunction.aws; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +@SpringBootApplication +public class CloudFunctionAwsApplication { + + public static void main(String[] args) { + SpringApplication.run(CloudFunctionAwsApplication.class, args); + } + + @Bean + public Function reverseString() { + return value -> new StringBuilder(value).reverse().toString(); + } + +} diff --git a/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java new file mode 100644 index 0000000000..52514dcd12 --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/StringReverseHandler.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.cloudfunction.aws; + +import org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler; + +public class StringReverseHandler extends SpringBootRequestHandler { + +} diff --git a/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java new file mode 100644 index 0000000000..c443b98c18 --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/main/java/com/baeldung/spring/cloudfunction/aws/functions/Greeter.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.cloudfunction.functions.aws; + +import java.util.function.Function; + +public class Greeter implements Function { + + @Override + public String apply(String s) { + return "Hello " + s + ", and welcome to Spring Cloud Function!!!"; + } +} diff --git a/spring-cloud/spring-cloud-functions/src/main/resources/application.properties b/spring-cloud/spring-cloud-functions/src/main/resources/application.properties new file mode 100644 index 0000000000..b445bfa4ed --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.cloud.function.scan.packages: com.baeldung.spring.cloudfunction.functions.aws \ No newline at end of file diff --git a/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java new file mode 100644 index 0000000000..6039debe3f --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/CloudFunctionApplicationTests.java @@ -0,0 +1,33 @@ +package com.baeldung.spring.cloudfunction.aws; + +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 org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; + +import static org.assertj.core.api.Java6Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class CloudFunctionApplicationTests { + + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate testRestTemplate; + + @Test + public void givenAString_whenReverseStringCloudFunctionInvoked_thenStringIsReversed() { + assertThat(this.testRestTemplate.getForObject("http://localhost:" + port + "/reverseString/HelloWorld", String.class)).isEqualTo("dlroWolleH"); + } + + @Test + public void givenAString_whenGreeterCloudFunctionInvoked_thenPrintsGreeting() { + assertThat(this.testRestTemplate.getForObject("http://localhost:" + port + "/greeter/BaeldungUser", String.class)).isEqualTo("Hello BaeldungUser, and welcome to Spring Cloud Function!!!"); + } + +} diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index db57373b6f..4d8b57d4cf 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -28,7 +28,7 @@ org.springframework.cloud - spring-cloud-starter-gateway + spring-cloud-starter org.springframework.boot @@ -38,6 +38,11 @@ org.springframework.boot spring-boot-starter-webflux + + org.springframework.boot + spring-boot-starter-test + test + org.hibernate @@ -54,27 +59,8 @@ - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - 2.0.0.RC2 + 2.0.1.RELEASE 6.0.2.Final diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f2addf5c1a --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.GatewayApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GatewayApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml index ce1e1856ed..11b9275b46 100644 --- a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/pom.xml @@ -24,33 +24,32 @@ org.springframework.cloud spring-cloud-starter-hystrix - ${spring-cloud-starter-hystrix.version} org.springframework.cloud spring-cloud-starter-hystrix-dashboard - ${spring-cloud-starter-hystrix.version} org.springframework.cloud spring-cloud-starter-feign - ${spring-cloud-starter-feign.version} org.springframework.boot spring-boot-starter-web - ${spring-boot-starter-web.version} org.springframework.boot spring-boot-starter-thymeleaf - ${spring-boot-starter-web.version} org.springframework.boot spring-boot-starter-actuator - ${spring-boot-starter-web.version} + + org.springframework.boot + spring-boot-starter-test + test + diff --git a/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationTests.java b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 54% rename from spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationTests.java rename to spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 3969c7ba2d..ce57cf5052 100644 --- a/spring-cloud-bus/spring-cloud-config-server/src/test/java/com/baeldung/SpringCloudConfigServerApplicationTests.java +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,13 +1,15 @@ -package com.baeldung; +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.spring.cloud.kubernetes.backend.KubernetesBackendApplication; + @RunWith(SpringRunner.class) -@SpringBootTest -public class SpringCloudConfigServerApplicationTests { +@SpringBootTest(classes = KubernetesBackendApplication.class) +public class SpringContextIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java deleted file mode 100644 index 19ad9676cb..0000000000 --- a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.spring.cloud.kubernetes.frontend; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class KubernetesFrontendApplicationIntegrationTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f7e9e35540 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +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.spring.cloud.kubernetes.frontend.KubernetesFrontendApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KubernetesFrontendApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..24e758ff82 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BooksApiApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapApplicationIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 72% rename from spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapApplicationIntegrationTest.java rename to spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 7c54288665..28c6e67377 100644 --- a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapApplicationIntegrationTest.java +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -6,10 +6,10 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest -public class SpringBootBootstrapApplicationIntegrationTest { - +@SpringBootTest(classes = SpringCloudRestConfigApplication.class) +public class SpringContextIntegrationTest { @Test public void contextLoads() { } + } diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e22359a016 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudRestServerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..07d7db0505 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookReviewsApiApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml index eb8398848c..12125f4cf3 100644 --- a/spring-cloud/spring-cloud-ribbon-client/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -2,7 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - spring-cloud-ribbon + spring-cloud-ribbon-client 0.0.1-SNAPSHOT jar spring-cloud-ribbon-client @@ -38,25 +38,6 @@ - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - Brixton.SR7 diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..baa1b12eff --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.ribbon.client.ServerLocationApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ServerLocationApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-security/README.md b/spring-cloud/spring-cloud-security/README.md deleted file mode 100644 index 39af52c077..0000000000 --- a/spring-cloud/spring-cloud-security/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# README # - -This README would normally document whatever steps are necessary to get your application up and running. - -### What is this repository for? ### - -* Quick summary -* Version -* [Learn Markdown](https://bitbucket.org/tutorials/markdowndemo) - -### How do I get set up? ### - -* Summary of set up -* Configuration -* Dependencies -* Database configuration -* How to run tests -* Deployment instructions - -### Contribution guidelines ### - -* Writing tests -* Code review -* Other guidelines - -### Who do I talk to? ### - -* Repo owner or admin -* Other community or team contact \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index f2d6308374..340c276c2d 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -2,18 +2,15 @@ 4.0.0 - com.baeldung auth-client - 0.0.1-SNAPSHOT jar auth-client - Demo project for Spring Boot - + Spring Cloud Security APP Client Module + - parent-boot-1 + spring-cloud-security com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + 1.0.0-SNAPSHOT @@ -88,9 +85,6 @@ - UTF-8 - UTF-8 - 1.8 2.1.0 Dalston.SR4 diff --git a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java similarity index 87% rename from spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java rename to spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java index ca89575ee0..37cff095db 100644 --- a/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationTests.java +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/com/example/springoath2/Springoath2ApplicationIntegrationTest.java @@ -9,7 +9,7 @@ import com.baeldung.CloudSite; @RunWith(SpringRunner.class) @SpringBootTest(classes = CloudSite.class) -public class Springoath2ApplicationTests { +public class Springoath2ApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 64% rename from spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java rename to spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 1add635ed8..60a208d6f4 100644 --- a/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,13 +1,15 @@ -package com.baeldung.springbootmvc; +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.CloudSite; + @RunWith(SpringRunner.class) -@SpringBootTest -public class SpringBootMvcApplicationTests { +@SpringBootTest(classes = CloudSite.class) +public class SpringContextIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-security/auth-resource/pom.xml b/spring-cloud/spring-cloud-security/auth-resource/pom.xml index 0115259108..09474b2a4d 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -3,21 +3,18 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung auth-resource - 0.0.1-SNAPSHOT jar auth-resource - Demo project for Spring Boot + Spring Cloud Security APP Resource Module - parent-boot-1 + spring-cloud-security com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + 1.0.0-SNAPSHOT - + org.springframework.security.oauth @@ -60,9 +57,6 @@ - UTF-8 - UTF-8 - 1.8 Edgware.RELEASE diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationTests.java b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationIntegrationTest.java similarity index 85% rename from spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationTests.java rename to spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationIntegrationTest.java index e0fe7006d9..3caa06ba4d 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationTests.java +++ b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/com/baeldung/service/personservice/PersonserviceApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class PersonserviceApplicationTests { +public class PersonserviceApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4d4c312bce --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +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.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-security/auth-server/pom.xml b/spring-cloud/spring-cloud-security/auth-server/pom.xml index b4367935e3..92f92808f6 100644 --- a/spring-cloud/spring-cloud-security/auth-server/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-server/pom.xml @@ -2,15 +2,13 @@ 4.0.0 - com.baeldung auth-server - 0.0.1-SNAPSHOT - + Spring Cloud Security APP Server Module + - parent-boot-1 + spring-cloud-security com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + 1.0.0-SNAPSHOT diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 64% rename from spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java rename to spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 9bd0fd8c24..63a89ac45c 100644 --- a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java +++ b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,13 +1,15 @@ -package org.baeldung.spring.cloud; +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.AuthServer; + @RunWith(SpringRunner.class) -@SpringBootTest -public class TimeProcessorApplicationIntegrationTest { +@SpringBootTest(classes = AuthServer.class) +public class SpringContextIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-security/pom.xml b/spring-cloud/spring-cloud-security/pom.xml new file mode 100644 index 0000000000..1cf8751548 --- /dev/null +++ b/spring-cloud/spring-cloud-security/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + spring-cloud-security + pom + 1.0.0-SNAPSHOT + spring-cloud-security + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 + + + + auth-client + auth-resource + auth-server + + + diff --git a/spring-cloud/spring-cloud-stream-starters/boot/.gitignore b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/.gitignore similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/.gitignore rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/.gitignore diff --git a/spring-cloud/spring-cloud-stream-starters/boot/pom.xml b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml similarity index 80% rename from spring-cloud/spring-cloud-stream-starters/boot/pom.xml rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml index bf725da5cf..6f582576d8 100644 --- a/spring-cloud/spring-cloud-stream-starters/boot/pom.xml +++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/pom.xml @@ -1,11 +1,11 @@ - - + + 4.0.0 com.baeldung.twitterhdfs twitterhdfs jar - 1.0.0 + 1.0.0-SNAPSHOT twitterhdfs @@ -45,9 +45,6 @@ - UTF-8 - UTF-8 - 1.8 1.3.1.RELEASE diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/aggregate/AggregateApp.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/aggregate/AggregateApp.java similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/aggregate/AggregateApp.java rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/aggregate/AggregateApp.java diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/processor/ProcessorApp.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/processor/ProcessorApp.java similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/processor/ProcessorApp.java rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/processor/ProcessorApp.java diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/sink/SinkApp.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/sink/SinkApp.java similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/sink/SinkApp.java rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/sink/SinkApp.java diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/source/SourceApp.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/source/SourceApp.java similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/java/com/baeldung/twitterhdfs/source/SourceApp.java rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/java/com/baeldung/twitterhdfs/source/SourceApp.java diff --git a/spring-cloud/spring-cloud-stream-starters/boot/src/main/resources/application.properties b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/resources/application.properties similarity index 100% rename from spring-cloud/spring-cloud-stream-starters/boot/src/main/resources/application.properties rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/resources/application.properties diff --git a/spring-remoting/remoting-hessian-burlap/server/src/main/resources/logback.xml b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/resources/logback.xml similarity index 100% rename from spring-remoting/remoting-hessian-burlap/server/src/main/resources/logback.xml rename to spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/main/resources/logback.xml diff --git a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3d370e7b48 --- /dev/null +++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +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.twitterhdfs.aggregate.AggregateApp; +import com.baeldung.twitterhdfs.processor.ProcessorApp; +import com.baeldung.twitterhdfs.sink.SinkApp; +import com.baeldung.twitterhdfs.source.SourceApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {AggregateApp.class, ProcessorApp.class, SinkApp.class, SourceApp.class}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..70c5f46aa1 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.stream.rabbit.MultipleOutputsServiceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MultipleOutputsServiceApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-task/pom.xml b/spring-cloud/spring-cloud-task/pom.xml new file mode 100644 index 0000000000..ef76d464bc --- /dev/null +++ b/spring-cloud/spring-cloud-task/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + com.baeldung.spring.cloud + spring-cloud-task + 1.0.0-SNAPSHOT + pom + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-1 + + + + springcloudtaskbatch + springcloudtasksink + + + + + + org.springframework.cloud + spring-cloud-task-dependencies + ${spring-cloud-task.version} + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud-dependencies.version} + pom + import + + + + + + Brixton.SR7 + 1.2.2.RELEASE + + + diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml index afe609288d..89c9318c4e 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml @@ -2,14 +2,13 @@ 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.cloud - springcloudtask - 0.0.1-SNAPSHOT + springcloudtaskbatch + springcloudtaskbatch - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + spring-cloud-task + com.baeldung.spring.cloud + 1.0.0-SNAPSHOT @@ -46,18 +45,6 @@ - - - - org.springframework.cloud - spring-cloud-task-dependencies - ${spring-cloud-task.version} - pom - import - - - - @@ -69,10 +56,6 @@ com.baeldung.TaskDemo - UTF-8 - UTF-8 - 1.8 - 1.2.2.RELEASE diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4b5aff2db8 --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +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.task.JobConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = JobConfiguration.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml index fdcbabdd51..ca0de342a9 100644 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml @@ -2,19 +2,15 @@ 4.0.0 - - com.baeldung SpringCloudTaskSink - 0.0.1-SNAPSHOT jar SpringCloudTaskSink Demo project for Spring Boot - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../../parent-boot-1 + + spring-cloud-task + com.baeldung.spring.cloud + 1.0.0-SNAPSHOT @@ -36,11 +32,6 @@ spring-boot-starter-test test - - org.springframework.boot - spring-boot-starter-test - test - org.springframework.cloud @@ -49,25 +40,6 @@ - - - - org.springframework.cloud - spring-cloud-task-dependencies - ${spring-cloud-task.version} - pom - import - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - @@ -78,11 +50,7 @@ - UTF-8 - UTF-8 - 1.8 1.2.2.RELEASE - Edgware.SR2 1.3.0.RELEASE diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationTests.java b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationIntegrationTest.java similarity index 97% rename from spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationTests.java rename to spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationIntegrationTest.java index 1f47eada14..104c04138e 100644 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationTests.java +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/com/baeldung/SpringCloudTaskFinal/SpringCloudTaskSinkApplicationIntegrationTest.java @@ -24,7 +24,7 @@ import static org.mockito.Mockito.verify; @RunWith(SpringRunner.class) @SpringBootTest( classes = SpringCloudTaskSinkApplication.class) -public class SpringCloudTaskSinkApplicationTests { +public class SpringCloudTaskSinkApplicationIntegrationTest { @Autowired ApplicationContext context; diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..b8dd03d65f --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.SpringCloudTaskFinal.SpringCloudTaskSinkApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudTaskSinkApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-vault/.gitignore b/spring-cloud/spring-cloud-vault/.gitignore new file mode 100644 index 0000000000..e6237b6f81 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/.gitignore @@ -0,0 +1,29 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +## Extra +/vault-data/ +*.log diff --git a/spring-cloud/spring-cloud-vault/database-setup.sql b/spring-cloud/spring-cloud-vault/database-setup.sql new file mode 100644 index 0000000000..4bb1293f74 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/database-setup.sql @@ -0,0 +1,20 @@ +-- +-- Sample schema for testing vault database secrets +-- +create schema fakebank; +use fakebank; +create table account( + id decimal(16,0), + name varchar(30), + branch_id decimal(16,0), + customer_id decimal(16,0), + primary key (id)); + +-- +-- MySQL user that will be used by Vault to create other users on demand +-- +create user 'fakebank-admin'@'%' identified by 'Sup&rSecre7!' +grant all privileges on fakebank.* to 'fakebank-admin'@'%' with grant option; +grant create user on *.* to 'fakebank-admin' with grant option; + +flush privileges; diff --git a/spring-cloud/spring-cloud-vault/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml new file mode 100644 index 0000000000..68b8e44875 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.baeldung.spring.cloud + spring-cloud-vault + jar + + spring-cloud-vault + Demo project for Spring Boot + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + UTF-8 + UTF-8 + 1.8 + Finchley.SR1 + + + + + + + + + org.springframework.cloud + spring-cloud-starter-vault-config + + + + org.springframework.cloud + spring-cloud-vault-config-databases + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + mysql + mysql-connector-java + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-cloud/spring-cloud-vault/sample-policy.hcl b/spring-cloud/spring-cloud-vault/sample-policy.hcl new file mode 100644 index 0000000000..554888661e --- /dev/null +++ b/spring-cloud/spring-cloud-vault/sample-policy.hcl @@ -0,0 +1,6 @@ +path "secret/fakebank" { + capabilities = ["read"] + allowed_parameters = { + "api_key" = [] + } +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java new file mode 100644 index 0000000000..81ece1ca4c --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplication.java @@ -0,0 +1,12 @@ +package org.baeldung.spring.cloud.vaultsample; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class VaultSampleApplication { + + public static void main(String[] args) { + SpringApplication.run(VaultSampleApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-vault/src/main/resources/application.yml b/spring-cloud/spring-cloud-vault/src/main/resources/application.yml new file mode 100644 index 0000000000..3d347ec855 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + application: + name: fakebank + + datasource: + url: jdbc:mysql://localhost:3306/fakebank diff --git a/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml b/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml new file mode 100644 index 0000000000..1e837c4920 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml @@ -0,0 +1,37 @@ +spring: + cloud: + vault: + uri: https://localhost:8200 + connection-timeout: 5000 + read-timeout: 15000 + config: + order: -10 + + ssl: + trust-store: classpath:/vault.jks + trust-store-password: changeit + + generic: + enabled: true + application-name: fakebank + + kv: + enabled: false + backend: kv + application-name: fakebank + + database: + enabled: true + role: fakebank-accounts-rw +# backend: database +# username-property: spring.datasource.username +# password-property: spring.datasource.password + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-vault/src/main/resources/vault.jks b/spring-cloud/spring-cloud-vault/src/main/resources/vault.jks new file mode 100644 index 0000000000..7090707543 Binary files /dev/null and b/spring-cloud/spring-cloud-vault/src/main/resources/vault.jks differ diff --git a/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java new file mode 100644 index 0000000000..7a9c5ba11a --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/VaultSampleApplicationLiveTest.java @@ -0,0 +1,66 @@ +package org.baeldung.spring.cloud.vaultsample; + +import static org.junit.Assert.assertEquals; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; + +import javax.sql.DataSource; + +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.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class VaultSampleApplicationLiveTest { + + @Autowired + Environment env; + + @Autowired + DataSource datasource; + + + @Test + public void whenGenericBackendEnabled_thenEnvHasAccessToVaultSecrets() { + + String fooValue = env.getProperty("foo"); + assertEquals("test-bar", fooValue); + + } + + @Test + public void whenKvBackendEnabled_thenEnvHasAccessToVaultSecrets() { + + String fooValue = env.getProperty("foo.versioned"); + assertEquals("bar1", fooValue); + + + } + + + @Test + public void whenDatabaseBackendEnabled_thenDatasourceUsesVaultCredentials() { + + try (Connection c = datasource.getConnection()) { + + ResultSet rs = c.createStatement() + .executeQuery("select 1"); + + rs.next(); + Long value = rs.getLong(1); + + assertEquals(Long.valueOf(1), value); + + } catch (SQLException sex) { + throw new RuntimeException(sex); + } + + } + +} diff --git a/spring-cloud/spring-cloud-vault/src/test/resources/bootstrap.properties b/spring-cloud/spring-cloud-vault/src/test/resources/bootstrap.properties new file mode 100644 index 0000000000..8c54227dda --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/resources/bootstrap.properties @@ -0,0 +1,3 @@ +spring.cloud.vault.token=b93d1b0d-15b5-f69e-d311-352a65fa7bc8 + +logging.level.org.springframework=INFO \ No newline at end of file diff --git a/spring-cloud/spring-cloud-vault/src/test/resources/vault.jks b/spring-cloud/spring-cloud-vault/src/test/resources/vault.jks new file mode 100644 index 0000000000..7090707543 Binary files /dev/null and b/spring-cloud/spring-cloud-vault/src/test/resources/vault.jks differ diff --git a/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.cert b/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.cert new file mode 100644 index 0000000000..6a598df419 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.cert @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC+zCCAeOgAwIBAgIJAKoy5OBgOKYwMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV +BAMMCWxvY2FsaG9zdDAeFw0xODA4MDkwMTM1MzJaFw0yODA4MDYwMTM1MzJaMBQx +EjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAMXiHqB5dYdxJ1+abSG55gb3NNo3fzNbkjp/tAIl1FUeyCyyP/yERrkUkhFj +4gg/q1YHUO/ftc0PdL/JBaVBTKnzsxgp7hY/dUEkZqXZ649X0UrJIRd13w5N71cL +P1+PjCrqokMVceU18kK7CyaOmiTKYFmt/RTJQLmFQspmJXNSiq7zUvAgyvoY5TzJ +n7MuSobHXq17pnlm+XbnAgDJUt9yR6BC2dFF20iZU4uTXy2VRngfLey3p+6in0TO +jD4cEMJqwgUbjiI8m/hESCketVkq0W0qkkVfWBNzz5qqGHNRbhZBwT7SM0MuXum+ +qEY7n7jcQAk5BDb613liVQjQ0tkCAwEAAaNQME4wHQYDVR0OBBYEFHYjQ0/HJgXd +BnqM4jLPjmygfi8fMB8GA1UdIwQYMBaAFHYjQ0/HJgXdBnqM4jLPjmygfi8fMAwG +A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBABSf++sinLT9dFnC+B6ut5Zp +haTL7PA1/CdmhTdE2vlFPGGw2BD4c/gphBsHKSNHE96irTqFXI/kl6labQpZ5P8G +JORLfaAyl58UT1FayxL4ISzwsp+UrqO60vxkYyLkbEJjuaxIv11oOoFDIp5oBTqe +BVoCfcTjYtTr+IwwlypLPrVTnDNGX5oPIBbTUFvR0t5RaLZgmXLT78ERhWOLINqh +Yi6j7fYaRm/C5IQ8N/TASot7V0SMH2Rt6PrzJb5SLV8r+yozg2BSfU6hZUyKwABR +N3zppKvKzdhlVo9OuSW3x4Tb3V+CVE/8CmTwRfhab9SCmvmaa2FxI+8/2OPVWDU= +-----END CERTIFICATE----- diff --git a/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.key b/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.key new file mode 100644 index 0000000000..eba611823a --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/vault-config/localhost.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAxeIeoHl1h3EnX5ptIbnmBvc02jd/M1uSOn+0AiXUVR7ILLI/ +/IRGuRSSEWPiCD+rVgdQ79+1zQ90v8kFpUFMqfOzGCnuFj91QSRmpdnrj1fRSskh +F3XfDk3vVws/X4+MKuqiQxVx5TXyQrsLJo6aJMpgWa39FMlAuYVCymYlc1KKrvNS +8CDK+hjlPMmfsy5KhsderXumeWb5ducCAMlS33JHoELZ0UXbSJlTi5NfLZVGeB8t +7Len7qKfRM6MPhwQwmrCBRuOIjyb+ERIKR61WSrRbSqSRV9YE3PPmqoYc1FuFkHB +PtIzQy5e6b6oRjufuNxACTkENvrXeWJVCNDS2QIDAQABAoIBACEyB5VACtlHwCUn +kLshplbwzWr1+F6zM9qgZaAenHoTCd2FoXpI7lxJ+R71tItRsvphi9BRpPvbZehu +XoYUaDnyac7Z6djNmGvvIVEdN4j6YF+9UdHPsjWCGW5uspjjSc5BQisiw9KBtDxB +iGNVdMJLONKSf2wnPrZgho3RiOLJX/poPyGTkMHuhBVvo4oy7Ax3XalaAcufgqwm +YBQJ1Tka+33EUiLkxzJTXxNbIAI2scP8jhGn6mokS0V4gZPxJKUZEyydXRWwi6ex +ua/7q76ELJS5b+xKRYfGsvavFDx8R+LqX8oegALD33ki3rm1MQW7GmikRL98+EVW +Q9mQsqECgYEA/IrP8vycbJOgn1vriNItFcZtczSBlrXCRF0up2cqKMs9c+T5i51x +ZKXK5lo3DfMT+YDM+iiGZ9+vM0UA2VxbFD3XV9mQDBaNC+Duknqxx+OLmWva9YwR +nMaevqVV9LCn+GgUcK+IygEnpzpdP4q8YcXAfGAnZgnihN/AUYAaB70CgYEAyJe4 +yO0S9gAH5aoDdooL0YXrH/Dzd+fAgNsawLhoOltcoZqZFWeAllM0GsrCpfTRltuy +dn9ca3YK0GlWl7h5rDle1HO3nhp1FcpeG1oxmkeQta3PG66uUuMccTAljCLFrEe3 +DguH8+qdjhLk+ZnUB9AVkS79pzdwuEHVljCK600CgYB6mMygkh9B2lzkX9Q0xItc +gcqKXdf3GN9pHq9SVxOxYBDCHUtDirgMeyvHrc4COJneyrc3TcsJzB4aToo9+sbA +SdErdZOnOp9YP+axN1zsw7r2TNSr1UaLjCRuOodC1SuFvMkHdz95iRv946h2+1u+ +PyjVeDxIHc5YYOLU7dI1JQKBgQDF5KDBYNm25brkwcCe3nvgXfzjyyN25KUOupn/ +DS6Oe/m72Lgz3KOIKleaIvS7IvbunJnIu8dioNb0Wye5kJ5A4WyDrhG1IabnM3l6 +BJYw/W9vPSS4y7FhRnuV0wkH4nofh7S5X3jlk02Sj2NkN3Vtq8TLMY++uzwyG4jq +ncM/dQKBgQC+6mA5OfbVN4lRn+zrSiIH5gpvZYPh9wXeTnDWHa13sJsu3e8AQxtk +TfE0W13UV5jhGL8Wvyyxn+doGFTdcZapOlwuoQ6RcgHcVQm2sOl60GAa4idmm0A6 +TcgnIOTyVRlNBoWLCfN83BlGz4gcDpnuZZ/0JuguixgLS323hQlLvg== +-----END RSA PRIVATE KEY----- diff --git a/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl b/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl new file mode 100644 index 0000000000..c880f2d744 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl @@ -0,0 +1,20 @@ +/* + * Sample configuration file for tests + */ + +// Enable UI +ui = true + +// Filesystem storage +storage "file" { + path = "./vault-data" +} + +// TCP Listener using a self-signed certificate +listener "tcp" { + address = "127.0.0.1:8200" + tls_cert_file = "./src/test/vault-config/localhost.cert" + tls_key_file = "./src/test/vault-config/localhost.key" +} + + diff --git a/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt b/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt new file mode 100644 index 0000000000..b965a95321 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt @@ -0,0 +1,82 @@ +== Vault server bootstrap + +1. Run vaul-start in one shell + +2. Open another shell and execute the command below: +> vault operator init + +Vault will output the unseal keys and root token: STORE THEM SAFELY !!! + +Example output: +Unseal Key 1: OfCseaSZzjTZmrxhfx+5clKobwLGCNiJdAlfixSG9E3o +Unseal Key 2: iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT +Unseal Key 3: K0TleK3OYUvWFF+uIDsQuf5a+/gkv1PtZ3O47ornzRoF +Unseal Key 4: +5zhysLAO4hIdZs0kiZpkrRovw11uQacfloiBwnZBJA/ +Unseal Key 5: GDwSq18lXV3Cw4MoHsKIH137kuI0mdl36UiD9WxOdulc + +Initial Root Token: d341fdaf-1cf9-936a-3c38-cf5eec94b5c0 + +... + +== Admin token setup + +1. Set the VAULT_TOKEN environment variable with the root token value +export VAULT_TOKEN=d341fdaf-1cf9-936a-3c38-cf5eec94b5c0 (Linux) +set VAULT_TOKEN=d341fdaf-1cf9-936a-3c38-cf5eec94b5c0 (Windows) + +2. Create another admin token + +>vault token create -display-name=admin +Key Value +--- ----- +token 3779c3ca-9f5e-1d8f-3842-efa96d88de43 <=== this is the new root token +token_accessor 2dfa4031-973b-cf88-c749-ee6f520ecaea +token_duration ∞ +token_renewable false +token_policies ["root"] +identity_policies [] +policies ["root"] + +3. Create ~/.vault-secret with your root token +4. Unset the VAULT_TOKEN environment variable ! + +=== Test DB setup (MySQL only, for now) + +1. Create test db +2. Create admin account used to create dynamic accounts: + +create schema fakebank; +create user 'fakebank-admin'@'%' identified by 'Sup&rSecre7!' +grant all privileges on fakebank.* to 'fakebank-admin'@'%' with grant option; +grant create user on *.* to 'fakebank-admin' with grant option; +flush privileges; + + +=== Database secret backend setup +> vault secrets enable database + +==== Create db configuration +> vault write database/config/mysql-fakebank ^ + plugin_name=mysql-legacy-database-plugin ^ + connection_url="{{username}}:{{password}}@tcp(127.0.0.1:3306)/fakebank" ^ + allowed_roles="*" ^ + username="fakebank-admin" ^ + password="Sup&rSecre7!" + +==== Create roles +> vault write database/roles/fakebank-accounts-ro ^ + db_name=mysql-fakebank ^ + creation_statements="CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';GRANT SELECT ON fakebank.* TO '{{name}}'@'%';" ^ + default_ttl="1h" ^ + max_ttl="24h" + +> vault write database/roles/fakebank-accounts-rw ^ + db_name=mysql-fakebank ^ + creation_statements="CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';GRANT SELECT,INSERT,UPDATE ON fakebank.* TO '{{name}}'@'%';" ^ + default_ttl="1m" ^ + max_ttl="2m" + +=== Get credentials +> vault read database/creds/fakebank-accounts-rw + + diff --git a/spring-cloud/spring-cloud-vault/vault-env.bat b/spring-cloud/spring-cloud-vault/vault-env.bat new file mode 100644 index 0000000000..d7aa5da215 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-env.bat @@ -0,0 +1,5 @@ +@echo off +echo Setting environment variables to access local vault.. +set VAULT_ADDR=https://localhost:8200 +set VAULT_CACERT=%~dp0%/src/test/vault-config/localhost.cert +rem set VAULT_TLS_SERVER_NAME=localhost diff --git a/spring-cloud/spring-cloud-vault/vault-env.sh b/spring-cloud/spring-cloud-vault/vault-env.sh new file mode 100644 index 0000000000..06077cee2e --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-env.sh @@ -0,0 +1,6 @@ +#!/bin/bash +echo Setting environment variables to access local vault.. +SCRIPTPATH=$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd ) +export VAULT_ADDR=https://localhost:8200 +export VAULT_CACERT=$SCRIPTPATH/src/test/vault-config/localhost.cert +export VAULT_TLS_SERVER_NAME=localhost diff --git a/spring-cloud/spring-cloud-vault/vault-start.bat b/spring-cloud/spring-cloud-vault/vault-start.bat new file mode 100644 index 0000000000..e8f6ce4c9f --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-start.bat @@ -0,0 +1,3 @@ +echo Starting vault server... +pushd %~dp0% +vault server -config %~dp0%/src/test/vault-config/vault-test.hcl diff --git a/spring-cloud/spring-cloud-vault/vault-start.sh b/spring-cloud/spring-cloud-vault/vault-start.sh new file mode 100644 index 0000000000..d5af7cfee6 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-start.sh @@ -0,0 +1,5 @@ +#!/bin/bash +SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )" +pushd $SCRIPTPATH +echo Starting vault server... +vault server -config $SCRIPTPATH/src/test/vault-config/vault-test.hcl diff --git a/spring-cloud/spring-cloud-vault/vault-unseal.bat b/spring-cloud/spring-cloud-vault/vault-unseal.bat new file mode 100644 index 0000000000..8133f90892 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-unseal.bat @@ -0,0 +1,7 @@ + +call %~dp0%/vault-env.bat + +vault operator unseal OfCseaSZzjTZmrxhfx+5clKobwLGCNiJdAlfixSG9E3o +vault operator unseal iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT +vault operator unseal iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT +vault operator unseal K0TleK3OYUvWFF+uIDsQuf5a+/gkv1PtZ3O47ornzRoF diff --git a/spring-cloud/spring-cloud-vault/vault-unseal.sh b/spring-cloud/spring-cloud-vault/vault-unseal.sh new file mode 100644 index 0000000000..699b383801 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/vault-unseal.sh @@ -0,0 +1,8 @@ +#!/bin/bash +SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )" +. $SCRIPTPATH/vault-env.sh + +# Please replace the unseal keys below for your own +vault operator unseal OfCseaSZzjTZmrxhfx+5clKobwLGCNiJdAlfixSG9E3o +vault operator unseal iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT +vault operator unseal K0TleK3OYUvWFF+uIDsQuf5a+/gkv1PtZ3O47ornzRoF diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0f544b3ed1 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.cloud.ribbon.client.ServerLocationApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GreetingApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-core/README.md b/spring-core/README.md index adc21ffdaf..e5c359c11b 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -18,3 +18,7 @@ - [Spring – Injecting Collections](http://www.baeldung.com/spring-injecting-collections) - [Access a File from the Classpath in a Spring Application](http://www.baeldung.com/spring-classpath-file-access) - [Controlling Bean Creation Order with @DependsOn Annotation](http://www.baeldung.com/spring-depends-on) +- [Spring Autowiring of Generic Types](https://www.baeldung.com/spring-autowire-generics) +- [Spring Application Context Events](https://www.baeldung.com/spring-context-events) +- [Unsatisfied Dependency in Spring](https://www.baeldung.com/spring-unsatisfied-dependency) +- [What is a Spring Bean?](https://www.baeldung.com/spring-bean) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 9e885462f3..60f3262f08 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -16,11 +16,6 @@ - - org.mockito - mockito-all - ${mockito.version} - org.springframework spring-test @@ -82,15 +77,7 @@ - - - java.net - https://maven.java.net/content/repositories/releases/ - - - - 1.10.19 1.4.4.RELEASE 1 20.0 diff --git a/spring-core/src/main/java/com/baeldung/definition/Config.java b/spring-core/src/main/java/com/baeldung/definition/Config.java new file mode 100644 index 0000000000..126e6259ca --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/Config.java @@ -0,0 +1,16 @@ +package com.baeldung.definition; + +import com.baeldung.definition.domain.Address; +import com.baeldung.definition.domain.Company; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackageClasses = Company.class) +public class Config { + @Bean + public Address getAddress() { + return new Address("High Street", 1000); + } +} diff --git a/spring-core/src/main/java/com/baeldung/definition/domain/Address.java b/spring-core/src/main/java/com/baeldung/definition/domain/Address.java new file mode 100644 index 0000000000..91be18398e --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/domain/Address.java @@ -0,0 +1,14 @@ +package com.baeldung.definition.domain; + +import lombok.Data; + +@Data +public class Address { + private String street; + private int number; + + public Address(String street, int number) { + this.street = street; + this.number = number; + } +} diff --git a/spring-core/src/main/java/com/baeldung/definition/domain/Company.java b/spring-core/src/main/java/com/baeldung/definition/domain/Company.java new file mode 100644 index 0000000000..eabde8afdf --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/domain/Company.java @@ -0,0 +1,14 @@ +package com.baeldung.definition.domain; + +import lombok.Data; +import org.springframework.stereotype.Component; + +@Data +@Component +public class Company { + private Address address; + + public Company(Address address) { + this.address = address; + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java b/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java new file mode 100644 index 0000000000..e0fe01acdd --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java @@ -0,0 +1,14 @@ +package com.baeldung.dependency.exception.app; + +import com.baeldung.dependency.exception.repository.InventoryRepository; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class PurchaseDeptService { + private InventoryRepository repository; + + public PurchaseDeptService(@Qualifier("dresses") InventoryRepository repository) { + this.repository = repository; + } +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/app/SpringDependenciesExampleApplication.java b/spring-core/src/main/java/com/baeldung/dependency/exception/app/SpringDependenciesExampleApplication.java new file mode 100644 index 0000000000..e45438a9fe --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/app/SpringDependenciesExampleApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.dependency.exception.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.dependency.exception") +public class SpringDependenciesExampleApplication { + public static void main(String[] args) { + SpringApplication.run(SpringDependenciesExampleApplication.class, args); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java new file mode 100644 index 0000000000..5a1371ce04 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.dependency.exception.repository; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Repository; + +@Qualifier("dresses") +@Repository +public class DressRepository implements InventoryRepository { +} diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/InventoryRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/InventoryRepository.java new file mode 100644 index 0000000000..ccb2ad9c32 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/InventoryRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.dependency.exception.repository; + +import org.springframework.stereotype.Repository; + +@Repository +public interface InventoryRepository { +} diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java new file mode 100644 index 0000000000..227d8934b6 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.dependency.exception.repository; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Repository; + +@Qualifier("shoes") +@Repository +public class ShoeRepository implements InventoryRepository { +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/annotation/CarQualifier.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/annotation/CarQualifier.java new file mode 100644 index 0000000000..cd7f81c0fb --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/annotation/CarQualifier.java @@ -0,0 +1,15 @@ +package com.baeldung.dependencyinjectiontypes.annotation; + +import org.springframework.beans.factory.annotation.Qualifier; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.FIELD, ElementType.METHOD, + ElementType.TYPE, ElementType.PARAMETER}) +@Retention(RetentionPolicy.RUNTIME) +@Qualifier +public @interface CarQualifier { +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/app/CustomConfiguration.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/app/CustomConfiguration.java new file mode 100644 index 0000000000..841a8d4656 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/app/CustomConfiguration.java @@ -0,0 +1,39 @@ +package com.baeldung.dependencyinjectiontypes.app; + +import com.baeldung.dependencyinjectiontypes.annotation.CarQualifier; +import com.baeldung.dependencyinjectiontypes.model.Car; +import com.baeldung.dependencyinjectiontypes.model.CarHandler; +import com.baeldung.dependencyinjectiontypes.model.Motorcycle; +import com.baeldung.dependencyinjectiontypes.model.Vehicle; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan("com.baeldung.dependencyinjectiontypes.model") +public class CustomConfiguration { + @Bean + @CarQualifier + public Car getMercedes() { + return new Car("E280", "Mercedes", "Diesel"); + } + + public static void main(String[] args) throws NoSuchFieldException { + ConfigurableApplicationContext context = SpringApplication.run(CustomConfiguration.class, args); + CarHandler carHandler = context.getBean(CarHandler.class); + carHandler.getVehicles().forEach(System.out::println); + } + + @Bean + @CarQualifier + public Car getBmw() { + return new Car("M5", "BMW", "Petrol"); + } + + @Bean + public Motorcycle getSuzuki() { + return new Motorcycle("Yamaguchi", "Suzuki", true); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Car.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Car.java new file mode 100644 index 0000000000..a09d89248b --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Car.java @@ -0,0 +1,25 @@ +package com.baeldung.dependencyinjectiontypes.model; + +public class Car extends Vehicle { + private String engineType; + + public Car(String name, String manufacturer, String engineType) { + super(name, manufacturer); + this.engineType = engineType; + } + + public String getEngineType() { + return engineType; + } + + public void setEngineType(String engineType) { + this.engineType = engineType; + } + + @Override + public String toString() { + return "Car{" + + "engineType='" + engineType + '\'' + + '}'; + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/CarHandler.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/CarHandler.java new file mode 100644 index 0000000000..f5d581ef0a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/CarHandler.java @@ -0,0 +1,26 @@ +package com.baeldung.dependencyinjectiontypes.model; + +import com.baeldung.dependencyinjectiontypes.annotation.CarQualifier; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ResolvableType; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class CarHandler { + + @Autowired + @CarQualifier + private List vehicles; + + public List getVehicles() throws NoSuchFieldException { + ResolvableType vehiclesType = ResolvableType.forField(getClass().getDeclaredField("vehicles")); + System.out.println(vehiclesType); + ResolvableType type = vehiclesType.getGeneric(); + System.out.println(type); + Class aClass = type.resolve(); + System.out.println(aClass); + return this.vehicles; + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Motorcycle.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Motorcycle.java new file mode 100644 index 0000000000..ce5e97fb6d --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Motorcycle.java @@ -0,0 +1,25 @@ +package com.baeldung.dependencyinjectiontypes.model; + +public class Motorcycle extends Vehicle { + private boolean twoWheeler; + + public Motorcycle(String name, String manufacturer, boolean twoWheeler) { + super(name, manufacturer); + this.twoWheeler = true; + } + + public boolean isTwoWheeler() { + return twoWheeler; + } + + public void setTwoWheeler(boolean twoWheeler) { + this.twoWheeler = twoWheeler; + } + + @Override + public String toString() { + return "Motorcycle{" + + "twoWheeler=" + twoWheeler + + '}'; + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Vehicle.java b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Vehicle.java new file mode 100644 index 0000000000..cb3dca764e --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependencyinjectiontypes/model/Vehicle.java @@ -0,0 +1,28 @@ +package com.baeldung.dependencyinjectiontypes.model; + +public abstract class Vehicle { + private String name; + private String manufacturer; + + + public Vehicle(String name, String manufacturer) { + this.name = name; + this.manufacturer = manufacturer; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java b/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java new file mode 100644 index 0000000000..a2603bb95c --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java @@ -0,0 +1,24 @@ +package com.baeldung.event.listener; + +import org.springframework.context.event.ContextStartedEvent; +import org.springframework.context.event.ContextStoppedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +@Component +public class ContextEventListener { + + @Order(2) + @EventListener + public void handleContextRefreshEvent(ContextStartedEvent ctxStartEvt) { + System.out.println("Context Start Event received."); + } + + @Order(1) + @EventListener(classes = { ContextStartedEvent.class, ContextStoppedEvent.class }) + public void handleMultipleEvents() { + System.out.println("Multi-event listener invoked"); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java b/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java new file mode 100644 index 0000000000..f2a3af7640 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.event.listener; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.event.listener") +public class EventConfig { + +} diff --git a/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java b/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java new file mode 100644 index 0000000000..bbe4693900 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java @@ -0,0 +1,12 @@ +package com.baeldung.event.listener; + +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class SpringRunner { + + public static void main(String[] args) { + ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(EventConfig.class); + ctx.start(); + } +} diff --git a/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java b/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java new file mode 100644 index 0000000000..0057611308 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java @@ -0,0 +1,18 @@ +package com.baeldung.definition; + +import com.baeldung.definition.domain.Company; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.Assert.assertEquals; + +public class SpringBeanIntegrationTest { + @Test + public void whenUsingIoC_thenDependenciesAreInjected() { + ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); + Company company = context.getBean("company", Company.class); + assertEquals("High Street", company.getAddress().getStreet()); + assertEquals(1000, company.getAddress().getNumber()); + } +} diff --git a/spring-cucumber/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cucumber/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..80efd86f13 --- /dev/null +++ b/spring-cucumber/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.SpringDemoApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDemoApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-custom-aop/pom.xml b/spring-custom-aop/pom.xml index fd5f87a476..f0b1dbb5ac 100644 --- a/spring-custom-aop/pom.xml +++ b/spring-custom-aop/pom.xml @@ -149,6 +149,7 @@ 3.1.7 8.5.11 18.0 + 8.0.43 diff --git a/spring-custom-aop/src/main/resources/logback.xml b/spring-custom-aop/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-custom-aop/src/main/resources/logback.xml +++ b/spring-custom-aop/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-custom-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0384c67e26 --- /dev/null +++ b/spring-custom-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,25 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.annotation.servletcomponentscan.SpringBootAnnotatedApp; +import com.baeldung.annotation.servletcomponentscan.SpringBootPlainApp; +import com.baeldung.git.CommitIdApplication; +import com.baeldung.internationalization.InternationalizationApp; +import com.baeldung.intro.App; +import com.baeldung.servlets.ApplicationMain; +import com.baeldung.webjar.WebjarsdemoApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { SpringBootAnnotatedApp.class, SpringBootPlainApp.class, CommitIdApplication.class, + InternationalizationApp.class, App.class, ApplicationMain.class, Application.class, + WebjarsdemoApplication.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-couchbase-2/src/main/resources/logback.xml b/spring-data-couchbase-2/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-data-couchbase-2/src/main/resources/logback.xml +++ b/spring-data-couchbase-2/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9c9d58dd0b --- /dev/null +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTestConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) +@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-couchbase-2/src/test/resources/logback.xml b/spring-data-couchbase-2/src/test/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-data-couchbase-2/src/test/resources/logback.xml +++ b/spring-data-couchbase-2/src/test/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6f45039c96 --- /dev/null +++ b/spring-data-elasticsearch/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +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.spring.data.es.config.Config; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = Config.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-jpa/README.md b/spring-data-jpa/README.md new file mode 100644 index 0000000000..44ce240da3 --- /dev/null +++ b/spring-data-jpa/README.md @@ -0,0 +1,27 @@ +========= + +## Spring Data JPA Example Project + +### Relevant Articles: +- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) +- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) +- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) +- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) +- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) +- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) +- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) +- [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) +- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) +- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) +- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) +- [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator + diff --git a/spring-data-jpa/pom.xml b/spring-data-jpa/pom.xml index 517d43bd0e..8691ce1f09 100644 --- a/spring-data-jpa/pom.xml +++ b/spring-data-jpa/pom.xml @@ -17,10 +17,50 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.hibernate + hibernate-ehcache + + + org.hibernate + hibernate-envers + com.h2database h2 + + + org.springframework.security + spring-security-test + test + + + + com.google.guava + guava + 21.0 + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + org.junit.platform + junit-platform-launcher + ${junit-platform.version} + test + \ No newline at end of file diff --git a/spring-data-jpa/src/main/java/com/baeldung/Application.java b/spring-data-jpa/src/main/java/com/baeldung/Application.java index 43888c2d67..72d29d9fa5 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/Application.java +++ b/spring-data-jpa/src/main/java/com/baeldung/Application.java @@ -2,13 +2,16 @@ package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ApplicationContext; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; @SpringBootApplication +@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class) public class Application { - private static ApplicationContext applicationContext; public static void main(String[] args) { - applicationContext = SpringApplication.run(Application.class, args); + SpringApplication.run(Application.class, args); } + } diff --git a/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java new file mode 100644 index 0000000000..16407e510a --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java @@ -0,0 +1,102 @@ +package com.baeldung.config; + +import com.baeldung.services.IBarService; +import com.baeldung.services.impl.BarSpringDataJpaService; +import com.google.common.base.Preconditions; +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; +import com.baeldung.services.IFooService; +import com.baeldung.services.impl.FooService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.*; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; +import java.util.Properties; + +@Configuration +@ComponentScan({"com.baeldung.dao", "com.baeldung.services"}) +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = {"com.baeldung.dao"}, repositoryBaseClass = ExtendedRepositoryImpl.class) +@EnableJpaAuditing +@PropertySource("classpath:persistence.properties") +public class PersistenceConfiguration { + + @Autowired + private Environment env; + + public PersistenceConfiguration() { + super(); + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(dataSource()); + emf.setPackagesToScan("com.baeldung.domain"); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + emf.setJpaVendorAdapter(vendorAdapter); + emf.setJpaProperties(hibernateProperties()); + + return emf; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + @Bean + public IBarService barSpringDataJpaService() { + return new BarSpringDataJpaService(); + } + + @Bean + public IFooService fooService() { + return new FooService(); + } + + private final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + + hibernateProperties.setProperty("hibernate.show_sql", "true"); + // hibernateProperties.setProperty("hibernate.format_sql", "true"); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + + // Envers properties + hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); + + return hibernateProperties; + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java similarity index 84% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java rename to spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java index 13f8f4b27c..207fba9bc5 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java +++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceProductConfiguration.java @@ -1,9 +1,6 @@ -package org.baeldung.config; - -import java.util.HashMap; - -import javax.sql.DataSource; +package com.baeldung.config; +import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -16,16 +13,17 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.HashMap; @Configuration -@PropertySource({ "classpath:persistence-multiple-db.properties" }) -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.multiple.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") -public class ProductConfig { +@PropertySource({"classpath:persistence-multiple-db.properties"}) +@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") +public class PersistenceProductConfiguration { @Autowired private Environment env; - public ProductConfig() { + public PersistenceProductConfiguration() { super(); } @@ -35,7 +33,7 @@ public class ProductConfig { public LocalContainerEntityManagerFactoryBean productEntityManager() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(productDataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.multiple.model.product" }); + em.setPackagesToScan("com.baeldung.domain.product"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java similarity index 85% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java rename to spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java index 8e85f5d8e0..dd32477755 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java +++ b/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceUserConfiguration.java @@ -1,9 +1,6 @@ -package org.baeldung.config; - -import java.util.HashMap; - -import javax.sql.DataSource; +package com.baeldung.config; +import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -17,16 +14,17 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.HashMap; @Configuration -@PropertySource({ "classpath:persistence-multiple-db.properties" }) -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.multiple.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") -public class UserConfig { +@PropertySource({"classpath:persistence-multiple-db.properties"}) +@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") +public class PersistenceUserConfiguration { @Autowired private Environment env; - public UserConfig() { + public PersistenceUserConfiguration() { super(); } @@ -37,7 +35,7 @@ public class UserConfig { public LocalContainerEntityManagerFactoryBean userEntityManager() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(userDataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.multiple.model.user" }); + em.setPackagesToScan("com.baeldung.domain.user"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java b/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java new file mode 100644 index 0000000000..bb3c229945 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/IFooDao.java @@ -0,0 +1,12 @@ +package com.baeldung.dao; + +import com.baeldung.domain.Foo; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface IFooDao extends JpaRepository { + + @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") + Foo retrieveByName(@Param("name") String name); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java similarity index 95% rename from spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java index 4e1b109430..8402c099d9 100644 --- a/spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ArticleRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.repository; +package com.baeldung.dao.repositories; import com.baeldung.domain.Article; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java new file mode 100644 index 0000000000..ba077ccf1f --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.dao.repositories; + +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Item; + +@Repository +public interface CustomItemRepository { + + void deleteCustom(Item entity); + + Item findItemById(Long id); + + void findThenDelete(Long id); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java new file mode 100644 index 0000000000..81ebdf3fda --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemTypeRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.dao.repositories; + +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.ItemType; + +@Repository +public interface CustomItemTypeRepository { + + void deleteCustom(ItemType entity); + + void findThenDelete(Long id); +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java similarity index 69% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java index 9c9c12029a..9e82f02fa6 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.extended.persistence.dao; +package com.baeldung.dao.repositories; import java.io.Serializable; import java.util.List; @@ -8,5 +8,7 @@ import org.springframework.data.repository.NoRepositoryBean; @NoRepositoryBean public interface ExtendedRepository extends JpaRepository { - public List findByAttributeContainsText(String attributeName, String text); + + List findByAttributeContainsText(String attributeName, String text); + } diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java new file mode 100644 index 0000000000..199e4e5ff6 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ExtendedStudentRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.Student; + +public interface ExtendedStudentRepository extends ExtendedRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java new file mode 100644 index 0000000000..54a7d77691 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/IBarCrudRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.Bar; +import org.springframework.data.repository.CrudRepository; + +import java.io.Serializable; + +public interface IBarCrudRepository extends CrudRepository { + // +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java new file mode 100644 index 0000000000..a575f0b915 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.MerchandiseEntity; +import org.springframework.data.repository.CrudRepository; + +public interface InventoryRepository extends CrudRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java new file mode 100644 index 0000000000..2af83bc322 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ItemTypeRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.dao.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.ItemType; + +@Repository +public interface ItemTypeRepository extends JpaRepository, CustomItemTypeRepository, CustomItemRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java new file mode 100644 index 0000000000..27bbe27af0 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/LocationRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.dao.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Location; + +@Repository +public interface LocationRepository extends JpaRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java new file mode 100644 index 0000000000..8f68cdbbe5 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/ReadOnlyLocationRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.dao.repositories; + +import java.util.Optional; + +import org.springframework.data.repository.Repository; + +import com.baeldung.domain.Location; + +@org.springframework.stereotype.Repository +public interface ReadOnlyLocationRepository extends Repository { + + Optional findById(Long id); + + Location save(Location location); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java new file mode 100644 index 0000000000..9318c32ee9 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/StoreRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.dao.repositories; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Store; + +@Repository +public interface StoreRepository extends JpaRepository { + List findStoreByLocationId(Long locationId); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java new file mode 100644 index 0000000000..53def88af0 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java @@ -0,0 +1,32 @@ +package com.baeldung.dao.repositories.impl; + +import javax.persistence.EntityManager; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.Item; +import com.baeldung.dao.repositories.CustomItemRepository; + +@Repository +public class CustomItemRepositoryImpl implements CustomItemRepository { + + @Autowired + private EntityManager entityManager; + + @Override + public void deleteCustom(Item item) { + entityManager.remove(item); + } + + @Override + public Item findItemById(Long id) { + return entityManager.find(Item.class, id); + } + + @Override + public void findThenDelete(Long id) { + final Item item = entityManager.find(Item.class, id); + entityManager.remove(item); + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java new file mode 100644 index 0000000000..2b49f2380c --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemTypeRepositoryImpl.java @@ -0,0 +1,31 @@ +package com.baeldung.dao.repositories.impl; + +import javax.persistence.EntityManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import com.baeldung.domain.ItemType; +import com.baeldung.dao.repositories.CustomItemTypeRepository; + +@Repository +public class CustomItemTypeRepositoryImpl implements CustomItemTypeRepository { + + private static final Logger LOGGER = LoggerFactory.getLogger(CustomItemTypeRepositoryImpl.class); + + @Autowired + private EntityManager entityManager; + + @Override + public void deleteCustom(ItemType itemType) { + entityManager.remove(itemType); + } + + @Override + public void findThenDelete(Long id) { + ItemType itemTypeToDelete = entityManager.find(ItemType.class, id); + entityManager.remove(itemTypeToDelete); + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java similarity index 93% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java index 7ed652dc4d..f6f06efb51 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/ExtendedRepositoryImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.extended.persistence.dao; +package com.baeldung.dao.repositories.impl; import java.io.Serializable; import java.util.List; @@ -10,6 +10,7 @@ import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.transaction.Transactional; +import com.baeldung.dao.repositories.ExtendedRepository; import org.springframework.data.jpa.repository.support.JpaEntityInformation; import org.springframework.data.jpa.repository.support.SimpleJpaRepository; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java similarity index 54% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java index bad0170a3a..7044d57e53 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.multiple.dao.product; +package com.baeldung.dao.repositories.product; -import org.baeldung.persistence.multiple.model.product.Product; +import com.baeldung.domain.product.Product; import org.springframework.data.jpa.repository.JpaRepository; public interface ProductRepository extends JpaRepository { diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java similarity index 55% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java index 34913632d8..f0eeb475c1 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/PossessionRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.multiple.dao.user; +package com.baeldung.dao.repositories.user; -import org.baeldung.persistence.multiple.model.user.Possession; +import com.baeldung.domain.user.Possession; import org.springframework.data.jpa.repository.JpaRepository; public interface PossessionRepository extends JpaRepository { diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java similarity index 74% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java index eadac9a0d7..5bb0232e4a 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/repository/UserRepository.java +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.repository; +package com.baeldung.dao.repositories.user; -import org.baeldung.persistence.model.User; +import com.baeldung.domain.user.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -8,24 +8,25 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.List; +import java.util.stream.Stream; -@Repository("userRepository") public interface UserRepository extends JpaRepository { + Stream findAllByName(String name); + @Query("SELECT u FROM User u WHERE u.status = 1") Collection findAllActiveUsers(); - @Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true) + @Query(value = "SELECT * FROM USERS.USERS u WHERE u.status = 1", nativeQuery = true) Collection findAllActiveUsersNative(); @Query("SELECT u FROM User u WHERE u.status = ?1") User findUserByStatus(Integer status); - @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) + @Query(value = "SELECT * FROM USERS.Users u WHERE u.status = ?1", nativeQuery = true) User findUserByStatusNative(Integer status); @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") @@ -34,7 +35,7 @@ public interface UserRepository extends JpaRepository { @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); - @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) + @Query(value = "SELECT * FROM USERS.Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") @@ -46,7 +47,7 @@ public interface UserRepository extends JpaRepository { @Query("SELECT u FROM User u WHERE u.name like :name%") User findUserByNameLikeNamedParam(@Param("name") String name); - @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) + @Query(value = "SELECT * FROM USERS.users u WHERE u.name LIKE ?1%", nativeQuery = true) User findUserByNameLikeNative(String name); @Query(value = "SELECT u FROM User u") @@ -55,7 +56,7 @@ public interface UserRepository extends JpaRepository { @Query(value = "SELECT u FROM User u ORDER BY id") Page findAllUsersWithPagination(Pageable pageable); - @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) + @Query(value = "SELECT * FROM USERS.Users ORDER BY id", countQuery = "SELECT count(*) FROM USERS.Users", nativeQuery = true) Page findAllUsersWithPaginationNative(Pageable pageable); @Modifying @@ -63,7 +64,6 @@ public interface UserRepository extends JpaRepository { int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); @Modifying - @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) + @Query(value = "UPDATE USERS.Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) int updateUserSetStatusForNameNative(Integer status, String name); - } diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate.java new file mode 100644 index 0000000000..bf6ff0a0b9 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate.java @@ -0,0 +1,46 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Transient; + +import org.springframework.context.ApplicationEventPublisher; + +@Entity +class Aggregate { + @Transient + private ApplicationEventPublisher eventPublisher; + @Id + private long id; + + private Aggregate() { + } + + Aggregate(long id, ApplicationEventPublisher eventPublisher) { + this.id = id; + this.eventPublisher = eventPublisher; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "DomainEntity [id=" + id + "]"; + } + + void domainOperation() { + // some business logic + if (eventPublisher != null) { + eventPublisher.publishEvent(new DomainEvent()); + } + } + + long getId() { + return id; + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2.java new file mode 100644 index 0000000000..3d2816299a --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2.java @@ -0,0 +1,44 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Transient; + +import org.springframework.data.domain.AfterDomainEventPublication; +import org.springframework.data.domain.DomainEvents; + +@Entity +public class Aggregate2 { + @Transient + private final Collection domainEvents; + @Id + @GeneratedValue + private long id; + + public Aggregate2() { + domainEvents = new ArrayList<>(); + } + + @AfterDomainEventPublication + public void clearEvents() { + domainEvents.clear(); + } + + public void domainOperation() { + // some domain operation + domainEvents.add(new DomainEvent()); + } + + @DomainEvents + public Collection events() { + return domainEvents; + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2Repository.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2Repository.java new file mode 100644 index 0000000000..2a95abe347 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate2Repository.java @@ -0,0 +1,10 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import org.springframework.data.repository.CrudRepository; + +public interface Aggregate2Repository extends CrudRepository { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3.java new file mode 100644 index 0000000000..e0c3131b06 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3.java @@ -0,0 +1,23 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import org.springframework.data.domain.AbstractAggregateRoot; + +@Entity +public class Aggregate3 extends AbstractAggregateRoot { + @Id + @GeneratedValue + private long id; + + public void domainOperation() { + // some domain operation + registerEvent(new DomainEvent()); + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3Repository.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3Repository.java new file mode 100644 index 0000000000..e442bdb210 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/Aggregate3Repository.java @@ -0,0 +1,14 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import org.springframework.data.repository.CrudRepository; + +/** + * @author goobar + * + */ +public interface Aggregate3Repository extends CrudRepository { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/AggregateRepository.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/AggregateRepository.java new file mode 100644 index 0000000000..5a15156d03 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/AggregateRepository.java @@ -0,0 +1,10 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import org.springframework.data.repository.CrudRepository; + +public interface AggregateRepository extends CrudRepository { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DddConfig.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DddConfig.java new file mode 100644 index 0000000000..1315b11875 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DddConfig.java @@ -0,0 +1,15 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.PropertySource; + +@SpringBootConfiguration +@EnableAutoConfiguration +@PropertySource("classpath:/ddd.properties") +public class DddConfig { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainEvent.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainEvent.java new file mode 100644 index 0000000000..1e6479d4fc --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainEvent.java @@ -0,0 +1,8 @@ +/** + * + */ +package com.baeldung.ddd.event; + +class DomainEvent { + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainService.java b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainService.java new file mode 100644 index 0000000000..082c9bd88e --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/ddd/event/DomainService.java @@ -0,0 +1,31 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import javax.transaction.Transactional; + +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; + +@Service +public class DomainService { + private final ApplicationEventPublisher eventPublisher; + private final AggregateRepository repository; + + public DomainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) { + this.repository = repository; + this.eventPublisher = eventPublisher; + } + + @Transactional + public void serviceDomainOperation(long entityId) { + repository.findById(entityId) + .ifPresent(entity -> { + entity.domainOperation(); + repository.save(entity); + eventPublisher.publishEvent(new DomainEvent()); + }); + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java new file mode 100644 index 0000000000..efd297bafc --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Bar.java @@ -0,0 +1,220 @@ +package com.baeldung.domain; + +import com.google.common.collect.Sets; +import org.hibernate.annotations.OrderBy; +import org.hibernate.envers.Audited; +import org.jboss.logging.Logger; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; +import java.util.Set; + +@Entity +@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") +@Audited +@EntityListeners(AuditingEntityListener.class) +public class Bar implements Serializable { + + private static Logger logger = Logger.getLogger(Bar.class); + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private int id; + + @Column(name = "name") + private String name; + @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @OrderBy(clause = "NAME DESC") + // @NotAudited + private Set fooSet = Sets.newHashSet(); + @Column(name = "operation") + private String operation; + @Column(name = "timestamp") + private long timestamp; + @Column(name = "created_date", updatable = false, nullable = false) + @CreatedDate + private long createdDate; + @Column(name = "modified_date") + @LastModifiedDate + private long modifiedDate; + @Column(name = "created_by") + @CreatedBy + private String createdBy; + @Column(name = "modified_by") + @LastModifiedBy + private String modifiedBy; + + public Bar() { + super(); + } + + public Bar(final String name) { + super(); + + this.name = name; + } + + public Set getFooSet() { + return fooSet; + } + + // API + + public void setFooSet(final Set fooSet) { + this.fooSet = fooSet; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public OPERATION getOperation() { + return OPERATION.parse(operation); + } + + public void setOperation(final String operation) { + this.operation = operation; + } + + public void setOperation(final OPERATION operation) { + this.operation = operation.getValue(); + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(final long timestamp) { + this.timestamp = timestamp; + } + + public long getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(final long createdDate) { + this.createdDate = createdDate; + } + + public long getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(final long modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(final String createdBy) { + this.createdBy = createdBy; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(final String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + @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(); + } + + @PrePersist + public void onPrePersist() { + logger.info("@PrePersist"); + audit(OPERATION.INSERT); + } + + @PreUpdate + public void onPreUpdate() { + logger.info("@PreUpdate"); + audit(OPERATION.UPDATE); + } + + @PreRemove + public void onPreRemove() { + logger.info("@PreRemove"); + audit(OPERATION.DELETE); + } + + private void audit(final OPERATION operation) { + setOperation(operation); + setTimestamp((new Date()).getTime()); + } + + public enum OPERATION { + INSERT, UPDATE, DELETE; + private String value; + + OPERATION() { + value = toString(); + } + + public static OPERATION parse(final String value) { + OPERATION operation = null; + for (final OPERATION op : OPERATION.values()) { + if (op.getValue().equals(value)) { + operation = op; + break; + } + } + return operation; + } + + public String getValue() { + return value; + } + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java new file mode 100644 index 0000000000..ef88840746 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Foo.java @@ -0,0 +1,94 @@ +package com.baeldung.domain; + +import org.hibernate.envers.Audited; + +import javax.persistence.*; +import java.io.Serializable; + +@NamedNativeQueries({@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class)}) +@Entity +@Audited +// @Proxy(lazy = false) +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; + + @Column(name = "name", nullable = false) + private String name; + + @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar = new Bar(); + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + this.name = name; + } + + // + + 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/spring-data-jpa/src/main/java/com/baeldung/domain/Item.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Item.java new file mode 100644 index 0000000000..97ce14d92d --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Item.java @@ -0,0 +1,81 @@ +package com.baeldung.domain; + +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Item { + + private String color; + private String grade; + + @Id + private Long id; + + @ManyToOne + private ItemType itemType; + + private String name; + private BigDecimal price; + @ManyToOne + private Store store; + + public String getColor() { + return color; + } + + public String getGrade() { + return grade; + } + + public Long getId() { + return id; + } + + public ItemType getItemType() { + return itemType; + } + + public String getName() { + return name; + } + + public BigDecimal getPrice() { + return price; + } + + public Store getStore() { + return store; + } + + public void setColor(String color) { + this.color = color; + } + + public void setGrade(String grade) { + this.grade = grade; + } + + public void setId(Long id) { + this.id = id; + } + + public void setItemType(ItemType itemType) { + this.itemType = itemType; + } + + public void setName(String name) { + this.name = name; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public void setStore(Store store) { + this.store = store; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/ItemType.java b/spring-data-jpa/src/main/java/com/baeldung/domain/ItemType.java new file mode 100644 index 0000000000..412079c2ae --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/ItemType.java @@ -0,0 +1,46 @@ +package com.baeldung.domain; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; + +@Entity +public class ItemType { + + @Id + private Long id; + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "ITEM_TYPE_ID") + private List items = new ArrayList<>(); + + private String name; + + public Long getId() { + return id; + } + + public List getItems() { + return items; + } + + public String getName() { + return name; + } + + public void setId(Long id) { + this.id = id; + } + + public void setItems(List items) { + this.items = items; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java b/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java new file mode 100644 index 0000000000..b3e7d78b30 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/KVTag.java @@ -0,0 +1,34 @@ +package com.baeldung.domain; + +import javax.persistence.Embeddable; + +@Embeddable +public class KVTag { + private String key; + private String value; + + public KVTag() { + } + + public KVTag(String key, String value) { + super(); + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Location.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Location.java new file mode 100644 index 0000000000..2178d378eb --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Location.java @@ -0,0 +1,55 @@ +package com.baeldung.domain; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; + +@Entity +public class Location { + + private String city; + private String country; + @Id + private Long id; + + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "LOCATION_ID") + private List stores = new ArrayList<>(); + + public String getCity() { + return city; + } + + public String getCountry() { + return country; + } + + public Long getId() { + return id; + } + + public List getStores() { + return stores; + } + + public void setCity(String city) { + this.city = city; + } + + public void setCountry(String country) { + this.country = country; + } + + public void setId(Long id) { + this.id = id; + } + + public void setStores(List stores) { + this.stores = stores; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java b/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java new file mode 100644 index 0000000000..bfc690e0e2 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java @@ -0,0 +1,66 @@ +package com.baeldung.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.math.BigDecimal; + +@Entity +public class MerchandiseEntity { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String title; + + private BigDecimal price; + + private String brand; + + public MerchandiseEntity() { + } + + public MerchandiseEntity(String title, BigDecimal price) { + this.title = title; + this.price = price; + } + + public Long getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public String getBrand() { + return brand; + } + + public void setBrand(String brand) { + this.brand = brand; + } + + @Override + public String toString() { + return "MerchandiseEntity{" + + "id=" + id + + ", title='" + title + '\'' + + ", price=" + price + + ", brand='" + brand + '\'' + + '}'; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java b/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java new file mode 100644 index 0000000000..1f2778c589 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/SkillTag.java @@ -0,0 +1,30 @@ +package com.baeldung.domain; + +import javax.persistence.Embeddable; + +@Embeddable +public class SkillTag { + private String name; + private int value; + + public SkillTag() { + } + + public SkillTag(String name, int value) { + super(); + this.name = name; + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public String getName() { + return name; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Store.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Store.java new file mode 100644 index 0000000000..e04684c479 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Store.java @@ -0,0 +1,76 @@ +package com.baeldung.domain; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; + +@Entity +public class Store { + + private Boolean active; + @Id + private Long id; + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "STORE_ID") + private List items = new ArrayList<>(); + private Long itemsSold; + + @ManyToOne + private Location location; + + private String name; + + public Boolean getActive() { + return active; + } + + public Long getId() { + return id; + } + + public List getItems() { + return items; + } + + public Long getItemsSold() { + return itemsSold; + } + + public Location getLocation() { + return location; + } + + public String getName() { + return name; + } + + public void setActive(Boolean active) { + this.active = active; + } + + public void setId(Long id) { + this.id = id; + } + + public void setItems(List items) { + this.items = items; + } + + public void setItemsSold(Long itemsSold) { + this.itemsSold = itemsSold; + } + + public void setLocation(Location location) { + this.location = location; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java new file mode 100644 index 0000000000..bd7eaeb24b --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/Student.java @@ -0,0 +1,74 @@ +package com.baeldung.domain; + +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.Id; +import java.util.ArrayList; +import java.util.List; + +@Entity +public class Student { + + @Id + private long id; + private String name; + + @ElementCollection + private List tags = new ArrayList<>(); + + @ElementCollection + private List skillTags = new ArrayList<>(); + + @ElementCollection + private List kvTags = new ArrayList<>(); + + public Student() { + } + + public Student(long id, String name) { + super(); + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags.addAll(tags); + } + + public List getSkillTags() { + return skillTags; + } + + public void setSkillTags(List skillTags) { + this.skillTags.addAll(skillTags); + } + + public List getKVTags() { + return this.kvTags; + } + + public void setKVTags(List kvTags) { + this.kvTags.addAll(kvTags); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java b/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java similarity index 90% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java rename to spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java index 8490ed397d..42e6dd8f45 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java @@ -1,11 +1,11 @@ -package org.baeldung.persistence.multiple.model.product; +package com.baeldung.domain.product; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity -@Table(schema = "spring_jpa_product") +@Table(schema = "products") public class Product { @Id diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java b/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java new file mode 100644 index 0000000000..614e13df36 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/user/Possession.java @@ -0,0 +1,86 @@ +package com.baeldung.domain.user; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(schema = "users") +public class Possession { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + public Possession() { + super(); + } + + public Possession(final String name) { + super(); + + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final int 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) + (int) (id ^ (id >>> 32)); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Possession other = (Possession) obj; + if (id != other.id) { + return false; + } + 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("Possesion [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java b/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java new file mode 100644 index 0000000000..3a8b617d9a --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/user/User.java @@ -0,0 +1,86 @@ +package com.baeldung.domain.user; + +import javax.persistence.*; +import java.util.List; + +@Entity +@Table(name = "users", schema = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + private String name; + private int age; + @Column(unique = true, nullable = false) + private String email; + private Integer status; + @OneToMany + List possessionList; + + public User() { + super(); + } + + public User(String name, String email, Integer status) { + this.name = name; + this.email = email; + this.status = status; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(final String email) { + this.email = email; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public int getAge() { + return age; + } + + public void setAge(final int age) { + this.age = age; + } + + public List getPossessionList() { + return possessionList; + } + + public void setPossessionList(List possessionList) { + this.possessionList = possessionList; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [name=").append(name).append(", id=").append(id).append("]"); + return builder.toString(); + } + +} \ No newline at end of file diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java b/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java new file mode 100644 index 0000000000..7e127488db --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/IBarService.java @@ -0,0 +1,7 @@ +package com.baeldung.services; + +import com.baeldung.domain.Bar; + +public interface IBarService extends IOperations { + // +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java b/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java new file mode 100644 index 0000000000..7e16ace5b6 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/IFooService.java @@ -0,0 +1,13 @@ +package com.baeldung.services; + +import com.baeldung.domain.Foo; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +public interface IFooService extends IOperations { + + Foo retrieveByName(String name); + + Page findPaginated(Pageable pageable); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java b/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java new file mode 100644 index 0000000000..d50d465639 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/IOperations.java @@ -0,0 +1,26 @@ +package com.baeldung.services; + +import org.springframework.data.domain.Page; + +import java.io.Serializable; +import java.util.List; + +public interface IOperations { + + T findOne(final long id); + + List findAll(); + + Page findPaginated(int page, int size); + + // write + + T create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java new file mode 100644 index 0000000000..708524225b --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractService.java @@ -0,0 +1,61 @@ +package com.baeldung.services.impl; + +import com.baeldung.services.IOperations; +import com.google.common.collect.Lists; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.List; + +@Transactional +public abstract class AbstractService implements IOperations { + + // read - one + + @Override + @Transactional(readOnly = true) + public T findOne(final long id) { + return getDao().findById(id).orElse(null); + } + + // read - all + + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public Page findPaginated(final int page, final int size) { + return getDao().findAll(new PageRequest(page, size)); + } + + // write + + @Override + public T create(final T entity) { + return getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } + + protected abstract PagingAndSortingRepository getDao(); + +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractSpringDataJpaService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractSpringDataJpaService.java new file mode 100644 index 0000000000..28c86bee28 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/AbstractSpringDataJpaService.java @@ -0,0 +1,45 @@ +package com.baeldung.services.impl; + +import com.baeldung.services.IOperations; +import com.google.common.collect.Lists; +import org.springframework.data.repository.CrudRepository; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.List; + +@Transactional(value = "transactionManager") +public abstract class AbstractSpringDataJpaService implements IOperations { + + @Override + public T findOne(final long id) { + return getDao().findById(id).orElse(null); + } + + @Override + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public T create(final T entity) { + return getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } + + protected abstract CrudRepository getDao(); +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/BarSpringDataJpaService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/BarSpringDataJpaService.java new file mode 100644 index 0000000000..ca3e5f868d --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/BarSpringDataJpaService.java @@ -0,0 +1,30 @@ +package com.baeldung.services.impl; + +import com.baeldung.domain.Bar; +import com.baeldung.dao.repositories.IBarCrudRepository; +import com.baeldung.services.IBarService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.repository.CrudRepository; + +import java.io.Serializable; + +public class BarSpringDataJpaService extends AbstractSpringDataJpaService implements IBarService { + + @Autowired + private IBarCrudRepository dao; + + public BarSpringDataJpaService() { + super(); + } + + @Override + protected CrudRepository getDao() { + return dao; + } + + @Override + public Page findPaginated(int page, int size) { + throw new UnsupportedOperationException("Not implemented yet"); + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/services/impl/FooService.java b/spring-data-jpa/src/main/java/com/baeldung/services/impl/FooService.java new file mode 100644 index 0000000000..319ab3a825 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/services/impl/FooService.java @@ -0,0 +1,54 @@ +package com.baeldung.services.impl; + +import com.google.common.collect.Lists; +import com.baeldung.dao.IFooDao; +import com.baeldung.domain.Foo; +import com.baeldung.services.IFooService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class FooService extends AbstractService implements IFooService { + + @Autowired + private IFooDao dao; + + public FooService() { + super(); + } + + // API + + @Override + protected PagingAndSortingRepository getDao() { + return dao; + } + + // custom methods + + @Override + public Foo retrieveByName(final String name) { + return dao.retrieveByName(name); + } + + // overridden to be secured + + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public Page findPaginated(Pageable pageable) { + return dao.findAll(pageable); + } + +} diff --git a/spring-data-jpa/src/test/resources/application.properties b/spring-data-jpa/src/main/resources/application.properties similarity index 91% rename from spring-data-jpa/src/test/resources/application.properties rename to spring-data-jpa/src/main/resources/application.properties index de6ee2e6b5..73d72bc7d6 100644 --- a/spring-data-jpa/src/test/resources/application.properties +++ b/spring-data-jpa/src/main/resources/application.properties @@ -12,4 +12,4 @@ hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory -spring.datasource.data=import_articles.sql \ No newline at end of file +spring.datasource.data=import_entities.sql \ No newline at end of file diff --git a/spring-data-jpa/src/main/resources/ddd.properties b/spring-data-jpa/src/main/resources/ddd.properties new file mode 100644 index 0000000000..e5126b694b --- /dev/null +++ b/spring-data-jpa/src/main/resources/ddd.properties @@ -0,0 +1 @@ +spring.datasource.initialization-mode=never \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties b/spring-data-jpa/src/main/resources/persistence-multiple-db.properties similarity index 78% rename from persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties rename to spring-data-jpa/src/main/resources/persistence-multiple-db.properties index ce1b6da9ff..75534e8a54 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties +++ b/spring-data-jpa/src/main/resources/persistence-multiple-db.properties @@ -1,9 +1,9 @@ # jdbc.X jdbc.driverClassName=org.h2.Driver -user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS SPRING_JPA_USER -product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS SPRING_JPA_PRODUCT +user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS +product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS jdbc.user=sa -jdbc.pass= +jdbc.pass=sa # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/spring-data-jpa/src/main/resources/persistence.properties b/spring-data-jpa/src/main/resources/persistence.properties new file mode 100644 index 0000000000..3543e1b52b --- /dev/null +++ b/spring-data-jpa/src/main/resources/persistence.properties @@ -0,0 +1,16 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS +jdbc.user=sa +jdbc.pass=sa + +# 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 + +# envers.X +envers.audit_table_suffix=_audit_log \ No newline at end of file diff --git a/spring-data-jpa/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ArticleRepositoryIntegrationTest.java similarity index 85% rename from spring-data-jpa/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java rename to spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ArticleRepositoryIntegrationTest.java index dd1fe66a0d..093e744003 100644 --- a/spring-data-jpa/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ArticleRepositoryIntegrationTest.java @@ -1,7 +1,9 @@ -package com.baeldung.repository; +package com.baeldung.dao.repositories; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; import com.baeldung.domain.Article; -import com.baeldung.repository.ArticleRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -16,7 +18,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) -@DataJpaTest +@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class}) public class ArticleRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ExtendedStudentRepositoryIntegrationTest.java similarity index 72% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java rename to spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ExtendedStudentRepositoryIntegrationTest.java index f3cf921632..b19a34df82 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/ExtendedStudentRepositoryIntegrationTest.java @@ -1,23 +1,21 @@ -package org.baeldung.persistence.repository; +package com.baeldung.dao.repositories; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - -import javax.annotation.Resource; - -import org.baeldung.config.StudentJPAH2Config; -import org.baeldung.extended.persistence.dao.ExtendedStudentRepository; -import org.baeldung.inmemory.persistence.model.Student; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.Student; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { StudentJPAH2Config.class }) +import javax.annotation.Resource; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {PersistenceConfiguration.class}) @DirtiesContext public class ExtendedStudentRepositoryIntegrationTest { @Resource diff --git a/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/InventoryRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/InventoryRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9d6334445c --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/InventoryRepositoryIntegrationTest.java @@ -0,0 +1,60 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.MerchandiseEntity; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.math.BigDecimal; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class}) +public class InventoryRepositoryIntegrationTest { + + private static final String ORIGINAL_TITLE = "Pair of Pants"; + private static final String UPDATED_TITLE = "Branded Luxury Pants"; + private static final String UPDATED_BRAND = "Armani"; + private static final String ORIGINAL_SHORTS_TITLE = "Pair of Shorts"; + + @Autowired + private InventoryRepository repository; + + @Test + public void shouldCreateNewEntryInDB() { + MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE); + pants = repository.save(pants); + + MerchandiseEntity shorts = new MerchandiseEntity(ORIGINAL_SHORTS_TITLE, new BigDecimal(3)); + shorts = repository.save(shorts); + + assertNotNull(pants.getId()); + assertNotNull(shorts.getId()); + assertNotEquals(pants.getId(), shorts.getId()); + } + + @Test + public void shouldUpdateExistingEntryInDB() { + MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE); + pants = repository.save(pants); + + Long originalId = pants.getId(); + + pants.setTitle(UPDATED_TITLE); + pants.setPrice(BigDecimal.TEN); + pants.setBrand(UPDATED_BRAND); + + MerchandiseEntity result = repository.save(pants); + + assertEquals(originalId, result.getId()); + assertEquals(UPDATED_TITLE, result.getTitle()); + assertEquals(BigDecimal.TEN, result.getPrice()); + assertEquals(UPDATED_BRAND, result.getBrand()); + } +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/JpaRepositoriesIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/JpaRepositoriesIntegrationTest.java new file mode 100644 index 0000000000..01405c0b8a --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/JpaRepositoriesIntegrationTest.java @@ -0,0 +1,96 @@ +package com.baeldung.dao.repositories; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertNull; +import static junit.framework.TestCase.assertTrue; + +import java.util.List; +import java.util.Optional; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; +import com.baeldung.domain.Item; +import com.baeldung.domain.ItemType; +import com.baeldung.domain.Location; +import com.baeldung.domain.Store; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = { PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class }) +public class JpaRepositoriesIntegrationTest { + @Autowired + private LocationRepository locationRepository; + @Autowired + private StoreRepository storeRepository; + @Autowired + private ItemTypeRepository compositeRepository; + @Autowired + private ReadOnlyLocationRepository readOnlyRepository; + + @Test + public void whenSaveLocation_ThenGetSameLocation() { + Location location = new Location(); + location.setId(100L); + location.setCountry("Country H"); + location.setCity("City Hundred"); + location = locationRepository.saveAndFlush(location); + + Location otherLocation = locationRepository.getOne(location.getId()); + assertEquals("Country H", otherLocation.getCountry()); + assertEquals("City Hundred", otherLocation.getCity()); + + locationRepository.delete(otherLocation); + } + + @Test + public void givenLocationId_whenFindStores_thenGetStores() { + List stores = storeRepository.findStoreByLocationId(1L); + assertEquals(1, stores.size()); + } + + @Test + public void givenItemTypeId_whenDeleted_ThenItemTypeDeleted() { + Optional itemType = compositeRepository.findById(1L); + assertTrue(itemType.isPresent()); + compositeRepository.deleteCustom(itemType.get()); + itemType = compositeRepository.findById(1L); + assertFalse(itemType.isPresent()); + } + + @Test + public void givenItemId_whenUsingCustomRepo_ThenDeleteAppropriateEntity() { + Item item = compositeRepository.findItemById(1L); + assertNotNull(item); + compositeRepository.deleteCustom(item); + item = compositeRepository.findItemById(1L); + assertNull(item); + } + + @Test + public void givenItemAndItemType_WhenAmbiguousDeleteCalled_ThenItemTypeDeletedAndNotItem() { + Optional itemType = compositeRepository.findById(1L); + assertTrue(itemType.isPresent()); + Item item = compositeRepository.findItemById(2L); + assertNotNull(item); + + compositeRepository.findThenDelete(1L); + Optional sameItemType = compositeRepository.findById(1L); + assertFalse(sameItemType.isPresent()); + Item sameItem = compositeRepository.findItemById(2L); + assertNotNull(sameItem); + } + + @Test + public void whenCreatingReadOnlyRepo_thenHaveOnlyReadOnlyOperationsAvailable() { + Optional location = readOnlyRepository.findById(1L); + assertNotNull(location); + } +} diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java similarity index 67% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java rename to spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java index 9effd4717f..e29161394b 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/UserRepositoryIntegrationTest.java +++ b/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java @@ -1,23 +1,25 @@ -package org.baeldung.persistence.repository; +package com.baeldung.dao.repositories; -import org.baeldung.config.PersistenceJPAConfigL2Cache; -import org.baeldung.persistence.model.User; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.dao.repositories.user.UserRepository; +import com.baeldung.domain.user.User; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.JpaSort; import org.springframework.data.mapping.PropertyReferenceException; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; @@ -25,32 +27,71 @@ import static org.assertj.core.api.Assertions.assertThat; * Created by adam. */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = PersistenceJPAConfigL2Cache.class) +@SpringBootTest(classes = PersistenceConfiguration.class) @DirtiesContext public class UserRepositoryIntegrationTest { private final String USER_NAME_ADAM = "Adam"; private final String USER_NAME_PETER = "Peter"; + + private final String USER_EMAIL = "email@example.com"; + private final String USER_EMAIL2 = "email2@example.com"; + private final String USER_EMAIL3 = "email3@example.com"; + private final String USER_EMAIL4 = "email4@example.com"; + private final String USER_EMAIL5 = "email5@example.com"; + private final String USER_EMAIL6 = "email6@example.com"; + private final Integer INACTIVE_STATUS = 0; private final Integer ACTIVE_STATUS = 1; @Autowired private UserRepository userRepository; + @Test + @Transactional + public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + userRepository.save(user3); + + User user4 = new User(); + user4.setName("SAMPLE"); + user4.setEmail(USER_EMAIL4); + userRepository.save(user4); + + try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { + assertThat(foundUsersStream.count()).isEqualTo(3l); + } + } + @Test public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() { User user1 = new User(); user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); user1.setStatus(ACTIVE_STATUS); userRepository.save(user1); User user2 = new User(); user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); User user3 = new User(); user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); user3.setStatus(INACTIVE_STATUS); userRepository.save(user3); @@ -63,16 +104,19 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() { User user1 = new User(); user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); user1.setStatus(ACTIVE_STATUS); userRepository.save(user1); User user2 = new User(); user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); User user3 = new User(); user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); user3.setStatus(INACTIVE_STATUS); userRepository.save(user3); @@ -85,6 +129,7 @@ public class UserRepositoryIntegrationTest { public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); @@ -97,6 +142,7 @@ public class UserRepositoryIntegrationTest { public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); @@ -109,11 +155,13 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); User user2 = new User(); user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); @@ -126,11 +174,13 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); User user2 = new User(); user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); @@ -143,11 +193,13 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); User user2 = new User(); user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); @@ -160,11 +212,13 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); User user2 = new User(); user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); user2.setStatus(ACTIVE_STATUS); userRepository.save(user2); @@ -177,6 +231,7 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); @@ -189,6 +244,7 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); @@ -201,6 +257,7 @@ public class UserRepositoryIntegrationTest { public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() { User user = new User(); user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); user.setStatus(ACTIVE_STATUS); userRepository.save(user); @@ -211,9 +268,9 @@ public class UserRepositoryIntegrationTest { @Test public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); @@ -224,9 +281,9 @@ public class UserRepositoryIntegrationTest { @Test(expected = PropertyReferenceException.class) public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); @@ -239,9 +296,9 @@ public class UserRepositoryIntegrationTest { @Test public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); userRepository.findAllUsers(new Sort("name")); @@ -254,12 +311,12 @@ public class UserRepositoryIntegrationTest { @Test public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", INACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS)); Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); @@ -271,12 +328,12 @@ public class UserRepositoryIntegrationTest { @Test public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", INACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS)); Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); @@ -289,10 +346,10 @@ public class UserRepositoryIntegrationTest { @Test @Transactional public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS)); int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); @@ -302,10 +359,10 @@ public class UserRepositoryIntegrationTest { @Test @Transactional public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS)); userRepository.flush(); int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); diff --git a/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate2EventsIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate2EventsIntegrationTest.java new file mode 100644 index 0000000000..3f650d4d63 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate2EventsIntegrationTest.java @@ -0,0 +1,68 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +@SpringJUnitConfig +@SpringBootTest +class Aggregate2EventsIntegrationTest { + @MockBean + private TestEventHandler eventHandler; + @Autowired + private Aggregate2Repository repository; + + // @formatter:off + @DisplayName("given aggregate with @AfterDomainEventPublication," + + " when do domain operation and save twice," + + " then an event is published only for the first time") + // @formatter:on + @Test + void afterDomainEvents() { + // given + Aggregate2 aggregate = new Aggregate2(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + + @BeforeEach + void beforeEach() { + repository.deleteAll(); + } + + // @formatter:off + @DisplayName("given aggregate with @DomainEvents," + + " when do domain operation and save," + + " then an event is published") + // @formatter:on + @Test + void domainEvents() { + // given + Aggregate2 aggregate = new Aggregate2(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate3EventsIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate3EventsIntegrationTest.java new file mode 100644 index 0000000000..893dcac3f8 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/Aggregate3EventsIntegrationTest.java @@ -0,0 +1,63 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +@SpringJUnitConfig +@SpringBootTest +class Aggregate3EventsIntegrationTest { + + @MockBean + private TestEventHandler eventHandler; + @Autowired + private Aggregate3Repository repository; + + // @formatter:off + @DisplayName("given aggregate extending AbstractAggregateRoot," + + " when do domain operation and save twice," + + " then an event is published only for the first time") + // @formatter:on + @Test + void afterDomainEvents() { + // given + Aggregate3 aggregate = new Aggregate3(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + + // @formatter:off + @DisplayName("given aggregate extending AbstractAggregateRoot," + + " when do domain operation and save," + + " then an event is published") + // @formatter:on + @Test + void domainEvents() { + // given + Aggregate3 aggregate = new Aggregate3(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/ddd/event/AggregateEventsIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/AggregateEventsIntegrationTest.java new file mode 100644 index 0000000000..f0e1147245 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/AggregateEventsIntegrationTest.java @@ -0,0 +1,82 @@ +package com.baeldung.ddd.event; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.annotation.Bean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +@SpringJUnitConfig +@SpringBootTest +class AggregateEventsIntegrationTest { + + @Autowired + private DomainService domainService; + + @MockBean + private TestEventHandler eventHandler; + @Autowired + private ApplicationEventPublisher eventPublisher; + @Autowired + private AggregateRepository repository; + + // @formatter:off + @DisplayName("given existing aggregate," + + " when do domain operation directly on aggregate," + + " then domain event is NOT published") + // @formatter:on + @Test + void aggregateEventsTest() { + Aggregate existingDomainEntity = new Aggregate(0, eventPublisher); + repository.save(existingDomainEntity); + + // when + repository.findById(existingDomainEntity.getId()) + .get() + .domainOperation(); + + // then + verifyZeroInteractions(eventHandler); + } + + @BeforeEach + void beforeEach() { + repository.deleteAll(); + } + + // @formatter:off + @DisplayName("given existing aggregate," + + " when do domain operation on service," + + " then domain event is published") + // @formatter:on + @Test + void serviceEventsTest() { + Aggregate existingDomainEntity = new Aggregate(1, eventPublisher); + repository.save(existingDomainEntity); + + // when + domainService.serviceDomainOperation(existingDomainEntity.getId()); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + + @TestConfiguration + public static class TestConfig { + @Bean + public DomainService domainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) { + return new DomainService(repository, eventPublisher); + } + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/ddd/event/TestEventHandler.java b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/TestEventHandler.java new file mode 100644 index 0000000000..721402c17a --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/ddd/event/TestEventHandler.java @@ -0,0 +1,12 @@ +/** + * + */ +package com.baeldung.ddd.event; + +import org.springframework.transaction.event.TransactionalEventListener; + +interface TestEventHandler { + @TransactionalEventListener + void handleEvent(DomainEvent event); + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/services/AbstractServicePersistenceIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/AbstractServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..acac66f2f7 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/services/AbstractServicePersistenceIntegrationTest.java @@ -0,0 +1,251 @@ +package com.baeldung.services; + +import com.baeldung.domain.Foo; +import com.baeldung.util.IDUtil; +import org.hamcrest.Matchers; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.dao.DataAccessException; + +import java.io.Serializable; +import java.util.List; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.*; + +public abstract class AbstractServicePersistenceIntegrationTest { + + // tests + + // find - one + + @Test + /**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() { + // When + final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong()); + + // Then + assertNull(createdResource); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() { + final Foo existingResource = persistNewEntity(); + getApi().findOne(existingResource.getId()); + } + + @Test + public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() { + getApi().findOne(IDUtil.randomPositiveLong()); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() { + final Foo existingResource = persistNewEntity(); + final Foo retrievedResource = getApi().findOne(existingResource.getId()); + assertNotNull(retrievedResource); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() { + final Foo existingResource = persistNewEntity(); + final Foo retrievedResource = getApi().findOne(existingResource.getId()); + assertEquals(existingResource, retrievedResource); + } + + // find - one - by name + + // find - all + + @Test + /**/public void whenAllResourcesAreRetrieved_thenNoExceptions() { + getApi().findAll(); + } + + @Test + /**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() { + final List resources = getApi().findAll(); + + assertNotNull(resources); + } + + @Test + /**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() { + persistNewEntity(); + + // When + final List allResources = getApi().findAll(); + + // Then + assertThat(allResources, not(Matchers. empty())); + } + + @Test + /**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() { + final Foo existingResource = persistNewEntity(); + + final List resources = getApi().findAll(); + + assertThat(resources, hasItem(existingResource)); + } + + @Test + /**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() { + persistNewEntity(); + + // When + final List allResources = getApi().findAll(); + + // Then + for (final Foo resource : allResources) { + assertNotNull(resource.getId()); + } + } + + // create + + @Test(expected = RuntimeException.class) + /**/public void whenNullResourceIsCreated_thenException() { + getApi().create(null); + } + + @Test + /**/public void whenResourceIsCreated_thenNoExceptions() { + persistNewEntity(); + } + + @Test + /**/public void whenResourceIsCreated_thenResourceIsRetrievable() { + final Foo existingResource = persistNewEntity(); + + assertNotNull(getApi().findOne(existingResource.getId())); + } + + @Test + /**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() { + final Foo originalResource = createNewEntity(); + final Foo savedResource = getApi().create(originalResource); + + assertEquals(originalResource, savedResource); + } + + @Test(expected = RuntimeException.class) + public void whenResourceWithFailedConstraintsIsCreated_thenException() { + final Foo invalidResource = createNewEntity(); + invalidate(invalidResource); + + getApi().create(invalidResource); + } + + /** + * -- specific to the persistence engine + */ + @Test(expected = DataAccessException.class) + @Ignore("Hibernate simply ignores the id silently and still saved (tracking this)") + public void whenResourceWithIdIsCreated_thenDataAccessException() { + final Foo resourceWithId = createNewEntity(); + resourceWithId.setId(IDUtil.randomPositiveLong()); + + getApi().create(resourceWithId); + } + + // update + + @Test(expected = RuntimeException.class) + /**/public void whenNullResourceIsUpdated_thenException() { + getApi().update(null); + } + + @Test + /**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() { + // Given + final Foo existingResource = persistNewEntity(); + + // When + getApi().update(existingResource); + } + + /** + * - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException + */ + @Test(expected = RuntimeException.class) + public void whenResourceIsUpdatedWithFailedConstraints_thenException() { + final Foo existingResource = persistNewEntity(); + invalidate(existingResource); + + getApi().update(existingResource); + } + + @Test + /**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() { + // Given + final Foo existingResource = persistNewEntity(); + + // When + change(existingResource); + getApi().update(existingResource); + + final Foo updatedResource = getApi().findOne(existingResource.getId()); + + // Then + assertEquals(existingResource, updatedResource); + } + + // delete + + // @Test(expected = RuntimeException.class) + // public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() { + // // When + // getApi().delete(IDUtil.randomPositiveLong()); + // } + // + // @Test(expected = RuntimeException.class) + // public void whenResourceIsDeletedByNegativeId_thenException() { + // // When + // getApi().delete(IDUtil.randomNegativeLong()); + // } + // + // @Test + // public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() { + // // Given + // final Foo existingResource = persistNewEntity(); + // + // // When + // getApi().delete(existingResource.getId()); + // } + // + // @Test + // /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() { + // // Given + // final Foo existingResource = persistNewEntity(); + // + // // When + // getApi().delete(existingResource.getId()); + // + // // Then + // assertNull(getApi().findOne(existingResource.getId())); + // } + + // template method + + protected Foo createNewEntity() { + return new Foo(randomAlphabetic(6)); + } + + protected abstract IOperations getApi(); + + private final void invalidate(final Foo entity) { + entity.setName(null); + } + + private final void change(final Foo entity) { + entity.setName(randomAlphabetic(6)); + } + + protected Foo persistNewEntity() { + return getApi().create(createNewEntity()); + } + +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/services/FooServicePersistenceIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/FooServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..fd17d033e1 --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/services/FooServicePersistenceIntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.services; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.Foo; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {PersistenceConfiguration.class}, loader = AnnotationConfigContextLoader.class) +public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest { + + @Autowired + private IFooService service; + + // tests + + @Test + public final void whenContextIsBootstrapped_thenNoExceptions() { + // + } + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Foo(randomAlphabetic(6))); + } + + @Test(expected = DataIntegrityViolationException.class) + public final void whenInvalidEntityIsCreated_thenDataException() { + service.create(new Foo()); + } + + @Test(expected = DataIntegrityViolationException.class) + public final void whenEntityWithLongNameIsCreated_thenDataException() { + service.create(new Foo(randomAlphabetic(2048))); + } + + // custom Query method + + @Test + public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() { + final String name = randomAlphabetic(6); + service.create(new Foo(name)); + + final Foo retrievedByName = service.retrieveByName(name); + assertNotNull(retrievedByName); + } + + // work in progress + + @Test(expected = InvalidDataAccessApiUsageException.class) + @Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail") + public final void whenSameEntityIsCreatedTwice_thenDataException() { + final Foo entity = new Foo(randomAlphabetic(8)); + service.create(entity); + service.create(entity); + } + + // API + + @Override + protected final IOperations getApi() { + return service; + } + +} diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/JpaMultipleDBIntegrationTest.java similarity index 65% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java rename to spring-data-jpa/src/test/java/com/baeldung/services/JpaMultipleDBIntegrationTest.java index 6cd187230c..71a3fb0b44 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java +++ b/spring-data-jpa/src/test/java/com/baeldung/services/JpaMultipleDBIntegrationTest.java @@ -1,31 +1,33 @@ -package org.baeldung.persistence.service; +package com.baeldung.services; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.util.Arrays; +import java.util.Collections; +import java.util.Optional; -import org.baeldung.config.ProductConfig; -import org.baeldung.config.UserConfig; -import org.baeldung.persistence.multiple.dao.product.ProductRepository; -import org.baeldung.persistence.multiple.dao.user.PossessionRepository; -import org.baeldung.persistence.multiple.dao.user.UserRepository; -import org.baeldung.persistence.multiple.model.product.Product; -import org.baeldung.persistence.multiple.model.user.Possession; -import org.baeldung.persistence.multiple.model.user.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { UserConfig.class, ProductConfig.class }) +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; +import com.baeldung.dao.repositories.product.ProductRepository; +import com.baeldung.dao.repositories.user.PossessionRepository; +import com.baeldung.dao.repositories.user.UserRepository; +import com.baeldung.domain.product.Product; +import com.baeldung.domain.user.Possession; +import com.baeldung.domain.user.User; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { PersistenceUserConfiguration.class, PersistenceProductConfiguration.class }) @EnableTransactionManagement @DirtiesContext public class JpaMultipleDBIntegrationTest { @@ -50,12 +52,12 @@ public class JpaMultipleDBIntegrationTest { user.setAge(20); Possession p = new Possession("sample"); p = possessionRepository.save(p); - user.setPossessionList(Arrays.asList(p)); + user.setPossessionList(Collections.singletonList(p)); user = userRepository.save(user); - final User result = userRepository.findOne(user.getId()); - assertNotNull(result); - System.out.println(result.getPossessionList()); - assertTrue(result.getPossessionList().size() == 1); + final Optional result = userRepository.findById(user.getId()); + assertTrue(result.isPresent()); + System.out.println(result.get().getPossessionList()); + assertEquals(1, result.get().getPossessionList().size()); } @Test @@ -66,7 +68,7 @@ public class JpaMultipleDBIntegrationTest { user1.setEmail("john@test.com"); user1.setAge(20); user1 = userRepository.save(user1); - assertNotNull(userRepository.findOne(user1.getId())); + assertTrue(userRepository.findById(user1.getId()).isPresent()); User user2 = new User(); user2.setName("Tom"); @@ -92,7 +94,7 @@ public class JpaMultipleDBIntegrationTest { product.setPrice(20); product = productRepository.save(product); - assertNotNull(productRepository.findOne(product.getId())); + assertTrue(productRepository.findById(product.getId()).isPresent()); } } diff --git a/spring-data-jpa/src/test/java/com/baeldung/services/SpringDataJPABarAuditIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/services/SpringDataJPABarAuditIntegrationTest.java new file mode 100644 index 0000000000..f3b857c73d --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/services/SpringDataJPABarAuditIntegrationTest.java @@ -0,0 +1,76 @@ +package com.baeldung.services; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +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.beans.factory.annotation.Qualifier; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.domain.Bar; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { PersistenceConfiguration.class }, loader = AnnotationConfigContextLoader.class) +public class SpringDataJPABarAuditIntegrationTest { + + private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("barSpringDataJpaService") + private IBarService barService; + + @Autowired + private EntityManagerFactory entityManagerFactory; + + private EntityManager em; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + em = entityManagerFactory.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + em.close(); + } + + @Test + @WithMockUser(username = "tutorialuser") + public final void whenBarsModified_thenBarsAudited() { + Bar bar = new Bar("BAR1"); + barService.create(bar); + assertEquals(bar.getCreatedDate(), bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + bar.setName("BAR2"); + bar = barService.update(bar); + assertTrue(bar.getCreatedDate() < bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + } +} diff --git a/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java b/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java new file mode 100644 index 0000000000..45e72e046d --- /dev/null +++ b/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java @@ -0,0 +1,33 @@ +package com.baeldung.util; + +import java.util.Random; + +public final class IDUtil { + + private IDUtil() { + throw new AssertionError(); + } + + // API + + public static String randomPositiveLongAsString() { + return Long.toString(randomPositiveLong()); + } + + public static String randomNegativeLongAsString() { + return Long.toString(randomNegativeLong()); + } + + public static long randomPositiveLong() { + long id = new Random().nextLong() * 10000; + id = (id < 0) ? (-1 * id) : id; + return id; + } + + private static long randomNegativeLong() { + long id = new Random().nextLong() * 10000; + id = (id > 0) ? (-1 * id) : id; + return id; + } + +} diff --git a/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0a60412813 --- /dev/null +++ b/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,22 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class}) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-jpa/src/test/resources/import_articles.sql b/spring-data-jpa/src/test/resources/import_articles.sql deleted file mode 100644 index 4fe18bf4aa..0000000000 --- a/spring-data-jpa/src/test/resources/import_articles.sql +++ /dev/null @@ -1,3 +0,0 @@ -insert into Article(id, publication_date, publication_time, creation_date_time) values(1, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:00', 'HH24:MI'), TO_DATE('31/12/2017 07:30', 'DD/MM/YYYY HH24:MI')); -insert into Article(id, publication_date, publication_time, creation_date_time) values(2, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:30', 'HH24:MI'), TO_DATE('15/12/2017 08:00', 'DD/MM/YYYY HH24:MI')); -insert into Article(id, publication_date, publication_time, creation_date_time) values(3, TO_DATE('15/12/2017', 'DD/MM/YYYY'), TO_DATE('16:00', 'HH24:MI'), TO_DATE('01/12/2017 13:45', 'DD/MM/YYYY HH24:MI')); \ No newline at end of file diff --git a/spring-data-jpa/src/test/resources/import_entities.sql b/spring-data-jpa/src/test/resources/import_entities.sql new file mode 100644 index 0000000000..deb9d07f05 --- /dev/null +++ b/spring-data-jpa/src/test/resources/import_entities.sql @@ -0,0 +1,21 @@ +insert into Article(id, publication_date, publication_time, creation_date_time) values(1, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:00', 'HH24:MI'), TO_DATE('31/12/2017 07:30', 'DD/MM/YYYY HH24:MI')); +insert into Article(id, publication_date, publication_time, creation_date_time) values(2, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:30', 'HH24:MI'), TO_DATE('15/12/2017 08:00', 'DD/MM/YYYY HH24:MI')); +insert into Article(id, publication_date, publication_time, creation_date_time) values(3, TO_DATE('15/12/2017', 'DD/MM/YYYY'), TO_DATE('16:00', 'HH24:MI'), TO_DATE('01/12/2017 13:45', 'DD/MM/YYYY HH24:MI')); + +insert into location (id, country, city) values (1, 'Country X', 'City One'); +insert into location (id, country, city) values (2, 'Country X', 'City Two'); +insert into location (id, country, city) values (3, 'Country X', 'City Three'); + +insert into store (id, name, location_id, items_sold, active) values (1, 'Store One', 3, 130000, true); +insert into store (id, name, location_id, items_sold, active) values (2, 'Store Two', 1, 170000, false); + +insert into item_type (id, name) values (1, 'Food'); +insert into item_type (id, name) values (2, 'Furniture'); +insert into item_type (id, name) values (3, 'Electronics'); + +insert into item (id, name, store_id, item_type_id, price, grade, color) values (1, 'Food Item One', 1, 1, 100, 'A', 'Color x'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (2, 'Furniture Item One', 1, 2, 2500, 'B', 'Color y'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (3, 'Food Item Two', 1, 1, 35, 'A', 'Color z'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (5, 'Furniture Item Two', 2, 2, 1600, 'A', 'Color w'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (6, 'Food Item Three', 2, 1, 5, 'B', 'Color a'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (7, 'Electronics Item One', 2, 3, 999, 'B', 'Color b'); diff --git a/spring-data-keyvalue/pom.xml b/spring-data-keyvalue/pom.xml index 6ab928303d..edd8967b97 100644 --- a/spring-data-keyvalue/pom.xml +++ b/spring-data-keyvalue/pom.xml @@ -1,9 +1,7 @@ 4.0.0 - com.baeldung spring-data-keyvalue - 1.0 parent-boot-2 @@ -13,7 +11,6 @@ - org.springframework.boot spring-boot-starter @@ -30,8 +27,4 @@ - - 2.0.3.RELEASE - - \ No newline at end of file diff --git a/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..d28bdcbc89 --- /dev/null +++ b/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.data.keyvalue.SpringDataKeyValueApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataKeyValueApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 332245adc8..072ed7a2ac 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../parent-spring-4 + ../parent-spring-5 @@ -19,6 +19,34 @@ spring-data-mongodb ${org.springframework.data.version} + + + org.springframework.data + spring-data-releasetrain + Lovelace-M3 + pom + import + + + + org.mongodb + mongodb-driver-reactivestreams + ${mongodb-reactivestreams.version} + + + + io.projectreactor + reactor-core + ${projectreactor.version} + + + + io.projectreactor + reactor-test + ${projectreactor.version} + test + + org.springframework spring-core @@ -48,6 +76,17 @@ + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + @@ -70,10 +109,13 @@ - 1.10.4.RELEASE - 2.9.0 + 2.1.0.RELEASE 4.1.4 1.1.3 + 5.1.0.RELEASE + 1.9.2 + 3.2.0.RELEASE + diff --git a/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java b/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java index 551a9142a6..f1048fa145 100644 --- a/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java @@ -1,21 +1,23 @@ package com.baeldung.config; -import com.mongodb.Mongo; -import com.mongodb.MongoClient; -import com.baeldung.converter.UserWriterConverter; -import com.baeldung.event.CascadeSaveMongoEventListener; -import com.baeldung.event.UserCascadeSaveMongoEventListener; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.convert.converter.Converter; -import org.springframework.data.mongodb.config.AbstractMongoConfiguration; -import org.springframework.data.mongodb.core.convert.CustomConversions; -import org.springframework.data.mongodb.gridfs.GridFsTemplate; -import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; - import java.util.ArrayList; import java.util.List; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.mongodb.MongoDbFactory; +import org.springframework.data.mongodb.MongoTransactionManager; +import org.springframework.data.mongodb.config.AbstractMongoConfiguration; +import org.springframework.data.mongodb.core.convert.MongoCustomConversions; +import org.springframework.data.mongodb.gridfs.GridFsTemplate; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; + +import com.baeldung.converter.UserWriterConverter; +import com.baeldung.event.CascadeSaveMongoEventListener; +import com.baeldung.event.UserCascadeSaveMongoEventListener; +import com.mongodb.MongoClient; + @Configuration @EnableMongoRepositories(basePackages = "com.baeldung.repository") public class MongoConfig extends AbstractMongoConfiguration { @@ -28,7 +30,7 @@ public class MongoConfig extends AbstractMongoConfiguration { } @Override - public Mongo mongo() throws Exception { + public MongoClient mongoClient() { return new MongoClient("127.0.0.1", 27017); } @@ -48,13 +50,19 @@ public class MongoConfig extends AbstractMongoConfiguration { } @Override - public CustomConversions customConversions() { + public MongoCustomConversions customConversions() { converters.add(new UserWriterConverter()); - return new CustomConversions(converters); + return new MongoCustomConversions(converters); } @Bean public GridFsTemplate gridFsTemplate() throws Exception { return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter()); } + + @Bean + MongoTransactionManager transactionManager(MongoDbFactory dbFactory) { + return new MongoTransactionManager(dbFactory); + } + } diff --git a/spring-data-mongodb/src/main/java/com/baeldung/config/MongoReactiveConfig.java b/spring-data-mongodb/src/main/java/com/baeldung/config/MongoReactiveConfig.java new file mode 100644 index 0000000000..b4042b5550 --- /dev/null +++ b/spring-data-mongodb/src/main/java/com/baeldung/config/MongoReactiveConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.config.AbstractReactiveMongoConfiguration; +import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories; + +import com.mongodb.reactivestreams.client.MongoClient; +import com.mongodb.reactivestreams.client.MongoClients; + +@Configuration +@EnableReactiveMongoRepositories(basePackages = "com.baeldung.reactive.repository") +public class MongoReactiveConfig extends AbstractReactiveMongoConfiguration { + + @Override + public MongoClient reactiveMongoClient() { + return MongoClients.create(); + } + + @Override + protected String getDatabaseName() { + return "reactive"; + } +} diff --git a/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java b/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java index 95f192811f..c3ddad5a82 100644 --- a/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java @@ -1,18 +1,18 @@ package com.baeldung.config; -import com.mongodb.Mongo; -import com.mongodb.MongoClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; +import com.mongodb.MongoClient; + @Configuration @EnableMongoRepositories(basePackages = "com.baeldung.repository") public class SimpleMongoConfig { @Bean - public Mongo mongo() throws Exception { + public MongoClient mongo() throws Exception { return new MongoClient("localhost"); } diff --git a/spring-data-mongodb/src/main/java/com/baeldung/reactive/repository/UserRepository.java b/spring-data-mongodb/src/main/java/com/baeldung/reactive/repository/UserRepository.java new file mode 100644 index 0000000000..7e754aa680 --- /dev/null +++ b/spring-data-mongodb/src/main/java/com/baeldung/reactive/repository/UserRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.reactive.repository; + +import org.springframework.data.mongodb.repository.ReactiveMongoRepository; + +import com.baeldung.model.User; + + +public interface UserRepository extends ReactiveMongoRepository { +} diff --git a/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java b/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java index e9dc0f5c95..4c69d7f9c6 100644 --- a/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java @@ -1,13 +1,14 @@ package com.baeldung.repository; -import com.baeldung.model.User; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; - import java.util.List; -public interface UserRepository extends MongoRepository, QueryDslPredicateExecutor { +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; + +import com.baeldung.model.User; + +public interface UserRepository extends MongoRepository, QuerydslPredicateExecutor { @Query("{ 'name' : ?0 }") List findUsersByName(String name); diff --git a/spring-data-mongodb/src/main/resources/logback.xml b/spring-data-mongodb/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-data-mongodb/src/main/resources/logback.xml +++ b/spring-data-mongodb/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-data-mongodb/src/main/resources/mongoConfig.xml b/spring-data-mongodb/src/main/resources/mongoConfig.xml index 2b32863fb6..324f7f60c2 100644 --- a/spring-data-mongodb/src/main/resources/mongoConfig.xml +++ b/spring-data-mongodb/src/main/resources/mongoConfig.xml @@ -3,17 +3,17 @@ xmlns:p="http://www.springframework.org/schema/p" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation=" http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-3.2.xsd + http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/mongo - http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd + http://www.springframework.org/schema/data/mongo/spring-mongo.xsd http://www.springframework.org/schema/context - http://www.springframework.org/schema/context/spring-context-3.2.xsd" + http://www.springframework.org/schema/context/spring-context.xsd" > - + - + @@ -27,12 +27,12 @@ - + - + - + diff --git a/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java index a4bea45fcf..1da50d7cb4 100644 --- a/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java @@ -1,12 +1,24 @@ package com.baeldung.aggregation; -import com.mongodb.DB; -import com.mongodb.DBCollection; -import com.mongodb.DBObject; -import com.mongodb.MongoClient; -import com.mongodb.util.JSON; -import com.baeldung.aggregation.model.StatePopulation; -import com.baeldung.config.MongoConfig; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.group; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.limit; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.match; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.project; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import org.bson.Document; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -26,23 +38,11 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.data.mongodb.core.aggregation.Aggregation.group; -import static org.springframework.data.mongodb.core.aggregation.Aggregation.limit; -import static org.springframework.data.mongodb.core.aggregation.Aggregation.match; -import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation; -import static org.springframework.data.mongodb.core.aggregation.Aggregation.project; -import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort; +import com.baeldung.aggregation.model.StatePopulation; +import com.baeldung.config.MongoConfig; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) @@ -56,23 +56,22 @@ public class ZipsAggregationLiveTest { @BeforeClass public static void setupTests() throws Exception { client = new MongoClient(); - DB testDB = client.getDB("test"); - DBCollection zipsCollection = testDB.getCollection("zips"); + MongoDatabase testDB = client.getDatabase("test"); + MongoCollection zipsCollection = testDB.getCollection("zips"); zipsCollection.drop(); InputStream zipsJsonStream = ZipsAggregationLiveTest.class.getResourceAsStream("/zips.json"); BufferedReader reader = new BufferedReader(new InputStreamReader(zipsJsonStream)); reader.lines() - .forEach(line -> zipsCollection.insert((DBObject) JSON.parse(line))); + .forEach(line -> zipsCollection.insertOne(Document.parse(line))); reader.close(); - } @AfterClass public static void tearDown() throws Exception { client = new MongoClient(); - DB testDB = client.getDB("test"); - DBCollection zipsCollection = testDB.getCollection("zips"); + MongoDatabase testDB = client.getDatabase("test"); + MongoCollection zipsCollection = testDB.getCollection("zips"); zipsCollection.drop(); client.close(); } @@ -140,13 +139,13 @@ public class ZipsAggregationLiveTest { Aggregation aggregation = newAggregation(sumZips, sortByCount, groupFirstAndLast); - AggregationResults result = mongoTemplate.aggregate(aggregation, "zips", DBObject.class); - DBObject dbObject = result.getUniqueMappedResult(); + AggregationResults result = mongoTemplate.aggregate(aggregation, "zips", Document.class); + Document document = result.getUniqueMappedResult(); - assertEquals("DC", dbObject.get("minZipState")); - assertEquals(24, dbObject.get("minZipCount")); - assertEquals("TX", dbObject.get("maxZipState")); - assertEquals(1671, dbObject.get("maxZipCount")); + assertEquals("DC", document.get("minZipState")); + assertEquals(24, document.get("minZipCount")); + assertEquals("TX", document.get("maxZipState")); + assertEquals(1671, document.get("maxZipCount")); } } diff --git a/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java index 02485e8517..3a88a1e654 100644 --- a/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java @@ -1,8 +1,19 @@ package com.baeldung.gridfs; -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.gridfs.GridFSDBFile; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import org.bson.types.ObjectId; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,18 +27,9 @@ import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import com.mongodb.BasicDBObject; +import com.mongodb.DBObject; +import com.mongodb.client.gridfs.model.GridFSFile; @ContextConfiguration("file:src/main/resources/mongoConfig.xml") @RunWith(SpringJUnit4ClassRunner.class) @@ -40,8 +42,9 @@ public class GridFSLiveTest { @After public void tearDown() { - List fileList = gridFsTemplate.find(null); - for (GridFSDBFile file : fileList) { + List fileList = new ArrayList(); + gridFsTemplate.find(new Query()).into(fileList); + for (GridFSFile file : fileList) { gridFsTemplate.delete(new Query(Criteria.where("filename").is(file.getFilename()))); } } @@ -54,7 +57,7 @@ public class GridFSLiveTest { String id = ""; try { inputStream = new FileInputStream("src/main/resources/test.png"); - id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).getId().toString(); + id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).toString(); } catch (FileNotFoundException ex) { logger.error("File not found", ex); } finally { @@ -75,10 +78,10 @@ public class GridFSLiveTest { DBObject metaData = new BasicDBObject(); metaData.put("user", "alex"); InputStream inputStream = null; - String id = ""; + ObjectId id = null; try { inputStream = new FileInputStream("src/main/resources/test.png"); - id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).getId().toString(); + id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData); } catch (FileNotFoundException ex) { logger.error("File not found", ex); } finally { @@ -91,22 +94,22 @@ public class GridFSLiveTest { } } - GridFSDBFile gridFSDBFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id))); + GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id))); - assertNotNull(gridFSDBFile); - assertNotNull(gridFSDBFile.getInputStream()); - assertThat(gridFSDBFile.numChunks(), is(1)); - assertThat(gridFSDBFile.containsField("filename"), is(true)); - assertThat(gridFSDBFile.get("filename"), is("test.png")); - assertThat(gridFSDBFile.getId(), is(id)); - assertThat(gridFSDBFile.keySet().size(), is(9)); - assertNotNull(gridFSDBFile.getMD5()); - assertNotNull(gridFSDBFile.getUploadDate()); - assertNull(gridFSDBFile.getAliases()); - assertNotNull(gridFSDBFile.getChunkSize()); - assertThat(gridFSDBFile.getContentType(), is("image/png")); - assertThat(gridFSDBFile.getFilename(), is("test.png")); - assertThat(gridFSDBFile.getMetaData().get("user"), is("alex")); + assertNotNull(gridFSFile); +// assertNotNull(gridFSFile.getInputStream()); +// assertThat(gridFSFile.numChunks(), is(1)); +// assertThat(gridFSFile.containsField("filename"), is(true)); + assertThat(gridFSFile.getFilename(), is("test.png")); + assertThat(gridFSFile.getObjectId(), is(id)); +// assertThat(gridFSFile.keySet().size(), is(9)); +// assertNotNull(gridFSFile.getMD5()); + assertNotNull(gridFSFile.getUploadDate()); +// assertNull(gridFSFile.getAliases()); + assertNotNull(gridFSFile.getChunkSize()); + assertThat(gridFSFile.getMetadata().get("_contentType"), is("image/png")); + assertThat(gridFSFile.getFilename(), is("test.png")); + assertThat(gridFSFile.getMetadata().get("user"), is("alex")); } @Test @@ -133,10 +136,11 @@ public class GridFSLiveTest { } } - List gridFSDBFiles = gridFsTemplate.find(null); + List gridFSFiles = new ArrayList(); + gridFsTemplate.find(new Query()).into(gridFSFiles); - assertNotNull(gridFSDBFiles); - assertThat(gridFSDBFiles.size(), is(2)); + assertNotNull(gridFSFiles); + assertThat(gridFSFiles.size(), is(2)); } @Test @@ -163,10 +167,11 @@ public class GridFSLiveTest { } } - List gridFSDBFiles = gridFsTemplate.find(new Query(Criteria.where("metadata.user").is("alex"))); + List gridFSFiles = new ArrayList(); + gridFsTemplate.find(new Query(Criteria.where("metadata.user").is("alex"))).into(gridFSFiles); - assertNotNull(gridFSDBFiles); - assertThat(gridFSDBFiles.size(), is(1)); + assertNotNull(gridFSFiles); + assertThat(gridFSFiles.size(), is(1)); } @Test @@ -177,7 +182,7 @@ public class GridFSLiveTest { String id = ""; try { inputStream = new FileInputStream("src/main/resources/test.png"); - id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).getId().toString(); + id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).toString(); } catch (FileNotFoundException ex) { logger.error("File not found", ex); } finally { @@ -200,10 +205,9 @@ public class GridFSLiveTest { DBObject metaData = new BasicDBObject(); metaData.put("user", "alex"); InputStream inputStream = null; - String id = ""; try { inputStream = new FileInputStream("src/main/resources/test.png"); - id = gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).getId().toString(); + gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).toString(); } catch (FileNotFoundException ex) { logger.error("File not found", ex); } finally { diff --git a/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java index 7a61f9f98a..d05bde0f1b 100644 --- a/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java @@ -1,8 +1,11 @@ package com.baeldung.mongotemplate; -import com.baeldung.config.MongoConfig; -import com.baeldung.model.EmailAddress; -import com.baeldung.model.User; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Iterator; +import java.util.List; + import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -17,11 +20,9 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.Iterator; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.EmailAddress; +import com.baeldung.model.User; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) @@ -152,7 +153,7 @@ public class DocumentQueryLiveTest { user.setAge(35); mongoTemplate.insert(user); - final Pageable pageableRequest = new PageRequest(0, 2); + final Pageable pageableRequest = PageRequest.of(0, 2); Query query = new Query(); query.with(pageableRequest); diff --git a/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java index ee1d4f4760..fc78921b75 100644 --- a/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java @@ -1,8 +1,11 @@ package com.baeldung.mongotemplate; -import com.baeldung.config.MongoConfig; -import com.baeldung.model.EmailAddress; -import com.baeldung.model.User; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +import java.util.List; + import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -20,11 +23,9 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.EmailAddress; +import com.baeldung.model.User; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) @@ -104,7 +105,7 @@ public class MongoTemplateQueryLiveTest { user.setAge(35); mongoTemplate.insert(user); - final Pageable pageableRequest = new PageRequest(0, 2); + final Pageable pageableRequest = PageRequest.of(0, 2); Query query = new Query(); query.with(pageableRequest); diff --git a/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java index da4e91baec..901610e42d 100644 --- a/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java @@ -5,8 +5,6 @@ import static org.junit.Assert.assertThat; import java.util.List; -import com.baeldung.config.MongoConfig; -import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -22,6 +20,9 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class UserRepositoryLiveTest { @@ -72,8 +73,7 @@ public class UserRepositoryLiveTest { user.setName("Jim"); userRepository.save(user); - - assertThat(mongoOps.findAll(User.class).size(), is(2)); + assertThat(mongoOps.findAll(User.class).size(), is(1)); } @Test @@ -94,7 +94,7 @@ public class UserRepositoryLiveTest { mongoOps.insert(user); user = mongoOps.findOne(Query.query(Criteria.where("name").is("Chris")), User.class); - final User foundUser = userRepository.findOne(user.getId()); + final User foundUser = userRepository.findById(user.getId()).get(); assertThat(user.getName(), is(foundUser.getName())); } @@ -106,7 +106,7 @@ public class UserRepositoryLiveTest { mongoOps.insert(user); user = mongoOps.findOne(Query.query(Criteria.where("name").is("Harris")), User.class); - final boolean isExists = userRepository.exists(user.getId()); + final boolean isExists = userRepository.existsById(user.getId()); assertThat(isExists, is(true)); } @@ -138,7 +138,7 @@ public class UserRepositoryLiveTest { user.setName("Adam"); mongoOps.insert(user); - final Pageable pageableRequest = new PageRequest(0, 1); + final Pageable pageableRequest = PageRequest.of(0, 1); final Page page = userRepository.findAll(pageableRequest); List users = page.getContent(); diff --git a/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveIntegrationTest.java b/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveIntegrationTest.java new file mode 100644 index 0000000000..43aa865e91 --- /dev/null +++ b/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.transaction; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.ReactiveMongoOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.config.MongoReactiveConfig; +import com.baeldung.model.User; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MongoReactiveConfig.class) +public class MongoTransactionReactiveIntegrationTest { + + @Autowired + private ReactiveMongoOperations reactiveOps; + + @Before + public void testSetup() { + if (!reactiveOps.collectionExists(User.class) + .block()) { + reactiveOps.createCollection(User.class); + } + } + + @After + public void tearDown() { + System.out.println(reactiveOps.findAll(User.class) + .count() + .block()); + reactiveOps.dropCollection(User.class); + } + + @Test + public void whenPerformTransaction_thenSuccess() { + User user1 = new User("Jane", 23); + User user2 = new User("John", 34); + reactiveOps.inTransaction() + .execute(action -> action.insert(user1) + .then(action.insert(user2))); + } + +} diff --git a/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateIntegrationTest.java b/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateIntegrationTest.java new file mode 100644 index 0000000000..1dbe724d87 --- /dev/null +++ b/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateIntegrationTest.java @@ -0,0 +1,68 @@ +package com.baeldung.transaction; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.MongoTransactionManager; +import org.springframework.data.mongodb.SessionSynchronization; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionCallbackWithoutResult; +import org.springframework.transaction.support.TransactionTemplate; + +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MongoConfig.class) +public class MongoTransactionTemplateIntegrationTest { + + @Autowired + private MongoTemplate mongoTemplate; + + @Autowired + private MongoTransactionManager mongoTransactionManager; + + @Before + public void testSetup() { + if (!mongoTemplate.collectionExists(User.class)) { + mongoTemplate.createCollection(User.class); + } + } + + @After + public void tearDown() { + mongoTemplate.dropCollection(User.class); + } + + @Test + public void givenTransactionTemplate_whenPerformTransaction_thenSuccess() { + mongoTemplate.setSessionSynchronization(SessionSynchronization.ALWAYS); + TransactionTemplate transactionTemplate = new TransactionTemplate(mongoTransactionManager); + transactionTemplate.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) { + mongoTemplate.insert(new User("Kim", 20)); + mongoTemplate.insert(new User("Jack", 45)); + }; + }); + + Query query = new Query().addCriteria(Criteria.where("name") + .is("Jack")); + List users = mongoTemplate.find(query, User.class); + + assertThat(users.size(), is(1)); + } + +} diff --git a/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalIntegrationTest.java b/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalIntegrationTest.java new file mode 100644 index 0000000000..4d747789a0 --- /dev/null +++ b/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalIntegrationTest.java @@ -0,0 +1,90 @@ +package com.baeldung.transaction; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.MongoTransactionException; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; +import com.mongodb.MongoCommandException; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MongoConfig.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class MongoTransactionalIntegrationTest { + + @Autowired + private MongoTemplate mongoTemplate; + + @Autowired + private UserRepository userRepository; + + @Test + @Transactional + public void whenPerformMongoTransaction_thenSuccess() { + userRepository.save(new User("John", 30)); + userRepository.save(new User("Ringo", 35)); + Query query = new Query().addCriteria(Criteria.where("name") + .is("John")); + List users = mongoTemplate.find(query, User.class); + + assertThat(users.size(), is(1)); + } + + @Test(expected = MongoTransactionException.class) + @Transactional + public void whenListCollectionDuringMongoTransaction_thenException() { + if (mongoTemplate.collectionExists(User.class)) { + mongoTemplate.save(new User("John", 30)); + mongoTemplate.save(new User("Ringo", 35)); + } + } + + @Test(expected = MongoCommandException.class) + @Transactional + public void whenCountDuringMongoTransaction_thenException() { + userRepository.save(new User("John", 30)); + userRepository.save(new User("Ringo", 35)); + userRepository.count(); + } + + @Test + @Transactional + public void whenQueryDuringMongoTransaction_thenSuccess() { + userRepository.save(new User("Jane", 20)); + userRepository.save(new User("Nick", 33)); + List users = mongoTemplate.find(new Query(), User.class); + + assertTrue(users.size() > 1); + } + + // ==== Using test instead of before and after due to @transactional doesn't allow list collection + + @Test + public void setup() { + if (!mongoTemplate.collectionExists(User.class)) { + mongoTemplate.createCollection(User.class); + } + } + + @Test + public void ztearDown() { + mongoTemplate.dropCollection(User.class); + } +} diff --git a/spring-data-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..04d549a288 --- /dev/null +++ b/spring-data-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +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; +import com.baeldung.config.SimpleMongoConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MongoConfig.class, SimpleMongoConfig.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7f906bdbcd --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0380e3dc2f --- /dev/null +++ b/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.SpringDataRestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataRestApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-spring-security/README.md b/spring-data-spring-security/README.md deleted file mode 100644 index da65527a8a..0000000000 --- a/spring-data-spring-security/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# About this project -This project contains examples from the [Spring Data with Spring Security](http://www.baeldung.com/spring-data-with-spring-security) article from Baeldung. - -# Running the project -The application uses [Spring Boot](http://projects.spring.io/spring-boot/), so it is easy to run. You can start it any of a few ways: -* Run the `main` method from `SpringDataRestApplication` -* Use the Maven Spring Boot plugin: `mvn spring-boot:run` -* Package the application as a JAR and run it using `java -jar spring-data-spring-security.jar` - -# Viewing the running application -To view the running application, visit [http://localhost:8080](http://localhost:8080) in your browser - -###Relevant Articles: -- [Spring Data with Spring Security](http://www.baeldung.com/spring-data-security) diff --git a/spring-data-spring-security/pom.xml b/spring-data-spring-security/pom.xml deleted file mode 100644 index 09e056ef01..0000000000 --- a/spring-data-spring-security/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-data-spring-security - 1.0 - jar - intro-spring-data-spring-security - Spring Data with Spring Security - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.security - spring-security-data - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.security - spring-security-test - test - - - org.apache.tomcat.embed - tomcat-embed-jasper - - - - com.h2database - h2 - - - javax.servlet - jstl - - - - - ${project.artifactId} - - - diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml index 4e4346e43b..7ac291740e 100644 --- a/spring-dispatcher-servlet/pom.xml +++ b/spring-dispatcher-servlet/pom.xml @@ -61,6 +61,12 @@ commons-fileupload ${commons-fileupload.version} + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8a9d3421c2 --- /dev/null +++ b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.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.web.WebAppConfiguration; + +import com.baeldung.springdispatcherservlet.configuration.AppConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-drools/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-drools/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..68325682e5 --- /dev/null +++ b/spring-drools/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +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.spring.drools.service.TaxiFareConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TaxiFareConfiguration.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-ejb/ejb-beans/pom.xml b/spring-ejb/ejb-beans/pom.xml index 7a569ae4fb..76c0afadee 100644 --- a/spring-ejb/ejb-beans/pom.xml +++ b/spring-ejb/ejb-beans/pom.xml @@ -2,13 +2,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.singletonsession - singleton-ejb-bean + ejb-beans 1.0.0-SNAPSHOT - EJB Singleton Session Bean + EJB Beans com.baeldung.spring.ejb - ejb-for-spring + spring-ejb 1.0.1 diff --git a/spring-ejb/ejb-remote-for-spring/pom.xml b/spring-ejb/ejb-remote-for-spring/pom.xml index 5f4869968f..21256fa801 100755 --- a/spring-ejb/ejb-remote-for-spring/pom.xml +++ b/spring-ejb/ejb-remote-for-spring/pom.xml @@ -7,7 +7,7 @@ com.baeldung.spring.ejb - ejb-for-spring + spring-ejb 1.0.1 diff --git a/spring-ejb/pom.xml b/spring-ejb/pom.xml index c034405cc6..31cde720f9 100755 --- a/spring-ejb/pom.xml +++ b/spring-ejb/pom.xml @@ -3,10 +3,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.ejb - ejb-for-spring + spring-ejb 1.0.1 pom - ejb + spring-ejb Spring EJB Tutorial @@ -72,7 +72,6 @@ ejb-remote-for-spring - spring-ejb-client ejb-beans diff --git a/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java b/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java index d3542a2158..0a1e389113 100644 --- a/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java +++ b/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java @@ -47,4 +47,5 @@ public class SpringEjbClientApplication { public static void main(String[] args) { SpringApplication.run(SpringEjbClientApplication.class, args); } + } diff --git a/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..4d2d83646d --- /dev/null +++ b/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.springejbclient.SpringEjbClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringEjbClientApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-exceptions/src/main/resources/logback.xml b/spring-exceptions/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-exceptions/src/main/resources/logback.xml +++ b/spring-exceptions/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-exceptions/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..492673b168 --- /dev/null +++ b/spring-exceptions/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.spring.config.CoreConfig; +import org.baeldung.spring.config.MvcConfig; +import org.baeldung.spring.config.PersistenceConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { CoreConfig.class, MvcConfig.class, PersistenceConfig.class}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-freemarker/pom.xml b/spring-freemarker/pom.xml index 9c694256f3..4ff57e27f0 100644 --- a/spring-freemarker/pom.xml +++ b/spring-freemarker/pom.xml @@ -1,8 +1,8 @@ 4.0.0 - com.freemarker.example - spring4-freemarker-example + com.baeldung.freemarker + spring-freemarker war 1.0-SNAPSHOT Spring Freemarker Example @@ -44,14 +44,21 @@ freemarker ${freemarker.version} + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + - 4.3.4.RELEASE - 2.3.23 + 5.0.8.RELEASE + 2.3.28 3.1.0 false - \ No newline at end of file + diff --git a/spring-freemarker/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-freemarker/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ab0e6e8f49 --- /dev/null +++ b/spring-freemarker/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.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.web.WebAppConfiguration; + +import com.baeldung.freemarker.config.SpringWebConfig; +import com.baeldung.freemarker.config.WebConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringWebConfig.class, WebConfiguration.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java similarity index 97% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java rename to spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java index 91ca6dbfe9..dbefba5ba5 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java @@ -7,7 +7,7 @@ import java.io.File; import org.junit.Test; import org.springframework.context.support.GenericGroovyApplicationContext; -public class GroovyConfigurationTest { +public class GroovyConfigurationUnitTest { private static final String FILE_NAME = "GroovyBeanConfig.groovy"; private static final String FILE_PATH = "src/main/java/com/baeldug/groovyconfig/"; diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java similarity index 93% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java rename to spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java index 2d9b1000ff..c1e16f1b62 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java @@ -5,7 +5,7 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -public class JavaConfigurationTest { +public class JavaConfigurationUnitTest { @Test public void whenJavaConfig_thenCorrectPerson() { diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java similarity index 94% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java rename to spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java index 3ee724207c..b8d341ee39 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class XmlConfigurationTest { +public class XmlConfigurationUnitTest { @Test public void whenXmlConfig_thenCorrectPerson() { diff --git a/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppTest.java b/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java similarity index 82% rename from spring-groovy/src/test/java/com/baeldug/spring_groovy/AppTest.java rename to spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java index 19eefb6c0f..3d8fa3e2d8 100644 --- a/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppTest.java +++ b/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java @@ -7,7 +7,7 @@ import junit.framework.TestSuite; /** * Unit test for simple App. */ -public class AppTest +public class AppUnitTest extends TestCase { /** @@ -15,7 +15,7 @@ public class AppTest * * @param testName name of the test case */ - public AppTest( String testName ) + public AppUnitTest( String testName ) { super( testName ); } @@ -25,7 +25,7 @@ public class AppTest */ public static Test suite() { - return new TestSuite( AppTest.class ); + return new TestSuite( AppUnitTest.class ); } /** diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index 88ee7fadd3..b15b7278f4 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -11,7 +11,6 @@ - [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) - [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) -- [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) - [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) - [Guide to @Immutable Annotation in Hibernate](http://www.baeldung.com/hibernate-immutable) - [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java deleted file mode 100644 index 83e3c2f9a5..0000000000 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java +++ /dev/null @@ -1,251 +0,0 @@ -/** - * ApplicationViewer is the class that starts the application - * First it creates the session object and then creates the - * criteria query. - * - * @author Pritam Banerjee - * @version 1.0 - * @since 07/20/2016 - */ - -package com.baeldung.hibernate.criteria.view; - -import java.util.List; - -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.LogicalExpression; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Restrictions; - -import com.baeldung.hibernate.criteria.model.Item; -import com.baeldung.hibernate.criteria.util.HibernateUtil; - -public class ApplicationView { - - // default Constructor - public ApplicationView() { - - } - - public boolean checkIfCriteriaTimeLower() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - Transaction tx = null; - - // calculate the time taken by criteria - final long startTimeCriteria = System.nanoTime(); - cr.add(Restrictions.like("itemName", "%item One%")); - final List results = cr.list(); - final long endTimeCriteria = System.nanoTime(); - final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; - - // calculate the time taken by HQL - final long startTimeHQL = System.nanoTime(); - tx = session.beginTransaction(); - final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); - final long endTimeHQL = System.nanoTime(); - final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; - - if (durationCriteria > durationHQL) { - return false; - } else { - return true; - } - } - - // To get items having price more than 1000 - public String[] greaterThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.gt("itemPrice", 1000)); - final List greaterThanItemsList = cr.list(); - final String greaterThanItems[] = new String[greaterThanItemsList.size()]; - for (int i = 0; i < greaterThanItemsList.size(); i++) { - greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); - } - session.close(); - return greaterThanItems; - } - - // To get items having price less than 1000 - public String[] lessThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.lt("itemPrice", 1000)); - final List lessThanItemsList = cr.list(); - final String lessThanItems[] = new String[lessThanItemsList.size()]; - for (int i = 0; i < lessThanItemsList.size(); i++) { - lessThanItems[i] = lessThanItemsList.get(i).getItemName(); - } - session.close(); - return lessThanItems; - } - - // To get items whose Name start with Chair - public String[] likeCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.like("itemName", "%chair%")); - final List likeItemsList = cr.list(); - final String likeItems[] = new String[likeItemsList.size()]; - for (int i = 0; i < likeItemsList.size(); i++) { - likeItems[i] = likeItemsList.get(i).getItemName(); - } - session.close(); - return likeItems; - } - - // Case sensitive search - public String[] likeCaseCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.ilike("itemName", "%Chair%")); - final List ilikeItemsList = cr.list(); - final String ilikeItems[] = new String[ilikeItemsList.size()]; - for (int i = 0; i < ilikeItemsList.size(); i++) { - ilikeItems[i] = ilikeItemsList.get(i).getItemName(); - } - session.close(); - return ilikeItems; - } - - // To get records having itemPrice in between 100 and 200 - public String[] betweenCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - // To get items having price more than 1000 - cr.add(Restrictions.between("itemPrice", 100, 200)); - final List betweenItemsList = cr.list(); - final String betweenItems[] = new String[betweenItemsList.size()]; - for (int i = 0; i < betweenItemsList.size(); i++) { - betweenItems[i] = betweenItemsList.get(i).getItemName(); - } - session.close(); - return betweenItems; - } - - // To check if the given property is null - public String[] nullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - final List nullItemsList = cr.list(); - final String nullDescItems[] = new String[nullItemsList.size()]; - for (int i = 0; i < nullItemsList.size(); i++) { - nullDescItems[i] = nullItemsList.get(i).getItemName(); - } - session.close(); - return nullDescItems; - } - - // To check if the given property is not null - public String[] notNullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNotNull("itemDescription")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } - - // Adding more than one expression in one cr - public String[] twoCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - cr.add(Restrictions.like("itemName", "chair%")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } - - // To get items matching with the above defined conditions joined - // with Logical AND - public String[] andLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); - cr.add(andExample); - final List andItemsList = cr.list(); - final String andItems[] = new String[andItemsList.size()]; - for (int i = 0; i < andItemsList.size(); i++) { - andItems[i] = andItemsList.get(i).getItemName(); - } - session.close(); - return andItems; - } - - // To get items matching with the above defined conditions joined - // with Logical OR - public String[] orLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); - cr.add(orExample); - final List orItemsList = cr.list(); - final String orItems[] = new String[orItemsList.size()]; - for (int i = 0; i < orItemsList.size(); i++) { - orItems[i] = orItemsList.get(i).getItemName(); - } - session.close(); - return orItems; - } - - // Sorting example - public String[] sortingCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.addOrder(Order.asc("itemName")); - cr.addOrder(Order.desc("itemPrice")).list(); - final List sortedItemsList = cr.list(); - final String sortedItems[] = new String[sortedItemsList.size()]; - for (int i = 0; i < sortedItemsList.size(); i++) { - sortedItems[i] = sortedItemsList.get(i).getItemName(); - } - session.close(); - return sortedItems; - } - - // Set projections Row Count - public Long[] projectionRowCount() { - final Session session = HibernateUtil.getHibernateSession(); - final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).list(); - final Long projectedRowCount[] = new Long[itemProjected.size()]; - for (int i = 0; i < itemProjected.size(); i++) { - projectedRowCount[i] = itemProjected.get(i); - } - session.close(); - return projectedRowCount; - } - - // Set projections average of itemPrice - public Double[] projectionAverage() { - final Session session = HibernateUtil.getHibernateSession(); - final List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); - - final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; - for (int i = 0; i < avgItemPriceList.size(); i++) { - avgItemPrice[i] = (Double) avgItemPriceList.get(i); - } - session.close(); - return avgItemPrice; - } - -} diff --git a/spring-hibernate4/src/main/resources/criteria.cfg.xml b/spring-hibernate4/src/main/resources/criteria.cfg.xml deleted file mode 100644 index a39a32e151..0000000000 --- a/spring-hibernate4/src/main/resources/criteria.cfg.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - com.mysql.jdbc.Driver - jdbc:mysql://localhost:3306/test - root - iamtheking - org.hibernate.dialect.MySQLDialect - true - - - \ No newline at end of file diff --git a/spring-hibernate4/src/main/resources/criteria_create_queries.sql b/spring-hibernate4/src/main/resources/criteria_create_queries.sql deleted file mode 100644 index 3a627dd38c..0000000000 --- a/spring-hibernate4/src/main/resources/criteria_create_queries.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TABLE `item` ( - `ITEM_ID` int(11) NOT NULL AUTO_INCREMENT, - `ITEM_DESC` varchar(100) DEFAULT NULL, - `ITEM_PRICE` int(11) NOT NULL, - `ITEM_NAME` varchar(255) NOT NULL, - PRIMARY KEY (`ITEM_ID`) -) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1; diff --git a/spring-hibernate4/src/main/resources/logback.xml b/spring-hibernate4/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-hibernate4/src/main/resources/logback.xml +++ b/spring-hibernate4/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-hibernate4/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-hibernate4/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..af4618d0f3 --- /dev/null +++ b/spring-hibernate4/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.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 com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-integration/README.md b/spring-integration/README.md index d782862901..e116f934c8 100644 --- a/spring-integration/README.md +++ b/spring-integration/README.md @@ -1,6 +1,7 @@ ### Relevant Articles: - [Introduction to Spring Integration](http://www.baeldung.com/spring-integration) - [Security In Spring Integration](http://www.baeldung.com/spring-integration-security) +- [Spring Integration Java DSL](https://www.baeldung.com/spring-integration-java-dsl) ### Running the Sample Executing the `mvn exec:java` maven command (either from the command line or from an IDE) will start up the application. Follow the command prompt for further instructions. diff --git a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java new file mode 100644 index 0000000000..7e91345f04 --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java @@ -0,0 +1,146 @@ +package com.baeldung.dsl; + +import java.io.File; +import java.util.Scanner; +import java.util.concurrent.TimeUnit; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.integration.annotation.IntegrationComponentScan; +import org.springframework.integration.channel.PriorityChannel; +import org.springframework.integration.config.EnableIntegration; +import org.springframework.integration.core.GenericSelector; +import org.springframework.integration.core.MessageSource; +import org.springframework.integration.dsl.IntegrationFlow; +import org.springframework.integration.dsl.IntegrationFlows; +import org.springframework.integration.dsl.Pollers; +import org.springframework.integration.file.FileReadingMessageSource; +import org.springframework.integration.file.FileWritingMessageHandler; +import org.springframework.messaging.MessageHandler; + +/** + * JavaDSLFileCopyConfig contains various Integration Flows created from various spring integration components. + * Activate only one flow at a time by un-commenting @Bean annotation from IntegrationFlow beans. + *

    + * Different flows are :
    + * - {@link #fileMover()} - default app - activated
    + * - {@link #fileMoverWithLambda()} - app with file writing expressions as lambda
    + * - {@link #fileMoverWithPriorityChannel()} - app with priority channel
    + * - {@link #fileReader()}, {@link #fileWriter()}, {@link #anotherFileWriter()} - app with bridge + */ +@Configuration +@EnableIntegration +@IntegrationComponentScan +public class JavaDSLFileCopyConfig { + + public static final String INPUT_DIR = "source"; + public static final String OUTPUT_DIR = "target"; + public static final String OUTPUT_DIR2 = "target2"; + + @Bean + public MessageSource sourceDirectory() { + FileReadingMessageSource messageSource = new FileReadingMessageSource(); + messageSource.setDirectory(new File(INPUT_DIR)); + return messageSource; + } + + @Bean + public GenericSelector onlyJpgs() { + return new GenericSelector() { + + @Override + public boolean accept(File source) { + return source.getName() + .endsWith(".jpg"); + } + }; + } + + @Bean + public MessageHandler targetDirectory() { + FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR)); + handler.setExpectReply(false); // end of pipeline, reply not needed + return handler; + } + + @Bean + public IntegrationFlow fileMover() { + return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) + .filter(onlyJpgs()) + .handle(targetDirectory()) + .get(); + } + + // @Bean + public IntegrationFlow fileMoverWithLambda() { + return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) + .filter(message -> ((File) message).getName() + .endsWith(".jpg")) + .handle(targetDirectory()) + .get(); + } + + @Bean + public PriorityChannel alphabetically() { + return new PriorityChannel(1000, (left, right) -> ((File) left.getPayload()).getName() + .compareTo(((File) right.getPayload()).getName())); + } + + // @Bean + public IntegrationFlow fileMoverWithPriorityChannel() { + return IntegrationFlows.from(sourceDirectory()) + .filter(onlyJpgs()) + .channel("alphabetically") + .handle(targetDirectory()) + .get(); + } + + @Bean + public MessageHandler anotherTargetDirectory() { + FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR2)); + handler.setExpectReply(false); // end of pipeline, reply not needed + return handler; + } + + // @Bean + public IntegrationFlow fileReader() { + return IntegrationFlows.from(sourceDirectory()) + .filter(onlyJpgs()) + .channel("holdingTank") + .get(); + } + + // @Bean + public IntegrationFlow fileWriter() { + return IntegrationFlows.from("holdingTank") + .bridge(e -> e.poller(Pollers.fixedRate(1, TimeUnit.SECONDS, 20))) + .handle(targetDirectory()) + .get(); + } + + // @Bean + public IntegrationFlow anotherFileWriter() { + return IntegrationFlows.from("holdingTank") + .bridge(e -> e.poller(Pollers.fixedRate(2, TimeUnit.SECONDS, 10))) + .handle(anotherTargetDirectory()) + .get(); + } + + public static void main(final String... args) { + final AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaDSLFileCopyConfig.class); + context.registerShutdownHook(); + final Scanner scanner = new Scanner(System.in); + System.out.print("Please enter a string and press : "); + while (true) { + final String input = scanner.nextLine(); + if ("q".equals(input.trim())) { + context.close(); + scanner.close(); + break; + } + } + System.exit(0); + } +} diff --git a/spring-integration/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-integration/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..92e80a0903 --- /dev/null +++ b/spring-integration/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,21 @@ +package org.baeldung; + +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.si.security.MessageConsumer; +import com.baeldung.si.security.SecuredDirectChannel; +import com.baeldung.si.security.SecurityConfig; +import com.baeldung.si.security.SecurityPubSubChannel; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SecurityConfig.class, SecuredDirectChannel.class, SecurityPubSubChannel.class, + MessageConsumer.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-integration/src/test/resources/logback-test.xml b/spring-integration/src/test/resources/logback-test.xml index a807be0ca2..8f1be4eb7a 100644 --- a/spring-integration/src/test/resources/logback-test.xml +++ b/spring-integration/src/test/resources/logback-test.xml @@ -1,5 +1,15 @@ - - + + + # Pattern of log message for console appender + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8eb1589de7 --- /dev/null +++ b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.SpringJenkinsPipelineApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringJenkinsPipelineApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jersey/README.md b/spring-jersey/README.md index 8b2eecc0e1..37928620d3 100644 --- a/spring-jersey/README.md +++ b/spring-jersey/README.md @@ -3,3 +3,4 @@ ## REST API with Jersey & Spring Example Project - [REST API with Jersey and Spring](http://www.baeldung.com/jersey-rest-api-with-spring) - [JAX-RS Client with Jersey](http://www.baeldung.com/jersey-jax-rs-client) +- [Reactive JAX-RS Client API](https://www.baeldung.com/jax-rs-reactive-client) diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 22adf265b1..872835177d 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -76,6 +76,57 @@ test + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey.version} + + + org.glassfish.jersey.ext.rx + jersey-rx-client-rxjava + ${jersey.version} + + + org.glassfish.jersey.ext.rx + jersey-rx-client-rxjava2 + ${jersey.version} + + + com.github.tomakehurst + wiremock + 1.58 + test + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + 2.6.0 + + + com.fasterxml.jackson.core + jackson-databind + 2.6.0 + + + org.slf4j + slf4j-jdk14 + 1.7.25 + + + org.assertj + assertj-core + 3.10.0 + test + + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + + @@ -170,7 +221,7 @@ - 2.26 + 2.27 3.2.0 1.6.1 4.4.9 diff --git a/spring-jersey/src/main/resources/logback.xml b/spring-jersey/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-jersey/src/main/resources/logback.xml +++ b/spring-jersey/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java b/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java new file mode 100644 index 0000000000..990279a481 --- /dev/null +++ b/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java @@ -0,0 +1,272 @@ +package com.baeldung.clientrx; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.assertj.core.api.Assertions.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.InvocationCallback; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; + +import org.glassfish.jersey.client.rx.rxjava.RxObservableInvoker; +import org.glassfish.jersey.client.rx.rxjava.RxObservableInvokerProvider; +import org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvoker; +import org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvokerProvider; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; + +import io.reactivex.Flowable; +import rx.Observable; + +/** + * + * @author baeldung + */ +public class ClientOrchestrationIntegrationTest { + + private Client client = ClientBuilder.newClient(); + + private WebTarget userIdService = client.target("http://localhost:8080/id-service/ids"); + private WebTarget nameService = client.target("http://localhost:8080/name-service/users/{userId}/name"); + private WebTarget hashService = client.target("http://localhost:8080/hash-service/{rawValue}"); + + private Logger logger = LoggerFactory.getLogger(ClientOrchestrationIntegrationTest.class); + + private String expectedUserIds = "[1,2,3,4,5,6]"; + + private List expectedNames = Arrays.asList("n/a", "Thor", "Hulk", "BlackWidow", "BlackPanther", "TheTick", "Hawkeye"); + + private List expectedHashValues = Arrays.asList("roht1", "kluh2", "WodiwKcalb3", "RehtnapKclab4", "kciteht5", "eyekwah6"); + + @Rule + public WireMockRule wireMockServer = new WireMockRule(); + + @Before + public void setup() { + + stubFor(get(urlEqualTo("/id-service/ids")).willReturn(aResponse().withBody(expectedUserIds).withHeader("Content-Type", "application/json"))); + + stubFor(get(urlEqualTo("/name-service/users/1/name")).willReturn(aResponse().withBody(expectedNames.get(1)))); + stubFor(get(urlEqualTo("/name-service/users/2/name")).willReturn(aResponse().withBody(expectedNames.get(2)))); + stubFor(get(urlEqualTo("/name-service/users/3/name")).willReturn(aResponse().withBody(expectedNames.get(3)))); + stubFor(get(urlEqualTo("/name-service/users/4/name")).willReturn(aResponse().withBody(expectedNames.get(4)))); + stubFor(get(urlEqualTo("/name-service/users/5/name")).willReturn(aResponse().withBody(expectedNames.get(5)))); + stubFor(get(urlEqualTo("/name-service/users/6/name")).willReturn(aResponse().withBody(expectedNames.get(6)))); + + stubFor(get(urlEqualTo("/hash-service/Thor1")).willReturn(aResponse().withBody(expectedHashValues.get(0)))); + stubFor(get(urlEqualTo("/hash-service/Hulk2")).willReturn(aResponse().withBody(expectedHashValues.get(1)))); + stubFor(get(urlEqualTo("/hash-service/BlackWidow3")).willReturn(aResponse().withBody(expectedHashValues.get(2)))); + stubFor(get(urlEqualTo("/hash-service/BlackPanther4")).willReturn(aResponse().withBody(expectedHashValues.get(3)))); + stubFor(get(urlEqualTo("/hash-service/TheTick5")).willReturn(aResponse().withBody(expectedHashValues.get(4)))); + stubFor(get(urlEqualTo("/hash-service/Hawkeye6")).willReturn(aResponse().withBody(expectedHashValues.get(5)))); + + } + + @Test + public void callBackOrchestrate() throws InterruptedException { + List receivedHashValues = new ArrayList<>(); + + final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls + + userIdService.request().accept(MediaType.APPLICATION_JSON).async().get(new InvocationCallback>() { + @Override + public void completed(List employeeIds) { + logger.info("[CallbackExample] id-service result: {}", employeeIds); + employeeIds.forEach((id) -> { + // for each employee ID, get the name + nameService.resolveTemplate("userId", id).request().async().get(new InvocationCallback() { + + @Override + public void completed(String response) { + logger.info("[CallbackExample] name-service result: {}", response); + + hashService.resolveTemplate("rawValue", response + id).request().async().get(new InvocationCallback() { + @Override + public void completed(String response) { + logger.info("[CallbackExample] hash-service result: {}", response); + receivedHashValues.add(response); + completionTracker.countDown(); + } + + @Override + public void failed(Throwable throwable) { + logger.warn("[CallbackExample] An error has occurred in the hashing request step!", throwable); + } + }); + } + + @Override + public void failed(Throwable throwable) { + logger.warn("[CallbackExample] An error has occurred in the username request step!", throwable); + } + }); + }); + + } + + @Override + public void failed(Throwable throwable) { + logger.warn("[CallbackExample] An error has occurred in the userId request step!", throwable); + } + }); + + // wait for async calls to complete + try { + // wait for inner requests to complete in 10 seconds + if (!completionTracker.await(10, TimeUnit.SECONDS)) { + logger.warn("[CallbackExample] Some requests didn't complete within the timeout"); + } + } catch (InterruptedException e) { + logger.error("Interrupted!", e); + } + + assertThat(receivedHashValues).containsAll(expectedHashValues); + } + + @Test + public void rxOrchestrate() throws InterruptedException { + List receivedHashValues = new ArrayList<>(); + + final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls + + CompletionStage> userIdStage = userIdService.request().accept(MediaType.APPLICATION_JSON).rx().get(new GenericType>() { + }).exceptionally((throwable) -> { + logger.warn("[CompletionStageExample] An error has occurred"); + return null; + }); + + userIdStage.thenAcceptAsync(employeeIds -> { + logger.info("[CompletionStageExample] id-service result: {}", employeeIds); + employeeIds.forEach((Long id) -> { + CompletableFuture completable = nameService.resolveTemplate("userId", id).request().rx().get(String.class).toCompletableFuture(); + + completable.thenAccept((String userName) -> { + logger.info("[CompletionStageExample] name-service result: {}", userName); + hashService.resolveTemplate("rawValue", userName + id).request().rx().get(String.class).toCompletableFuture().thenAcceptAsync(hashValue -> { + logger.info("[CompletionStageExample] hash-service result: {}", hashValue); + receivedHashValues.add(hashValue); + completionTracker.countDown(); + }).exceptionally((throwable) -> { + logger.warn("[CompletionStageExample] Hash computation failed for {}", id); + completionTracker.countDown(); + return null; + }); + + }); + + }); + }); + + // wait for async calls to complete + try { + // wait for inner requests to complete in 10 seconds + if (!completionTracker.await(10, TimeUnit.SECONDS)) { + logger.warn("[CallbackExample] Some requests didn't complete within the timeout"); + } + } catch (InterruptedException e) { + logger.error("Interrupted!", e); + } + + assertThat(receivedHashValues).containsAll(expectedHashValues); + } + + @Test + public void observableJavaOrchestrate() throws InterruptedException { + List receivedHashValues = new ArrayList<>(); + + final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls + + Observable> observableUserIdService = userIdService.register(RxObservableInvokerProvider.class).request().accept(MediaType.APPLICATION_JSON).rx(RxObservableInvoker.class).get(new GenericType>() { + }).asObservable(); + + observableUserIdService.subscribe((List employeeIds) -> { + logger.info("[ObservableExample] id-service result: {}", employeeIds); + Observable.from(employeeIds).subscribe(id -> nameService.register(RxObservableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the name for the given + // userId + .doOnError((throwable) -> { + logger.warn("[ObservableExample] An error has occurred in the username request step {}", throwable.getMessage()); + }).subscribe(userName -> { + logger.info("[ObservableExample] name-service result: {}", userName); + hashService.register(RxObservableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the hash value for + // userId+username + .doOnError((throwable) -> { + logger.warn("[ObservableExample] An error has occurred in the hashing request step {}", throwable.getMessage()); + }).subscribe(hashValue -> { + logger.info("[ObservableExample] hash-service result: {}", hashValue); + receivedHashValues.add(hashValue); + completionTracker.countDown(); + }); + })); + }); + + // wait for async calls to complete + try { + // wait for inner requests to complete in 10 seconds + if (!completionTracker.await(10, TimeUnit.SECONDS)) { + logger.warn("[CallbackExample] Some requests didn't complete within the timeout"); + } + } catch (InterruptedException e) { + logger.error("Interrupted!", e); + } + + assertThat(receivedHashValues).containsAll(expectedHashValues); + } + + @Test + public void flowableJavaOrchestrate() throws InterruptedException { + List receivedHashValues = new ArrayList<>(); + + final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls + + Flowable> userIdFlowable = userIdService.register(RxFlowableInvokerProvider.class).request().rx(RxFlowableInvoker.class).get(new GenericType>() { + }); + + userIdFlowable.subscribe((List employeeIds) -> { + logger.info("[FlowableExample] id-service result: {}", employeeIds); + Flowable.fromIterable(employeeIds).subscribe(id -> { + nameService.register(RxFlowableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the name for the given userId + .doOnError((throwable) -> { + logger.warn("[FlowableExample] An error has occurred in the username request step {}", throwable.getMessage()); + }).subscribe(userName -> { + logger.info("[FlowableExample] name-service result: {}", userName); + hashService.register(RxFlowableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the hash value for userId+username + .doOnError((throwable) -> { + logger.warn(" [FlowableExample] An error has occurred in the hashing request step!", throwable); + }).subscribe(hashValue -> { + logger.info("[FlowableExample] hash-service result: {}", hashValue); + receivedHashValues.add(hashValue); + completionTracker.countDown(); + }); + }); + }); + }); + + // wait for async calls to complete + try { + // wait for inner requests to complete in 10 seconds + if (!completionTracker.await(10, TimeUnit.SECONDS)) { + logger.warn("[CallbackExample] Some requests didn't complete within the timeout"); + } + } catch (InterruptedException e) { + logger.error("Interrupted!", e); + } + + assertThat(receivedHashValues).containsAll(expectedHashValues); + } + +} diff --git a/spring-jersey/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-jersey/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..21f180854c --- /dev/null +++ b/spring-jersey/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +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.server.config.RestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestConfig.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jinq/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-jinq/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ccf774330f --- /dev/null +++ b/spring-jinq/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.jinq.JinqApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = JinqApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index 949a78b2a1..814875f77b 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -33,6 +33,14 @@ activemq-all ${activemq.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-jms/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-jms/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e13809f571 --- /dev/null +++ b/spring-jms/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:EmbeddedActiveMQ.xml"}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index e1c13ef774..744ae34cc8 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -2,8 +2,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-jooq - 0.0.1-SNAPSHOT - + parent-boot-1 com.baeldung @@ -54,11 +53,6 @@ spring-test test - - org.springframework.boot - spring-boot-starter-test - - diff --git a/spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..40bf86c76f --- /dev/null +++ b/spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.kafka.KafkaApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KafkaApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-katharsis/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-katharsis/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..48081903b6 --- /dev/null +++ b/spring-katharsis/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-ldap/src/main/resources/logback.xml b/spring-ldap/src/main/resources/logback.xml index 32b78577ee..7bd5154680 100644 --- a/spring-ldap/src/main/resources/logback.xml +++ b/spring-ldap/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9c233e6562 --- /dev/null +++ b/spring-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +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.ldap.javaconfig.AppConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mobile/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mobile/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7f906bdbcd --- /dev/null +++ b/spring-mobile/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index 6aeaa9a1e8..d1fa7f410e 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -24,13 +24,13 @@ org.mockito - mockito-all + mockito-core ${mockito.version} - 1.10.19 + 2.21.0 diff --git a/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java b/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java index 05cb43e4df..51db07fde7 100644 --- a/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java +++ b/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java @@ -3,7 +3,7 @@ package com.baeldung.domain.util; import com.baeldung.domain.model.Message; import org.mockito.ArgumentMatcher; -public class MessageMatcher extends ArgumentMatcher { +public class MessageMatcher implements ArgumentMatcher { private Message left; @@ -12,16 +12,11 @@ public class MessageMatcher extends ArgumentMatcher { } @Override - public boolean matches(Object object) { - if (object instanceof Message) { - Message right = (Message) object; - return left.getFrom().equals(right.getFrom()) && - left.getTo().equals(right.getTo()) && - left.getText().equals(right.getText()) && - right.getDate() != null && - right.getId() != null; - } - - return false; + public boolean matches(Message right) { + return left.getFrom().equals(right.getFrom()) && + left.getTo().equals(right.getTo()) && + left.getText().equals(right.getText()) && + right.getDate() != null && + right.getId() != null; } } \ No newline at end of file diff --git a/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java b/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java index f30af140af..aeec57d136 100644 --- a/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java +++ b/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java @@ -1,17 +1,18 @@ package com.baeldung.app.rest; -import com.baeldung.app.api.Flower; -import com.baeldung.domain.service.FlowerService; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.when; +import com.baeldung.app.api.Flower; +import com.baeldung.domain.service.FlowerService; @RunWith(MockitoJUnitRunner.class) public class FlowerControllerUnitTest { diff --git a/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java b/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java index e303c85caf..15e91d86b5 100644 --- a/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java +++ b/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java @@ -1,18 +1,19 @@ package com.baeldung.app.rest; +import static org.mockito.Mockito.times; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + import com.baeldung.app.api.MessageApi; import com.baeldung.domain.model.Message; import com.baeldung.domain.service.MessageService; import com.baeldung.domain.util.MessageMatcher; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.mockito.Mockito.times; @RunWith(MockitoJUnitRunner.class) public class MessageControllerUnitTest { @@ -37,6 +38,6 @@ public class MessageControllerUnitTest { message.setTo("you"); message.setText("Hello, you!"); - Mockito.verify(messageService, times(1)).deliverMessage(Matchers.argThat(new MessageMatcher(message))); + Mockito.verify(messageService, times(1)).deliverMessage(ArgumentMatchers.argThat(new MessageMatcher(message))); } } diff --git a/spring-mockito/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mockito/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7ce9f70302 --- /dev/null +++ b/spring-mockito/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.MocksApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MocksApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mustache/pom.xml b/spring-mustache/pom.xml index 4e7a1ba5a3..9e4c528ee0 100644 --- a/spring-mustache/pom.xml +++ b/spring-mustache/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-mustache - 0.0.1-SNAPSHOT jar spring-mustache Demo project for Spring Boot @@ -50,9 +48,6 @@ - UTF-8 - UTF-8 - 1.8 3.3.7 0.8 diff --git a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java similarity index 94% rename from spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java rename to spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java index 9138dfe92b..1eecf58986 100644 --- a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java +++ b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class SpringMustacheApplicationTests { +public class SpringMustacheApplicationIntegrationTest { @Autowired private TestRestTemplate restTemplate; diff --git a/spring-mvc-forms-jsp/pom.xml b/spring-mvc-forms-jsp/pom.xml index a51f76f9e1..5536314086 100644 --- a/spring-mvc-forms-jsp/pom.xml +++ b/spring-mvc-forms-jsp/pom.xml @@ -63,6 +63,12 @@ jackson-databind ${jackson-databind.version} + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + @@ -83,7 +89,6 @@ src/main/webapp spring-mvc-forms false - ${deploy-path} @@ -99,7 +104,6 @@ 2.3.1 3.1.0 6.0.10.Final - server default deploy directory 1.3.3 5.2.5.Final 6.0.6 diff --git a/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java index b8b36df84e..2b2844e0de 100644 --- a/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java +++ b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java @@ -14,7 +14,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.baeldung.springmvcforms", "com.baeldung.jstl"}) -class ApplicationConfiguration implements WebMvcConfigurer { +public class ApplicationConfiguration implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c1e9b71550 --- /dev/null +++ b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import com.baeldung.springmvcforms.configuration.ApplicationConfiguration; + +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.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ApplicationConfiguration.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-thymeleaf/pom.xml b/spring-mvc-forms-thymeleaf/pom.xml index 07c49766ee..504ad1dcb2 100644 --- a/spring-mvc-forms-thymeleaf/pom.xml +++ b/spring-mvc-forms-thymeleaf/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-mvc-forms-thymeleaf - 0.0.1-SNAPSHOT jar spring-mvc-forms-thymeleaf spring forms examples using thymeleaf @@ -40,36 +38,8 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LiveTest.java - - - - - - - UTF-8 - UTF-8 3.0.9.RELEASE com.baeldung.sessionattrs.SessionAttrsApplication - diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextIntegrationTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..da87a6830a --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung.listbindingexample; + +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.listbindingexample.ListBindingApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {ListBindingApplication.class}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextIntegrationTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e6b0dbf98c --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung.sessionattrs; + +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.sessionattrs.SessionAttrsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SessionAttrsApplication.class}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index c4a0e3579c..3a580202cf 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -28,10 +28,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) -- [Spring Boot Annotations](http://www.baeldung.com/spring-boot-annotations) -- [Spring Scheduling Annotations](http://www.baeldung.com/spring-scheduling-annotations) -- [Spring Web Annotations](http://www.baeldung.com/spring-mvc-annotations) -- [Spring Core Annotations](http://www.baeldung.com/spring-core-annotations) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) -- [Display RSS Feed with Spring MVC](http://www.baeldung.com/spring-mvc-rss-feed) +- [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) +- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 068824eba0..9d3e0ca1b2 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -5,70 +5,54 @@ spring-mvc-java 0.1-SNAPSHOT spring-mvc-java + war - parent-boot-2 + parent-spring-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-spring-5 - - - org.springframework.boot - spring-boot-starter-thymeleaf + + org.springframework + spring-webmvc + ${spring.version} - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-devtools - - - org.springframework.boot - spring-boot-test - test - - - org.springframework.boot - spring-boot-starter-aop - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-websocket - - - - - com.fasterxml.jackson.core - jackson-databind - - - javax.servlet javax.servlet-api + 4.0.1 + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.3 javax.servlet jstl + ${jstl.version} + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind.version} org.aspectj aspectjrt + 1.9.1 org.aspectj aspectjweaver + 1.9.1 @@ -80,6 +64,7 @@ net.sourceforge.htmlunit htmlunit + 2.32 commons-logging @@ -104,10 +89,12 @@ com.jayway.jsonpath json-path test + 2.4.0 org.springframework spring-test + ${spring.version} test @@ -120,34 +107,29 @@ - org.hibernate + org.hibernate.validator hibernate-validator ${hibernate-validator.version} - - javax.el - javax.el-api - ${javax.el.version} - - - org.glassfish.web - javax.el - ${javax.el.version} - com.google.code.gson gson + 2.8.5 - - - - com.rometools - rome - ${rome.version} - + + org.springframework + spring-websocket + ${spring.version} + + + + org.springframework + spring-messaging + ${spring.version} + @@ -163,11 +145,13 @@ maven-resources-plugin + ${maven-resources-plugin.version} org.apache.maven.plugins maven-war-plugin + ${maven-war-plugin.version} false @@ -261,7 +245,7 @@ 3.0.9.RELEASE - 5.2.5.Final + 6.0.10.Final 5.1.40 @@ -280,23 +264,19 @@ 2.23 - 2.6 + 3.2.2 2.7 1.6.1 + 3.1.0 - 1.8.9 + 1.9.1 3.16-beta1 - - 1.10.0 - - 2.2.4 + 3.0.1-b06 - - com.baeldung.app.Application diff --git a/spring-mvc-java/src/main/java/com/baeldung/app/Application.java b/spring-mvc-java/src/main/java/com/baeldung/app/Application.java deleted file mode 100644 index 68d078de78..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/app/Application.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.app; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.ComponentScan; - -@EnableAutoConfiguration -@ComponentScan(value = {"com.baeldung.web.controller"}, resourcePattern = "**/FileUploadController.class") -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - public static void main(final String[] args) { - SpringApplication.run(Application.class, args); - } -} \ No newline at end of file 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 index 9cf6e384f1..eec12f466f 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/config/AppInitializer.java +++ b/spring-mvc-java/src/main/java/com/baeldung/config/AppInitializer.java @@ -14,13 +14,20 @@ public class AppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.setConfigLocation("org.baeldung.config"); + + context.scan("com.baeldung"); container.addListener(new ContextLoaderListener(context)); - ServletRegistration.Dynamic dispatcher = container.addServlet("java-servlet", new DispatcherServlet(context)); + ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/java-servlet/*"); + 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/ApplicationConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java deleted file mode 100644 index 261d5793dc..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.spring.web.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@EnableWebMvc -@Configuration -@ComponentScan(basePackages = { "com.baeldung.web.controller" }) -public class ApplicationConfig extends WebMvcConfigurerAdapter { - - public ApplicationConfig() { - super(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("index"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/jsp/"); - bean.setSuffix(".jsp"); - return bean; - } -} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java deleted file mode 100644 index de47f9f69e..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.baeldung.spring.web.config; - -import javax.servlet.ServletContext; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Description; -import org.springframework.context.support.ResourceBundleMessageSource; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; -import org.thymeleaf.spring4.SpringTemplateEngine; -import org.thymeleaf.spring4.view.ThymeleafViewResolver; -import org.thymeleaf.templateresolver.ServletContextTemplateResolver; - -@EnableWebMvc -@Configuration -public class ClientWebConfig implements WebMvcConfigurer { - - public ClientWebConfig() { - super(); - } - - // API - - @Autowired - private ServletContext ctx; - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - - registry.addViewController("/sample.html"); - } - - @Bean - public ViewResolver thymeleafViewResolver() { - final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(0); - return bean; - } - - @Bean - @Description("Thymeleaf template resolver serving HTML 5") - public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx); - templateResolver.setPrefix("/WEB-INF/templates/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); - return templateResolver; - } - - @Bean - @Description("Thymeleaf template engine with Spring integration") - public SpringTemplateEngine templateEngine() { - final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - return templateEngine; - } - - @Bean - @Description("Spring message resolver") - public MessageSource messageSource() { - final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setBasename("messages"); - return messageSource; - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } - -} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java deleted file mode 100644 index 498105ded1..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.spring.web.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@EnableWebMvc -@Configuration -public class ContentManagementWebConfig extends WebMvcConfigurerAdapter { - - public ContentManagementWebConfig() { - super(); - } - - // API - - @Override - public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useJaf(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", - MediaType.APPLICATION_JSON); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(0); - return bean; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java deleted file mode 100644 index 80ce22edd6..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.spring.web.config; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; -import java.util.Set; - -public class MainWebAppInitializer implements WebApplicationInitializer { - - private static final String TMP_FOLDER = "/tmp"; - private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB - - /** - * Register and configure all Servlet container components necessary to power the web application. - */ - @Override - public void onStartup(final ServletContext sc) throws ServletException { - - // Create the 'root' Spring application context - final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.scan("com.baeldung.spring.web.config"); - // root.getEnvironment().setDefaultProfiles("embedded"); - - sc.addListener(new ContextLoaderListener(root)); - - // Handles requests into the application - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext())); - appServlet.setLoadOnStartup(1); - - // final MultipartConfigElement multipartConfigElement = new - // MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE, - // MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); - // - // appServlet.setMultipartConfig(multipartConfigElement); - - final Set mappingConflicts = appServlet.addMapping("/"); - if (!mappingConflicts.isEmpty()) { - throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); - } - } - -} 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 11be08a79d..191d721dfb 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,40 +3,105 @@ 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; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Description; +import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.core.io.ClassPathResource; 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.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.ResourceBundleViewResolver; import org.springframework.web.servlet.view.XmlViewResolver; import org.springframework.web.util.UrlPathHelper; -import com.baeldung.excel.*; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; + +import com.baeldung.excel.ExcelPOIHelper; -@Configuration @EnableWebMvc -@ComponentScan("com.baeldung.web") -public class WebConfig extends WebMvcConfigurerAdapter { +@Configuration +@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +public class WebConfig implements WebMvcConfigurer { - public WebConfig() { - super(); + @Autowired + private ServletContext ctx; + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + } + + @Bean + public ViewResolver thymeleafViewResolver() { + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; } - // @Bean - // public StandardServletMultipartResolver multipartResolver() { - // return new StandardServletMultipartResolver(); - // } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } + @Bean + @Description("Thymeleaf template resolver serving HTML 5") + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } + + @Bean + @Description("Thymeleaf template engine with Spring integration") + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + return templateEngine; + } + + @Bean + @Description("Spring message resolver") + public MessageSource messageSource() { + final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + + @Override + public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { + configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useRegisteredExtensionsOnly(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", + MediaType.APPLICATION_JSON); + } @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { @@ -45,23 +110,7 @@ public class WebConfig extends WebMvcConfigurerAdapter { return multipartResolver; } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } - - @Bean - public ViewResolver internalResourceViewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(2); - return bean; - } - + @Bean public ViewResolver xmlViewResolver() { final XmlViewResolver bean = new XmlViewResolver(); @@ -112,5 +161,4 @@ public class WebConfig extends WebMvcConfigurerAdapter { public ExcelPOIHelper excelPOIHelper() { return new ExcelPOIHelper(); } - -} +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java index 93ec13da58..0793658e90 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java @@ -2,13 +2,13 @@ package com.baeldung.spring.web.config; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; -import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker -public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { +public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(final MessageBrokerRegistry config) { diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java index 7f14380e5e..dbd52e20ba 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketSendToUserConfig.java @@ -6,9 +6,9 @@ import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.WebSocketHandler; -import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; import javax.servlet.http.HttpSession; @@ -16,7 +16,7 @@ import java.util.Map; @Configuration @EnableWebSocketMessageBroker -public class WebSocketSendToUserConfig extends AbstractWebSocketMessageBrokerConfigurer { +public class WebSocketSendToUserConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SampleController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/SampleController.java new file mode 100644 index 0000000000..c13986e005 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/SampleController.java @@ -0,0 +1,13 @@ +package com.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class SampleController { + @GetMapping("/sample") + public String showForm() { + return "sample"; + } + +} diff --git a/spring-mvc-java/src/main/resources/logback.xml b/spring-mvc-java/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-mvc-java/src/main/resources/logback.xml +++ b/spring-mvc-java/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java index b628228b7e..384bd85ec6 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java @@ -20,12 +20,12 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.spring.web.config.ApplicationConfig; +import com.baeldung.spring.web.config.WebConfig; import com.baeldung.spring.web.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = { ApplicationConfig.class, WebConfig.class }) +@ContextConfiguration(classes = { WebConfig.class, WebConfig.class }) public class GreetControllerIntegrationTest { @Autowired diff --git a/spring-mvc-java/src/test/resources/logback-test.xml b/spring-mvc-java/src/test/resources/logback-test.xml index e0721aa890..e35a9680bb 100644 --- a/spring-mvc-java/src/test/resources/logback-test.xml +++ b/spring-mvc-java/src/test/resources/logback-test.xml @@ -3,7 +3,7 @@ - %date [%thread] %-5level %logger{6} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml index 1bf66d6f31..59b60ebd3c 100644 --- a/spring-mvc-kotlin/pom.xml +++ b/spring-mvc-kotlin/pom.xml @@ -1,124 +1,83 @@ - 4.0.0 - spring-mvc-kotlin - 0.1-SNAPSHOT - spring-mvc-kotlin - war + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + spring-mvc-kotlin + spring-mvc-kotlin + war - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + parent-kotlin + com.baeldung + 1.0.0-SNAPSHOT + ../parent-kotlin + - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.thymeleaf + thymeleaf + - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - org.thymeleaf - thymeleaf - ${thymeleaf.version} - + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + + + org.hibernate + hibernate-core + + + org.hibernate + hibernate-testing + test + + + com.h2database + h2 + test + + + org.springframework + spring-test + test + + - - org.thymeleaf - thymeleaf-spring4 - ${thymeleaf.version} - - - org.hibernate - hibernate-core - ${hibernate.version} - - - org.hibernate - hibernate-testing - ${hibernate.version} - test - - - com.h2database - h2 - ${h2.version} - test - - - org.springframework - spring-test - ${spring.version} - test - - + + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + jpa + + + + + org.jetbrains.kotlin + kotlin-maven-noarg + ${kotlin.version} + + + + + - - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/test/kotlin - - - kotlin-maven-plugin - org.jetbrains.kotlin - ${kotlin.version} - - - spring - jpa - - ${java.version} - - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-maven-noarg - ${kotlin.version} - - - - - - - - 5.2.15.Final - 1.2.30 - 4.3.10.RELEASE - 3.0.7.RELEASE - 1.4.196 - + + 3.0.7.RELEASE + \ No newline at end of file diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index 64cf0a73a5..dc5adcf3cf 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung 0.1-SNAPSHOT spring-mvc-velocity @@ -94,7 +93,6 @@ - org.apache.maven.plugins maven-war-plugin @@ -103,25 +101,7 @@ false - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - - diff --git a/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3649332870 --- /dev/null +++ b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.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.web.WebAppConfiguration; + +import com.baeldung.mvc.velocity.spring.config.WebConfig; +import com.baeldung.mvc.velocity.test.config.TestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-webflow/pom.xml b/spring-mvc-webflow/pom.xml index f7070efb94..e1a279a787 100644 --- a/spring-mvc-webflow/pom.xml +++ b/spring-mvc-webflow/pom.xml @@ -52,6 +52,14 @@ log4j-over-slf4j ${org.slf4j.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-mvc-webflow/src/main/resources/logback.xml b/spring-mvc-webflow/src/main/resources/logback.xml index 1146dade63..5ce05b3361 100644 --- a/spring-mvc-webflow/src/main/resources/logback.xml +++ b/spring-mvc-webflow/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6f028c78d8 --- /dev/null +++ b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.WebFlowConfig; +import org.baeldung.spring.WebMvcConfig; +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.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {WebFlowConfig.class, WebMvcConfig.class}) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index fd33c25241..7187b5c270 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -86,6 +86,13 @@ + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java index 9752526963..22260fca70 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -1,11 +1,13 @@ package com.baeldung.spring; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @ImportResource("classpath:webMvcConfig.xml") @Configuration +@ComponentScan public class ClientWebConfig implements WebMvcConfigurer { public ClientWebConfig() { diff --git a/spring-mvc-xml/src/main/resources/logback.xml b/spring-mvc-xml/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-mvc-xml/src/main/resources/logback.xml +++ b/spring-mvc-xml/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-mvc-xml/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ec34abd367 --- /dev/null +++ b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.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.web.WebAppConfiguration; + +import com.baeldung.spring.ClientWebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ClientWebConfig.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java index 427613f23f..c1e5579103 100644 --- a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java +++ b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java @@ -31,7 +31,7 @@ public class StudentController { @RequestMapping(value = "/signup", method = RequestMethod.POST) public String signup(@Validated @ModelAttribute("student") Student student, BindingResult result, ModelMap model) { - if (studentService.getStudentByUserName(student.getUserName())) { + if (studentService.getStudentByUserName(student.getUserName()) != null) { model.addAttribute("message", "User Name exists. Try another user name"); return "signup"; } else { @@ -50,7 +50,7 @@ public class StudentController { @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(@ModelAttribute("studentLogin") StudentLogin studentLogin, BindingResult result, ModelMap model) { - boolean found = studentService.getStudentByLogin(studentLogin.getUserName(), studentLogin.getPassword()); + boolean found = studentService.getStudentByLogin(studentLogin.getUserName(), studentLogin.getPassword()) != null; if (found) { return "success"; } else { diff --git a/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..615ebd5f4a --- /dev/null +++ b/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.protobuf.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-quartz/src/main/resources/logback.xml b/spring-quartz/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-quartz/src/main/resources/logback.xml +++ b/spring-quartz/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..516cc587a7 --- /dev/null +++ b/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.springquartz.SpringQuartzApp; +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 = SpringQuartzApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-reactive-kotlin/pom.xml b/spring-reactive-kotlin/pom.xml index 8eafe9f217..bff39984e0 100644 --- a/spring-reactive-kotlin/pom.xml +++ b/spring-reactive-kotlin/pom.xml @@ -2,28 +2,17 @@ 4.0.0 - - com.baeldung - springreactivekotlin - 0.0.1-SNAPSHOT + spring-reactive-kotlin jar - - springreactivekotlin + Spring Reactive Kotlin Demo project for Spring Boot - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - UTF-8 - UTF-8 - 1.8 - 1.2.41 - + parent-kotlin + com.baeldung + 1.0.0-SNAPSHOT + ../parent-kotlin + @@ -38,15 +27,7 @@ com.fasterxml.jackson.module jackson-module-kotlin - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - - - org.jetbrains.kotlin - kotlin-reflect - - + org.springframework.boot spring-boot-starter-test @@ -60,34 +41,17 @@ - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/test/kotlin - - org.springframework.boot - spring-boot-maven-plugin - kotlin-maven-plugin org.jetbrains.kotlin + ${kotlin.version} -Xjsr305=strict - - spring - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - - diff --git a/spring-reactor/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-reactor/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7f906bdbcd --- /dev/null +++ b/spring-reactor/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index 8db51e2a16..9f05bc91d2 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -32,7 +32,7 @@ remoting-hessian-burlap remoting-amqp remoting-jms - spring-remoting-rmi + remoting-rmi \ No newline at end of file diff --git a/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml b/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml index b715327c28..98e0bc5df5 100644 --- a/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml +++ b/spring-remoting/remoting-amqp/remoting-amqp-client/pom.xml @@ -26,7 +26,7 @@ com.baeldung - api + remoting-http-api ${project.version} diff --git a/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2de3ed94d1 --- /dev/null +++ b/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.client.AmqpClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AmqpClient.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml b/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml index a456ba8d2c..7fe276f824 100644 --- a/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml +++ b/spring-remoting/remoting-amqp/remoting-amqp-server/pom.xml @@ -16,7 +16,7 @@ com.baeldung - api + remoting-http-api ${project.version} @@ -25,13 +25,13 @@ com.baeldung - spring-remoting-http-server - ${spring-remoting-http-server.version} + remoting-http-server + ${remoting-http-server.version} - 1.0-SNAPSHOT + 1.0-SNAPSHOT diff --git a/spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..5dc6d1df75 --- /dev/null +++ b/spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.server.AmqpServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AmqpServer.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-hessian-burlap/pom.xml b/spring-remoting/remoting-hessian-burlap/pom.xml index 682e460880..6cb5a51812 100644 --- a/spring-remoting/remoting-hessian-burlap/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/pom.xml @@ -2,19 +2,18 @@ - + 4.0.0 + remoting-hessian-burlap + pom + + spring-remoting com.baeldung 1.0-SNAPSHOT - pom + - server - client + remoting-hessian-burlap-server + remoting-hessian-burlap-client - 4.0.0 - - remoting-hessian-burlap - - \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/client/pom.xml b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml similarity index 95% rename from spring-remoting/remoting-hessian-burlap/client/pom.xml rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml index 1ae9b10019..f337d5e51f 100644 --- a/spring-remoting/remoting-hessian-burlap/client/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml @@ -24,7 +24,8 @@ ${project.groupId} - api + remoting-http-api + ${project.version} com.caucho diff --git a/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/BurlapClient.java similarity index 100% rename from spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/BurlapClient.java diff --git a/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/HessianClient.java similarity index 100% rename from spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/HessianClient.java diff --git a/spring-remoting/remoting-http/client/src/main/resources/logback.xml b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/resources/logback.xml similarity index 100% rename from spring-remoting/remoting-http/client/src/main/resources/logback.xml rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/resources/logback.xml diff --git a/spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java similarity index 100% rename from spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..1aec444aa0 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +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.client.BurlapClient; +import com.baeldung.client.HessianClient; + +@SpringBootTest(classes = {BurlapClient.class, HessianClient.class}) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-hessian-burlap/client/src/test/resources/application.properties b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/resources/application.properties similarity index 100% rename from spring-remoting/remoting-hessian-burlap/client/src/test/resources/application.properties rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/resources/application.properties diff --git a/spring-remoting/remoting-hessian-burlap/server/pom.xml b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml similarity index 94% rename from spring-remoting/remoting-hessian-burlap/server/pom.xml rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml index f1fed73ed8..5b6e03348f 100644 --- a/spring-remoting/remoting-hessian-burlap/server/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml @@ -14,7 +14,7 @@ com.baeldung - spring-remoting-http-server + remoting-http-server ${project.version} diff --git a/spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/java/com/baeldung/server/Server.java similarity index 100% rename from spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/java/com/baeldung/server/Server.java diff --git a/spring-remoting/remoting-http/server/src/main/resources/logback.xml b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/resources/logback.xml similarity index 100% rename from spring-remoting/remoting-http/server/src/main/resources/logback.xml rename to spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/resources/logback.xml diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f1aad1f601 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.server.Server; + +@SpringBootTest(classes = Server.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-http/pom.xml b/spring-remoting/remoting-http/pom.xml index 439f6782ba..3262736ec8 100644 --- a/spring-remoting/remoting-http/pom.xml +++ b/spring-remoting/remoting-http/pom.xml @@ -3,17 +3,19 @@ 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 + remoting-http + Parent for all modules related to HTTP Spring Remoting. + pom + com.baeldung spring-remoting 1.0-SNAPSHOT - spring-remoting-http - Parent for all modules related to HTTP Spring Remoting. - pom + - server - client - api + remoting-http-server + remoting-http-client + remoting-http-api \ No newline at end of file diff --git a/spring-remoting/remoting-http/api/pom.xml b/spring-remoting/remoting-http/remoting-http-api/pom.xml similarity index 77% rename from spring-remoting/remoting-http/api/pom.xml rename to spring-remoting/remoting-http/remoting-http-api/pom.xml index 633217f7de..579255060d 100644 --- a/spring-remoting/remoting-http/api/pom.xml +++ b/spring-remoting/remoting-http/remoting-http-api/pom.xml @@ -2,13 +2,15 @@ - - spring-remoting-http + 4.0.0 + remoting-http-api + remoting-http-api + API definition shared between client and server. + + + remoting-http com.baeldung 1.0-SNAPSHOT - 4.0.0 - api - spring-remoting-http-api - API definition shared between client and server. + \ No newline at end of file diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java b/spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/Booking.java similarity index 100% rename from spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java rename to spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/Booking.java diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/BookingException.java b/spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/BookingException.java similarity index 100% rename from spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/BookingException.java rename to spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/BookingException.java diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java b/spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/CabBookingService.java similarity index 100% rename from spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java rename to spring-remoting/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/CabBookingService.java diff --git a/spring-remoting/remoting-http/client/pom.xml b/spring-remoting/remoting-http/remoting-http-client/pom.xml similarity index 83% rename from spring-remoting/remoting-http/client/pom.xml rename to spring-remoting/remoting-http/remoting-http-client/pom.xml index 94a536fc18..9a6e98ffdd 100644 --- a/spring-remoting/remoting-http/client/pom.xml +++ b/spring-remoting/remoting-http/remoting-http-client/pom.xml @@ -3,14 +3,15 @@ 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 - + remoting-http-client + Shows how to invoke a remote service using Spring Remoting HTTP. + com.baeldung - spring-remoting-http + remoting-http 1.0-SNAPSHOT - spring-remoting-http-client - Shows how to invoke a remote service using Spring Remoting HTTP. + org.springframework.boot @@ -24,7 +25,8 @@ ${project.groupId} - api + remoting-http-api + ${project.version} \ No newline at end of file diff --git a/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Client.java b/spring-remoting/remoting-http/remoting-http-client/src/main/java/com/baeldug/client/Client.java similarity index 100% rename from spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Client.java rename to spring-remoting/remoting-http/remoting-http-client/src/main/java/com/baeldug/client/Client.java diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-client/src/main/resources/logback.xml b/spring-remoting/remoting-http/remoting-http-client/src/main/resources/logback.xml similarity index 100% rename from spring-remoting/spring-remoting-rmi/remoting-rmi-client/src/main/resources/logback.xml rename to spring-remoting/remoting-http/remoting-http-client/src/main/resources/logback.xml diff --git a/spring-remoting/remoting-http/server/pom.xml b/spring-remoting/remoting-http/remoting-http-server/pom.xml similarity index 79% rename from spring-remoting/remoting-http/server/pom.xml rename to spring-remoting/remoting-http/remoting-http-server/pom.xml index 517f4451f7..53d27a5efa 100644 --- a/spring-remoting/remoting-http/server/pom.xml +++ b/spring-remoting/remoting-http/remoting-http-server/pom.xml @@ -3,13 +3,15 @@ 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 + remoting-http-server + Shows how to expose a service using Spring Remoting HTTP. + com.baeldung - spring-remoting-http + remoting-http 1.0-SNAPSHOT - spring-remoting-http-server - Shows how to expose a service using Spring Remoting HTTP. + org.springframework.boot @@ -17,7 +19,8 @@ ${project.groupId} - api + remoting-http-api + ${project.version} \ No newline at end of file diff --git a/spring-remoting/remoting-http/server/readme.md b/spring-remoting/remoting-http/remoting-http-server/readme.md similarity index 100% rename from spring-remoting/remoting-http/server/readme.md rename to spring-remoting/remoting-http/remoting-http-server/readme.md diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java b/spring-remoting/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java similarity index 100% rename from spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java rename to spring-remoting/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/Server.java b/spring-remoting/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/Server.java similarity index 100% rename from spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/Server.java rename to spring-remoting/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/Server.java diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/resources/logback.xml b/spring-remoting/remoting-http/remoting-http-server/src/main/resources/logback.xml similarity index 100% rename from spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/resources/logback.xml rename to spring-remoting/remoting-http/remoting-http-server/src/main/resources/logback.xml diff --git a/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f1aad1f601 --- /dev/null +++ b/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.server.Server; + +@SpringBootTest(classes = Server.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-jms/remoting-jms-client/pom.xml b/spring-remoting/remoting-jms/remoting-jms-client/pom.xml index 01b7bea657..ed27282a38 100644 --- a/spring-remoting/remoting-jms/remoting-jms-client/pom.xml +++ b/spring-remoting/remoting-jms/remoting-jms-client/pom.xml @@ -28,7 +28,8 @@ com.baeldung - api + remoting-http-api + ${project.version} diff --git a/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a94e639dc8 --- /dev/null +++ b/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.client.JmsClient; + +@SpringBootTest(classes = JmsClient.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-jms/remoting-jms-server/pom.xml b/spring-remoting/remoting-jms/remoting-jms-server/pom.xml index 8feac4df57..7657267f1d 100644 --- a/spring-remoting/remoting-jms/remoting-jms-server/pom.xml +++ b/spring-remoting/remoting-jms/remoting-jms-server/pom.xml @@ -28,11 +28,7 @@ com.baeldung - api - - - com.baeldung - api + remoting-http-api ${project.version} diff --git a/spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..5c9cc5f872 --- /dev/null +++ b/spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.server.JmsServer; + +@SpringBootTest(classes = JmsServer.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/spring-remoting-rmi/pom.xml b/spring-remoting/remoting-rmi/pom.xml similarity index 88% rename from spring-remoting/spring-remoting-rmi/pom.xml rename to spring-remoting/remoting-rmi/pom.xml index 723158775f..cd15a6ec60 100644 --- a/spring-remoting/spring-remoting-rmi/pom.xml +++ b/spring-remoting/remoting-rmi/pom.xml @@ -2,18 +2,18 @@ - + 4.0.0 + pom + remoting-rmi + + spring-remoting com.baeldung 1.0-SNAPSHOT - 4.0.0 - pom - + + remoting-rmi-server remoting-rmi-client - spring-remoting-rmi - - \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-client/pom.xml b/spring-remoting/remoting-rmi/remoting-rmi-client/pom.xml similarity index 86% rename from spring-remoting/spring-remoting-rmi/remoting-rmi-client/pom.xml rename to spring-remoting/remoting-rmi/remoting-rmi-client/pom.xml index 003976dc7b..1e3cd4b977 100644 --- a/spring-remoting/spring-remoting-rmi/remoting-rmi-client/pom.xml +++ b/spring-remoting/remoting-rmi/remoting-rmi-client/pom.xml @@ -3,7 +3,7 @@ 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"> - spring-remoting-rmi + remoting-rmi com.baeldung 1.0-SNAPSHOT @@ -24,7 +24,8 @@ com.baeldung - api + remoting-http-api + ${project.version} \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java b/spring-remoting/remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java similarity index 100% rename from spring-remoting/spring-remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java rename to spring-remoting/remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java diff --git a/spring-security-anguar/server/src/main/resources/logback.xml b/spring-remoting/remoting-rmi/remoting-rmi-client/src/main/resources/logback.xml similarity index 100% rename from spring-security-anguar/server/src/main/resources/logback.xml rename to spring-remoting/remoting-rmi/remoting-rmi-client/src/main/resources/logback.xml diff --git a/spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3460792fc6 --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.client.RmiClient; + +@SpringBootTest(classes = RmiClient.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/pom.xml b/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml similarity index 83% rename from spring-remoting/spring-remoting-rmi/remoting-rmi-server/pom.xml rename to spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml index f1633e5dc2..68b01829e1 100644 --- a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/pom.xml +++ b/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml @@ -3,7 +3,7 @@ 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"> - spring-remoting-rmi + remoting-rmi com.baeldung 1.0-SNAPSHOT @@ -28,11 +28,7 @@ com.baeldung - api - - - com.baeldung - api + remoting-http-api ${project.version} diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java b/spring-remoting/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java similarity index 100% rename from spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java rename to spring-remoting/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java b/spring-remoting/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java similarity index 100% rename from spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java rename to spring-remoting/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java diff --git a/vaadin-spring/src/main/resources/logback.xml b/spring-remoting/remoting-rmi/remoting-rmi-server/src/main/resources/logback.xml similarity index 100% rename from vaadin-spring/src/main/resources/logback.xml rename to spring-remoting/remoting-rmi/remoting-rmi-server/src/main/resources/logback.xml diff --git a/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2063dd5e6e --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.server.RmiServer; + +@SpringBootTest(classes = RmiServer.class) +@RunWith(SpringRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-angular/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-angular/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..228d0019bd --- /dev/null +++ b/spring-rest-angular/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.web.main.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml index edccbb17d5..a8c53dbc3a 100644 --- a/spring-rest-embedded-tomcat/pom.xml +++ b/spring-rest-embedded-tomcat/pom.xml @@ -2,8 +2,7 @@ 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.embedded - SpringRestTomcat - 0.0.1-SNAPSHOT + spring-rest-embedded-tomcat spring-rest-embedded-tomcat war @@ -58,37 +57,18 @@ httpcore ${httpcore.version} + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + - - spring-rest-embedded-tomcat - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - - - 2.19.1 2.9.2 - 1.8 - 1.8 4.0.0 9.0.1 4.5.3 diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8b8ff1a322 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.embedded.configuration.UserConfiguration; +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.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { UserConfiguration.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index 23b0b0435b..b8fef9cb82 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -16,7 +16,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Project Configuration with Spring](http://www.baeldung.com/project-configuration-with-spring) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) -- [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) - [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) - [Build a REST API with Spring 4 and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) - [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring) @@ -41,5 +40,5 @@ mysql -u root -p ### Use the REST Service ``` -curl http://localhost:8080/spring-rest-full/foos +curl http://localhost:8082/spring-rest-full/auth/foos ``` diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index 4d328361ca..81c938a289 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -212,6 +212,23 @@ org.apache.maven.plugins maven-war-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*LiveTest.java + **/*TestSuite.java + + + org.codehaus.cargo cargo-maven2-plugin diff --git a/spring-rest-full/src/main/resources/logback.xml b/spring-rest-full/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-rest-full/src/main/resources/logback.xml +++ b/spring-rest-full/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-rest-full/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-full/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..35939c992f --- /dev/null +++ b/spring-rest-full/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-query-language/src/main/resources/logback.xml b/spring-rest-query-language/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-rest-query-language/src/main/resources/logback.xml +++ b/spring-rest-query-language/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-rest-query-language/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-query-language/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..35939c992f --- /dev/null +++ b/spring-rest-query-language/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-shell/pom.xml b/spring-rest-shell/pom.xml index 2f7d1c8933..7a604946b6 100644 --- a/spring-rest-shell/pom.xml +++ b/spring-rest-shell/pom.xml @@ -2,9 +2,7 @@ 4.0.0 - com.baeldung spring-rest-shell - 0.0.1-SNAPSHOT jar spring-rest-shell A simple project to demonstrate Spring REST Shell features. @@ -48,10 +46,4 @@ - - UTF-8 - UTF-8 - 1.8 - - diff --git a/spring-rest-simple/README.md b/spring-rest-simple/README.md index ae853ba787..57d6f50887 100644 --- a/spring-rest-simple/README.md +++ b/spring-rest-simple/README.md @@ -6,5 +6,4 @@ - [Spring RequestMapping](http://www.baeldung.com/spring-requestmapping) - [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring) - [Spring and Apache FileUpload](http://www.baeldung.com/spring-apache-file-upload) -- [Spring RestTemplate Error Handling](http://www.baeldung.com/spring-rest-template-error-handling) - [Test a REST API with curl](http://www.baeldung.com/curl-rest) diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index f5ce46ade4..d39e3a43c1 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -187,36 +187,6 @@ - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-war-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - org.codehaus.cargo cargo-maven2-plugin @@ -245,6 +215,26 @@ integration + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + org.apache.maven.plugins maven-surefire-plugin @@ -266,10 +256,10 @@ - + live diff --git a/spring-rest-simple/src/main/resources/logback.xml b/spring-rest-simple/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-rest-simple/src/main/resources/logback.xml +++ b/spring-rest-simple/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-simple/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java deleted file mode 100644 index 40e93f2d89..0000000000 --- a/spring-rest-simple/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.baeldung.client; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -import java.io.IOException; - -import org.baeldung.web.dto.Foo; -import org.junit.Before; -import org.junit.Test; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -public class RestTemplateBasicLiveTest { - - private RestTemplate restTemplate; - - private static final String fooResourceUrl = String.format("http://localhost:%d/spring-rest/foos", 8082); - - @Before - public void beforeTest() { - restTemplate = new RestTemplate(); - } - - // GET - - @Test - public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { - final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); - - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException { - final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); - - assertThat(foo.getName(), notNullValue()); - assertThat(foo.getId(), is(1L)); - } - - // PUT - - @Test - public void givenFooService_whenPutObject_thenUpdatedObjectIsReturned() { - final HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - final Foo foo = new Foo(1, "newName"); - final String resourceUrl = fooResourceUrl + "/1"; - final HttpEntity requestUpdate = new HttpEntity<>(foo, headers); - final ResponseEntity response = restTemplate.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Foo.class); - - assertThat(foo.getName(), is(response.getBody() - .getName())); - } - -} diff --git a/spring-rest/README.md b/spring-rest/README.md index 6ef86ad015..d449a4d92a 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -14,7 +14,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to FindBugs](http://www.baeldung.com/intro-to-findbugs) - [A Custom Media Type for a Spring REST API](http://www.baeldung.com/spring-rest-custom-media-type) - [HTTP PUT vs HTTP PATCH in a REST API](http://www.baeldung.com/http-put-patch-difference-spring) -- [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate) - [Spring – Log Incoming Requests](http://www.baeldung.com/spring-http-logging) - [RequestBody and ResponseBody Annotations](http://www.baeldung.com/requestbody-and-responsebody-annotations) - [Introduction to CheckStyle](http://www.baeldung.com/checkstyle-java) @@ -22,6 +21,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide to DeferredResult in Spring](http://www.baeldung.com/spring-deferred-result) - [Spring Custom Property Editor](http://www.baeldung.com/spring-mvc-custom-property-editor) - [Using the Spring RestTemplate Interceptor](http://www.baeldung.com/spring-rest-template-interceptor) -- [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) - [Get and Post Lists of Objects with RestTemplate](http://www.baeldung.com/spring-rest-template-list) - [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 403ed4cfde..ba74d26c35 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-rest 0.1-SNAPSHOT spring-rest @@ -102,7 +101,6 @@ org.apache.commons commons-lang3 - ${commons-lang3.version} @@ -168,7 +166,6 @@ io.rest-assured rest-assured - ${rest-assured.version} @@ -194,25 +191,6 @@ org.apache.maven.plugins maven-war-plugin - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - - tomcat8x - embedded - - - - - - - 8082 - - - - org.apache.maven.plugins maven-checkstyle-plugin @@ -228,23 +206,7 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*LiveTest.java - - - - diff --git a/spring-rest/src/main/resources/logback.xml b/spring-rest/src/main/resources/logback.xml index 3496a4a03c..9f48d36486 100644 --- a/spring-rest/src/main/resources/logback.xml +++ b/spring-rest/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java index a84f866dfe..814efc112a 100644 --- a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java +++ b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java @@ -4,10 +4,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; - -import com.baeldung.propertyeditor.creditcard.CreditCard; -import com.baeldung.propertyeditor.creditcard.CreditCardEditor; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class CreditCardEditorUnitTest { diff --git a/spring-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..d99dacd331 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,24 @@ +package org.baeldung; + +import org.baeldung.config.MainApplication; +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.custom.CustomApplication; +import com.baeldung.produceimage.ImageApplication; +import com.baeldung.propertyeditor.PropertyEditorApplication; +import com.baeldung.responseheaders.ResponseHeadersApplication; +import com.baeldung.web.log.app.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { CustomApplication.class, ImageApplication.class, PropertyEditorApplication.class, + ResponseHeadersApplication.class, Application.class, com.baeldung.web.upload.app.Application.class, + MainApplication.class}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java b/spring-rest/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java deleted file mode 100644 index a8a71c7d73..0000000000 --- a/spring-rest/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.baeldung.client; - -import okhttp3.Request; -import okhttp3.RequestBody; -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.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -import static org.baeldung.client.Consts.APPLICATION_PORT; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; - -public class TestRestTemplateBasicLiveTest { - - private RestTemplateBuilder restTemplate; - private static final String FOO_RESOURCE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos"; - private static final String URL_SECURED_BY_AUTHENTICATION = "http://httpbin.org/basic-auth/user/passwd"; - private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; - - @Before - public void beforeTest() { - restTemplate = new RestTemplateBuilder(); - } - - // GET - @Test - public void givenTestRestTemplate_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate); - ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() { - RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); - restTemplateBuilder.build(); - TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); - ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, "user", "passwd"); - ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, - String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenTestRestTemplateWithCredentials_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); - ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, - String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenTestRestTemplateWithBasicAuth_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ResponseEntity response = testRestTemplate.withBasicAuth("user", "passwd"). - getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenTestRestTemplateWithCredentialsAndEnabledCookies_whenSendGetForEntity_thenStatusOk() { - TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd", TestRestTemplate. - HttpClientOption.ENABLE_COOKIES); - ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, - String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - // HEAD - @Test - public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeaders() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - final HttpHeaders httpHeaders = testRestTemplate.headForHeaders(FOO_RESOURCE_URL); - assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); - } - - // POST - @Test - public void givenService_whenPostForObject_thenCreatedObjectIsReturned() { - TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); - final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), - "{\"id\":1,\"name\":\"Jim\"}"); - final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); - testRestTemplate.postForObject(URL_SECURED_BY_AUTHENTICATION, request, String.class); - } - - // PUT - @Test - public void givenService_whenPutForObject_thenCreatedObjectIsReturned() { - TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); - final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), - "{\"id\":1,\"name\":\"Jim\"}"); - final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); - testRestTemplate.put(URL_SECURED_BY_AUTHENTICATION, request, String.class); - } - -} diff --git a/spring-resttemplate/.gitignore b/spring-resttemplate/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-resttemplate/.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/spring-resttemplate/README.md b/spring-resttemplate/README.md new file mode 100644 index 0000000000..bf8c56e6ec --- /dev/null +++ b/spring-resttemplate/README.md @@ -0,0 +1,10 @@ +## Spring REST Example Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: +- [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) +- [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate) +- [Spring RestTemplate Error Handling](http://www.baeldung.com/spring-rest-template-error-handling) +- [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) \ No newline at end of file diff --git a/spring-resttemplate/pom.xml b/spring-resttemplate/pom.xml new file mode 100644 index 0000000000..481104372a --- /dev/null +++ b/spring-resttemplate/pom.xml @@ -0,0 +1,297 @@ + + 4.0.0 + com.baeldung + spring-resttemplate + 0.1-SNAPSHOT + spring-resttemplate + war + + + parent-boot-1 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-1 + + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework + spring-web + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + + + org.springframework + spring-oxm + + + + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.thoughtworks.xstream + xstream + ${xstream.version} + + + + + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + org.slf4j + jcl-over-slf4j + + + + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + + + + + junit + junit + test + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + org.mockito + mockito-core + test + + + org.springframework + spring-test + + + + + spring-resttemplate + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-war-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + + + tomcat8x + embedded + + + + + + + 8082 + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + + + 3.5 + 1.4.9 + + + 20.0 + + + 1.6.0 + 3.0.4 + + + 3.4.1 + + + diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java similarity index 100% rename from spring-rest/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/dto/Foo.java b/spring-resttemplate/src/main/java/org/baeldung/web/dto/Foo.java new file mode 100644 index 0000000000..240b368b50 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/web/dto/Foo.java @@ -0,0 +1,45 @@ +package org.baeldung.web.dto; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("Foo") +public class Foo { + private long id; + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + public Foo(final long id, final String name) { + super(); + + this.id = id; + 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; + } + +} \ No newline at end of file diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/exception/NotFoundException.java b/spring-resttemplate/src/main/java/org/baeldung/web/exception/NotFoundException.java similarity index 100% rename from spring-rest-simple/src/main/java/org/baeldung/web/exception/NotFoundException.java rename to spring-resttemplate/src/main/java/org/baeldung/web/exception/NotFoundException.java diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java b/spring-resttemplate/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java similarity index 100% rename from spring-rest-simple/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java rename to spring-resttemplate/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/model/Bar.java b/spring-resttemplate/src/main/java/org/baeldung/web/model/Bar.java similarity index 100% rename from spring-rest-simple/src/main/java/org/baeldung/web/model/Bar.java rename to spring-resttemplate/src/main/java/org/baeldung/web/model/Bar.java diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/service/BarConsumerService.java b/spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java similarity index 100% rename from spring-rest-simple/src/main/java/org/baeldung/web/service/BarConsumerService.java rename to spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java diff --git a/spring-resttemplate/src/main/resources/application.properties b/spring-resttemplate/src/main/resources/application.properties new file mode 100644 index 0000000000..1a26e3ad99 --- /dev/null +++ b/spring-resttemplate/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8082 +server.servlet.context-path=/spring-rest \ No newline at end of file diff --git a/spring-resttemplate/src/main/resources/logback.xml b/spring-resttemplate/src/main/resources/logback.xml new file mode 100644 index 0000000000..9f48d36486 --- /dev/null +++ b/spring-resttemplate/src/main/resources/logback.xml @@ -0,0 +1,23 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-resttemplate/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..3a5a20cfeb --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.resttemplate.configuration.RestTemplateConfigurationApplication; +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 = RestTemplateConfigurationApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java b/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java new file mode 100644 index 0000000000..b40561d9c3 --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java @@ -0,0 +1,5 @@ +package org.baeldung.client; + +public interface Consts { + int APPLICATION_PORT = 8082; +} diff --git a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java similarity index 100% rename from spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java diff --git a/spring-rest-simple/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java similarity index 100% rename from spring-rest-simple/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java similarity index 100% rename from spring-rest-simple/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java rename to spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java diff --git a/spring-resttemplate/src/test/resources/.gitignore b/spring-resttemplate/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-resttemplate/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/spring-roo/pom.xml b/spring-roo/pom.xml index e689ab11aa..c205c98dc0 100644 --- a/spring-roo/pom.xml +++ b/spring-roo/pom.xml @@ -4,9 +4,9 @@ 4.0.0 com.baeldung - roo + spring-roo 1.0.0.BUILD-SNAPSHOT - roo + Spring Roo jar diff --git a/spring-security-acl/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-acl/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c7890d79ac --- /dev/null +++ b/spring-security-acl/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.acl.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-anguar/client/anguarjs/app.js b/spring-security-anguar/client/anguarjs/app.js deleted file mode 100644 index 4b7268da3f..0000000000 --- a/spring-security-anguar/client/anguarjs/app.js +++ /dev/null @@ -1,40 +0,0 @@ -(function () { - 'use strict'; - - angular - .module('app', ['ngRoute']) - .config(config) - .run(run); - - config.$inject = ['$routeProvider', '$locationProvider']; - function config($routeProvider, $locationProvider) { - $routeProvider - .when('/', { - controller: 'HomeController', - templateUrl: 'home/home.view.html', - controllerAs: 'vm' - }) - .when('/login', { - controller: 'LoginController', - templateUrl: 'login/login.view.html', - controllerAs: 'vm' - }) - .otherwise({ redirectTo: '/login' }); - } - - run.$inject = ['$rootScope', '$location', '$http', '$window']; - function run($rootScope, $location, $http, $window) { - var userData = $window.sessionStorage.getItem('userData'); - if (userData) { - $http.defaults.headers.common['Authorization'] = 'Basic ' + JSON.parse(userData).authData; - } - - $rootScope.$on('$locationChangeStart', function (event, next, current) { - var restrictedPage = $.inArray($location.path(), ['/login']) === -1; - var loggedIn = $window.sessionStorage.getItem('userData');; - if (restrictedPage && !loggedIn) { - $location.path('/login'); - } - }); - } -})(); \ No newline at end of file diff --git a/spring-security-anguar/client/anguarjs/home/home.controller.js b/spring-security-anguar/client/anguarjs/home/home.controller.js deleted file mode 100644 index 6449029ec2..0000000000 --- a/spring-security-anguar/client/anguarjs/home/home.controller.js +++ /dev/null @@ -1,34 +0,0 @@ -(function () { - 'use strict'; - - angular - .module('app') - .controller('HomeController', HomeController); - - HomeController.$inject = ['$window', '$http', '$scope']; - function HomeController($window, $http, $scope) { - var vm = this; - - vm.user = null; - - initController(); - - function initController() { - - $http({ - url: 'http://localhost:8082/user', - method: "GET" - }).then(function (response) { - vm.user = response.data.name; - },function(error){ - console.log(error); - }); - }; - - $scope.logout = function(){ - $window.sessionStorage.setItem('userData', ''); - $http.defaults.headers.common['Authorization'] = 'Basic'; - } - } - -})(); \ No newline at end of file diff --git a/spring-security-anguar/client/anguarjs/home/home.view.html b/spring-security-anguar/client/anguarjs/home/home.view.html deleted file mode 100644 index bb5c2d3dbf..0000000000 --- a/spring-security-anguar/client/anguarjs/home/home.view.html +++ /dev/null @@ -1,3 +0,0 @@ -

    Hi {{vm.user}}!

    -

    You're logged in!!

    -

    Logout

    \ No newline at end of file diff --git a/spring-security-anguar/client/anguarjs/index.html b/spring-security-anguar/client/anguarjs/index.html deleted file mode 100644 index a5584d53be..0000000000 --- a/spring-security-anguar/client/anguarjs/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - -
    - - - - - - - - - - \ No newline at end of file diff --git a/spring-security-anguar/client/anguarjs/login/login.controller.js b/spring-security-anguar/client/anguarjs/login/login.controller.js deleted file mode 100644 index 2da509ec83..0000000000 --- a/spring-security-anguar/client/anguarjs/login/login.controller.js +++ /dev/null @@ -1,38 +0,0 @@ -(function () { - 'use strict'; - - angular - .module('app') - .controller('LoginController', LoginController); - - LoginController.$inject = ['$location', '$window', '$http']; - function LoginController($location, $window, $http) { - var vm = this; - vm.login = login; - - (function initController() { - $window.localStorage.setItem('token', ''); - })(); - - function login() { - $http({ - url: 'http://localhost:8082/login', - method: "POST", - data: { 'userName': vm.username, 'password': vm.password } - }).then(function (response) { - if (response.data) { - var token = $window.btoa(vm.username + ':' + vm.password); - var userData = { - userName: vm.username, - authData: token - } - $window.sessionStorage.setItem('userData', JSON.stringify(userData)); - $http.defaults.headers.common['Authorization'] = 'Basic ' + token; - $location.path('/'); - } else { - alert("Authentication failed.") - } - }); - }; - } -})(); diff --git a/spring-security-anguar/client/anguarjs/login/login.view.html b/spring-security-anguar/client/anguarjs/login/login.view.html deleted file mode 100644 index 0d42f29b54..0000000000 --- a/spring-security-anguar/client/anguarjs/login/login.view.html +++ /dev/null @@ -1,18 +0,0 @@ -
    -

    Login

    -
    -
    - - - Username is required -
    -
    - - - Password is required -
    -
    - -
    -
    -
    \ No newline at end of file diff --git a/spring-security-anguar/client/angular2/app.css b/spring-security-anguar/client/angular2/app.css deleted file mode 100644 index cdd2d591d8..0000000000 --- a/spring-security-anguar/client/angular2/app.css +++ /dev/null @@ -1,7 +0,0 @@ -a { - cursor: pointer; -} - -.help-block { - font-size: 12px; -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular2/app/app.component.html b/spring-security-anguar/client/angular2/app/app.component.html deleted file mode 100644 index 7f77adea7b..0000000000 --- a/spring-security-anguar/client/angular2/app/app.component.html +++ /dev/null @@ -1,7 +0,0 @@ -
    -
    -
    - -
    -
    -
    diff --git a/spring-security-anguar/client/angular2/app/app.component.ts b/spring-security-anguar/client/angular2/app/app.component.ts deleted file mode 100644 index 0aae2b6992..0000000000 --- a/spring-security-anguar/client/angular2/app/app.component.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Component } from '@angular/core'; - -@Component({ - selector: 'app', - templateUrl: './app/app.component.html' -}) - -export class AppComponent { } \ No newline at end of file diff --git a/spring-security-anguar/client/angular2/app/app.module.ts b/spring-security-anguar/client/angular2/app/app.module.ts deleted file mode 100644 index 4d484b49f8..0000000000 --- a/spring-security-anguar/client/angular2/app/app.module.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { NgModule } from '@angular/core'; -import { BrowserModule } from '@angular/platform-browser'; -import { FormsModule } from '@angular/forms'; -import { HttpModule } from '@angular/http'; - -import { AppComponent } from './app.component'; -import { routing } from './app.routing'; - -import { HomeComponent } from './home/home.component'; -import { LoginComponent } from './login/login.component'; - -@NgModule({ - imports: [ - BrowserModule, - FormsModule, - HttpModule, - routing - ], - declarations: [ - AppComponent, - HomeComponent, - LoginComponent - ], - bootstrap: [AppComponent] -}) - -export class AppModule { } \ No newline at end of file diff --git a/spring-security-anguar/client/angular2/app/app.routing.ts b/spring-security-anguar/client/angular2/app/app.routing.ts deleted file mode 100644 index c794fc5c50..0000000000 --- a/spring-security-anguar/client/angular2/app/app.routing.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Routes, RouterModule } from '@angular/router'; - -import { HomeComponent } from './home/home.component'; -import { LoginComponent } from './login/login.component'; - -const appRoutes: Routes = [ - { path: '', component: HomeComponent}, - { path: 'login', component: LoginComponent }, - { path: '**', redirectTo: '' } -]; - -export const routing = RouterModule.forRoot(appRoutes); \ No newline at end of file diff --git a/spring-security-anguar/client/angular2/app/home/home.component.html b/spring-security-anguar/client/angular2/app/home/home.component.html deleted file mode 100644 index 5f3b24be3a..0000000000 --- a/spring-security-anguar/client/angular2/app/home/home.component.html +++ /dev/null @@ -1,4 +0,0 @@ -
    -

    Hi {{userName}}!

    -

    Logout

    -
    \ No newline at end of file diff --git a/spring-security-anguar/client/angular2/app/home/home.component.ts b/spring-security-anguar/client/angular2/app/home/home.component.ts deleted file mode 100644 index 1b168bfb30..0000000000 --- a/spring-security-anguar/client/angular2/app/home/home.component.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Component, OnInit } from '@angular/core'; -import { Http, RequestOptions, Headers } from '@angular/http'; -import 'rxjs/add/operator/map' - -@Component({ - selector:'home', - templateUrl: './app/home/home.component.html' -}) - -export class HomeComponent implements OnInit { - - userName: string; - - constructor(private http: Http) { } - - ngOnInit() { - let url = 'http://localhost:8082/user'; - let headers = new Headers({ - 'Authorization': 'Basic ' + sessionStorage.getItem('token') - }); - let options = new RequestOptions({ headers: headers }); - this.http.post(url,{}, options). - map(res => res.json()). - subscribe( - principal => this.userName = principal.name, - error => { - if(error.status == 401) - alert('Unauthorized'); - } - ); - } - - logout() { - sessionStorage.setItem('token', ''); - } -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular2/app/login/login.component.html b/spring-security-anguar/client/angular2/app/login/login.component.html deleted file mode 100644 index d87b91a7bb..0000000000 --- a/spring-security-anguar/client/angular2/app/login/login.component.html +++ /dev/null @@ -1,18 +0,0 @@ -
    -

    Login

    -
    -
    - - -
    Username is required
    -
    -
    - - -
    Password is required
    -
    -
    - -
    -
    -
    diff --git a/spring-security-anguar/client/angular2/app/login/login.component.ts b/spring-security-anguar/client/angular2/app/login/login.component.ts deleted file mode 100644 index 81d6c1d7ae..0000000000 --- a/spring-security-anguar/client/angular2/app/login/login.component.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Component, OnInit } from '@angular/core'; -import { Router, ActivatedRoute } from '@angular/router'; -import { Http } from '@angular/http'; - -@Component({ - selector: 'login', - templateUrl: './app/login/login.component.html' -}) - -export class LoginComponent implements OnInit { - model: any = {}; - - constructor( - private route: ActivatedRoute, - private router: Router, - private http: Http) { } - - ngOnInit() { - sessionStorage.setItem('token', ''); - } - - login() { - let url = 'http://localhost:8082/login'; - let result = this.http.post(url, { - userName: this.model.username, - password: this.model.password - }).map(res => res.json()).subscribe(isValid => { - if (isValid) { - sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password)); - this.router.navigate(['']); - } else { - alert("Authentication failed."); - } - }); - } -} diff --git a/spring-security-anguar/client/angular2/app/main.ts b/spring-security-anguar/client/angular2/app/main.ts deleted file mode 100644 index 3a6c754786..0000000000 --- a/spring-security-anguar/client/angular2/app/main.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - -import { AppModule } from './app.module'; - -platformBrowserDynamic().bootstrapModule(AppModule); \ No newline at end of file diff --git a/spring-security-anguar/client/angular2/index.html b/spring-security-anguar/client/angular2/index.html deleted file mode 100644 index c9730a8568..0000000000 --- a/spring-security-anguar/client/angular2/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - Loading... - - diff --git a/spring-security-anguar/client/angular2/package.json b/spring-security-anguar/client/angular2/package.json deleted file mode 100644 index 9b36652fac..0000000000 --- a/spring-security-anguar/client/angular2/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "angular2-quickstart", - "version": "1.0.0", - "description": "Sample of how easy and fast to start hacking with Angular2 and ng2-bootstrap", - "scripts": { - "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ", - "lite": "lite-server", - "tsc": "tsc", - "tsc:w": "tsc -w" - }, - "license": "ISC", - "dependencies": { - "@angular/common": "2.4.4", - "@angular/compiler": "2.4.4", - "@angular/core": "2.4.4", - "@angular/forms": "2.4.4", - "@angular/http": "2.4.4", - "@angular/platform-browser": "2.4.4", - "@angular/platform-browser-dynamic": "2.4.4", - "@angular/router": "3.4.4", - "@angular/upgrade": "2.4.4", - "angular2-in-memory-web-api": "0.0.21", - "bootstrap": "^3.3.7", - "core-js": "^2.4.1", - "ng2-bootstrap": "1.3.0", - "reflect-metadata": "^0.1.8", - "rxjs": "5.0.3", - "systemjs": "0.20.0", - "zone.js": "0.7.6" - }, - "devDependencies": { - "concurrently": "3.1.0", - "lite-server": "^2.2.0", - "typescript": "2.1.5" - }, - "repository": {} -} diff --git a/spring-security-anguar/client/angular2/systemjs.config.js b/spring-security-anguar/client/angular2/systemjs.config.js deleted file mode 100644 index ea4c543fdd..0000000000 --- a/spring-security-anguar/client/angular2/systemjs.config.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * System configuration for Angular 2 samples - * Adjust as necessary for your application needs. - */ -(function (global) { - System.config({ - paths: { - // paths serve as alias - 'npm:': 'node_modules/' - }, - // map tells the System loader where to look for things - map: { - // our app is within the app folder - app: 'app', - - // angular bundles - '@angular/core': 'npm:@angular/core/bundles/core.umd.js', - '@angular/common': 'npm:@angular/common/bundles/common.umd.js', - '@angular/http': 'npm:@angular/http/bundles/http.umd.js', - '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', - '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', - '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', - '@angular/router': 'npm:@angular/router/bundles/router.umd.js', - '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', - - // other libraries - 'rxjs': 'npm:rxjs', - 'tslib': 'npm:tslib/tslib.js' - }, - // packages tells the System loader how to load when no filename and/or no extension - packages: { - app: { - main: './main.js', - defaultExtension: 'js' - }, - rxjs: { - defaultExtension: 'js' - } - } - }); -})(this); diff --git a/spring-security-anguar/client/angular2/tsconfig.json b/spring-security-anguar/client/angular2/tsconfig.json deleted file mode 100644 index 55f9ad70c3..0000000000 --- a/spring-security-anguar/client/angular2/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "compilerOptions": { - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "lib": [ "es2015", "dom" ], - "module": "commonjs", - "moduleResolution": "node", - "noImplicitAny": true, - "sourceMap": true, - "suppressImplicitAnyIndexErrors": true, - "target": "es5" - }, - "exclude": [ - "node_modules/*" - ] -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/.angular-cli.json b/spring-security-anguar/client/angular4/.angular-cli.json deleted file mode 100644 index 967934b2f7..0000000000 --- a/spring-security-anguar/client/angular4/.angular-cli.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "$schema": "./node_modules/@angular/cli/lib/config/schema.json", - "project": { - "name": "angular-crud" - }, - "apps": [ - { - "root": "src", - "outDir": "dist", - "assets": [ - "assets", - "favicon.ico" - ], - "index": "index.html", - "main": "main.ts", - "polyfills": "polyfills.ts", - "test": "test.ts", - "tsconfig": "tsconfig.app.json", - "testTsconfig": "tsconfig.spec.json", - "prefix": "app", - "styles": [ - "../node_modules/bootstrap/dist/css/bootstrap.min.css", - "styles.css", - "../node_modules/font-awesome/css/font-awesome.min.css" - ], - "scripts": [ - "../node_modules/jquery/dist/jquery.js", - "../node_modules/bootstrap/dist/js/bootstrap.js" - ], - "environmentSource": "environments/environment.ts", - "environments": { - "dev": "environments/environment.ts", - "prod": "environments/environment.prod.ts" - } - } - ], - "e2e": { - "protractor": { - "config": "./protractor.conf.js" - } - }, - "lint": [ - { - "project": "src/tsconfig.app.json", - "exclude": "**/node_modules/**" - }, - { - "project": "src/tsconfig.spec.json", - "exclude": "**/node_modules/**" - }, - { - "project": "e2e/tsconfig.e2e.json", - "exclude": "**/node_modules/**" - } - ], - "test": { - "karma": { - "config": "./karma.conf.js" - } - }, - "defaults": { - "styleExt": "css", - "component": {} - } -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/package.json b/spring-security-anguar/client/angular4/package.json deleted file mode 100644 index 8c6ddcaf1f..0000000000 --- a/spring-security-anguar/client/angular4/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "angular-crud", - "version": "0.0.0", - "license": "MIT", - "scripts": { - "ng": "ng", - "start": "ng serve", - "build": "ng build", - "test": "ng test", - "lint": "ng lint", - "e2e": "ng e2e" - }, - "private": true, - "dependencies": { - "@angular/animations": "^4.0.0", - "@angular/common": "^4.0.0", - "@angular/compiler": "^4.0.0", - "@angular/core": "^4.0.0", - "@angular/forms": "^4.0.0", - "@angular/http": "^4.0.0", - "@angular/platform-browser": "^4.0.0", - "@angular/platform-browser-dynamic": "^4.0.0", - "@angular/router": "^4.0.0", - "bootstrap": "^3.3.7", - "core-js": "^2.4.1", - "font-awesome": "^4.7.0", - "jquery": "^3.2.1", - "lodash": "^4.17.4", - "rxjs": "^5.4.1", - "zone.js": "^0.8.14" - }, - "devDependencies": { - "@angular/cli": "1.2.3", - "@angular/compiler-cli": "^4.0.0", - "@angular/language-service": "^4.0.0", - "@types/jasmine": "~2.5.53", - "@types/jasminewd2": "~2.0.2", - "@types/lodash": "^4.14.66", - "@types/node": "~6.0.60", - "codelyzer": "~3.0.1", - "jasmine-core": "~2.6.2", - "jasmine-spec-reporter": "~4.1.0", - "karma": "~1.7.0", - "karma-chrome-launcher": "~2.1.1", - "karma-cli": "~1.0.1", - "karma-coverage-istanbul-reporter": "^1.2.1", - "karma-jasmine": "~1.1.0", - "karma-jasmine-html-reporter": "^0.2.2", - "protractor": "~5.1.2", - "ts-node": "~3.0.4", - "tslint": "~5.3.2", - "typescript": "~2.3.3" - } -} diff --git a/spring-security-anguar/client/angular4/src/app/app.component.html b/spring-security-anguar/client/angular4/src/app/app.component.html deleted file mode 100644 index 7f77adea7b..0000000000 --- a/spring-security-anguar/client/angular4/src/app/app.component.html +++ /dev/null @@ -1,7 +0,0 @@ -
    -
    -
    - -
    -
    -
    diff --git a/spring-security-anguar/client/angular4/src/app/app.component.ts b/spring-security-anguar/client/angular4/src/app/app.component.ts deleted file mode 100644 index 36f986c63f..0000000000 --- a/spring-security-anguar/client/angular4/src/app/app.component.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Component } from '@angular/core'; - -@Component({ - selector: 'app-root', - templateUrl: './app.component.html' -}) - -export class AppComponent { } \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/src/app/app.module.ts b/spring-security-anguar/client/angular4/src/app/app.module.ts deleted file mode 100644 index 9e840e6f13..0000000000 --- a/spring-security-anguar/client/angular4/src/app/app.module.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { NgModule } from '@angular/core'; -import { BrowserModule } from '@angular/platform-browser'; -import { FormsModule } from '@angular/forms'; -import { HttpModule } from '@angular/http'; - -// used to create fake backend - -import { AppComponent } from './app.component'; -import { routing } from './app.routing'; - -import { HomeComponent } from './home/home.component'; -import { LoginComponent } from './login/login.component'; - -@NgModule({ - imports: [ - BrowserModule, - FormsModule, - HttpModule, - routing - ], - declarations: [ - AppComponent, - HomeComponent, - LoginComponent - ], - bootstrap: [AppComponent] -}) - -export class AppModule { } \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/src/app/app.routing.ts b/spring-security-anguar/client/angular4/src/app/app.routing.ts deleted file mode 100644 index c794fc5c50..0000000000 --- a/spring-security-anguar/client/angular4/src/app/app.routing.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Routes, RouterModule } from '@angular/router'; - -import { HomeComponent } from './home/home.component'; -import { LoginComponent } from './login/login.component'; - -const appRoutes: Routes = [ - { path: '', component: HomeComponent}, - { path: 'login', component: LoginComponent }, - { path: '**', redirectTo: '' } -]; - -export const routing = RouterModule.forRoot(appRoutes); \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/src/app/home/home.component.html b/spring-security-anguar/client/angular4/src/app/home/home.component.html deleted file mode 100644 index 7ccd2c2a3a..0000000000 --- a/spring-security-anguar/client/angular4/src/app/home/home.component.html +++ /dev/null @@ -1,4 +0,0 @@ -
    -

    Hi {{userName}}!

    -

    Logout

    -
    \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/src/app/home/home.component.ts b/spring-security-anguar/client/angular4/src/app/home/home.component.ts deleted file mode 100644 index 0f66f42ce2..0000000000 --- a/spring-security-anguar/client/angular4/src/app/home/home.component.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Component, OnInit } from '@angular/core'; -import { Http, RequestOptions, Headers } from '@angular/http'; -import 'rxjs/add/operator/map' - -@Component({ - selector:'home', - templateUrl: './home.component.html' -}) - -export class HomeComponent implements OnInit { - - userName: string; - - constructor(private http: Http) { } - - ngOnInit() { - let url = 'http://localhost:8082/user'; - let headers = new Headers({ - 'Authorization': 'Basic ' + sessionStorage.getItem('token') - }); - let options = new RequestOptions({ headers: headers }); - this.http.post(url,{}, options). - map( - res => res.json(), - error => { - if(error.status == 401) - alert('Unauthorized'); - } - ).subscribe(principal => { - this.userName = principal.name; - }); - } - - logout() { - sessionStorage.setItem('token', ''); - } -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/src/app/login/login.component.html b/spring-security-anguar/client/angular4/src/app/login/login.component.html deleted file mode 100644 index d87b91a7bb..0000000000 --- a/spring-security-anguar/client/angular4/src/app/login/login.component.html +++ /dev/null @@ -1,18 +0,0 @@ -
    -

    Login

    -
    -
    - - -
    Username is required
    -
    -
    - - -
    Password is required
    -
    -
    - -
    -
    -
    diff --git a/spring-security-anguar/client/angular4/src/app/login/login.component.ts b/spring-security-anguar/client/angular4/src/app/login/login.component.ts deleted file mode 100644 index 2a2dc102af..0000000000 --- a/spring-security-anguar/client/angular4/src/app/login/login.component.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { Component, OnInit } from '@angular/core'; -import { Router, ActivatedRoute } from '@angular/router'; -import { Http } from '@angular/http'; - -@Component({ - selector: 'login', - templateUrl: './login.component.html' -}) - -export class LoginComponent implements OnInit { - model: any = {}; - - constructor( - private route: ActivatedRoute, - private router: Router, - private http: Http) { } - - ngOnInit() { - sessionStorage.setItem('token', ''); - } - - - login() { - let url = 'http://localhost:8082/login'; - let result = this.http.post(url, { - userName: this.model.username, - password: this.model.password - }). - map(res => res.json()). - subscribe(isValid => { - if (isValid) { - sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password)); - this.router.navigate(['']); - } else { - alert("Authentication failed.") - } - }); - } -} diff --git a/spring-security-anguar/client/angular4/src/index.html b/spring-security-anguar/client/angular4/src/index.html deleted file mode 100644 index c716820396..0000000000 --- a/spring-security-anguar/client/angular4/src/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - AngularCRUD - - - - - - - - - \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/src/main.ts b/spring-security-anguar/client/angular4/src/main.ts deleted file mode 100644 index 49db98ae89..0000000000 --- a/spring-security-anguar/client/angular4/src/main.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - -import { AppModule } from './app/app.module'; - -platformBrowserDynamic().bootstrapModule(AppModule); \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/src/polyfills.ts b/spring-security-anguar/client/angular4/src/polyfills.ts deleted file mode 100644 index a4984ced57..0000000000 --- a/spring-security-anguar/client/angular4/src/polyfills.ts +++ /dev/null @@ -1,68 +0,0 @@ -/** - * This file includes polyfills needed by Angular and is loaded before the app. - * You can add your own extra polyfills to this file. - * - * This file is divided into 2 sections: - * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. - * 2. Application imports. Files imported after ZoneJS that should be loaded before your main - * file. - * - * The current setup is for so-called "evergreen" browsers; the last versions of browsers that - * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), - * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. - * - * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html - */ - -/*************************************************************************************************** - * BROWSER POLYFILLS - */ - -/** IE9, IE10 and IE11 requires all of the following polyfills. **/ -// import 'core-js/es6/symbol'; -// import 'core-js/es6/object'; -// import 'core-js/es6/function'; -// import 'core-js/es6/parse-int'; -// import 'core-js/es6/parse-float'; -// import 'core-js/es6/number'; -// import 'core-js/es6/math'; -// import 'core-js/es6/string'; -// import 'core-js/es6/date'; -// import 'core-js/es6/array'; -// import 'core-js/es6/regexp'; -// import 'core-js/es6/map'; -// import 'core-js/es6/weak-map'; -// import 'core-js/es6/set'; -/** IE10 and IE11 requires the following for NgClass support on SVG elements */ -// import 'classlist.js'; // Run `npm install --save classlist.js`. -/** Evergreen browsers require these. **/ -import 'core-js/es6/reflect'; -import 'core-js/es7/reflect'; - - -/** - * Required to support Web Animations `@angular/animation`. - * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation - **/ -// import 'web-animations-js'; // Run `npm install --save web-animations-js`. - - -/*************************************************************************************************** - * Zone JS is required by Angular itself. - */ -import 'zone.js/dist/zone'; // Included with Angular CLI. - - -/*************************************************************************************************** - * APPLICATION IMPORTS - */ - -/** - * Date, currency, decimal and percent pipes. - * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 - */ -// import 'intl'; // Run `npm install --save intl`. -/** - * Need to import at least one locale-data with intl. - */ -// import 'intl/locale-data/jsonp/en'; \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/src/styles.css b/spring-security-anguar/client/angular4/src/styles.css deleted file mode 100644 index cdd2d591d8..0000000000 --- a/spring-security-anguar/client/angular4/src/styles.css +++ /dev/null @@ -1,7 +0,0 @@ -a { - cursor: pointer; -} - -.help-block { - font-size: 12px; -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/src/tsconfig.app.json b/spring-security-anguar/client/angular4/src/tsconfig.app.json deleted file mode 100644 index 213ce42a1b..0000000000 --- a/spring-security-anguar/client/angular4/src/tsconfig.app.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/app", - "baseUrl": "./", - "module": "es2015", - "types": [] - }, - "exclude": [ - "test.ts", - "**/*.spec.ts" - ] -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular4/tsconfig.json b/spring-security-anguar/client/angular4/tsconfig.json deleted file mode 100644 index ef44e2862b..0000000000 --- a/spring-security-anguar/client/angular4/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compileOnSave": false, - "compilerOptions": { - "baseUrl": "./", - "outDir": "./dist/out-tsc", - "sourceMap": true, - "declaration": false, - "moduleResolution": "node", - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es5", - "typeRoots": [ - "node_modules/@types" - ], - "lib": [ - "es2017", - "dom" - ] - } -} diff --git a/spring-security-anguar/client/angular4/tslint.json b/spring-security-anguar/client/angular4/tslint.json deleted file mode 100644 index 3ea984c776..0000000000 --- a/spring-security-anguar/client/angular4/tslint.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "rulesDirectory": [ - "node_modules/codelyzer" - ], - "rules": { - "arrow-return-shorthand": true, - "callable-types": true, - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "curly": true, - "deprecation": { - "severity": "warn" - }, - "eofline": true, - "forin": true, - "import-blacklist": [ - true, - "rxjs/Rx" - ], - "import-spacing": true, - "indent": [ - true, - "spaces" - ], - "interface-over-type-literal": true, - "label-position": true, - "max-line-length": [ - true, - 140 - ], - "member-access": false, - "member-ordering": [ - true, - { - "order": [ - "static-field", - "instance-field", - "static-method", - "instance-method" - ] - } - ], - "no-arg": true, - "no-bitwise": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], - "no-construct": true, - "no-debugger": true, - "no-duplicate-super": true, - "no-empty": false, - "no-empty-interface": true, - "no-eval": true, - "no-inferrable-types": [ - true, - "ignore-params" - ], - "no-misused-new": true, - "no-non-null-assertion": true, - "no-shadowed-variable": true, - "no-string-literal": false, - "no-string-throw": true, - "no-switch-case-fall-through": true, - "no-trailing-whitespace": true, - "no-unnecessary-initializer": true, - "no-unused-expression": true, - "no-use-before-declare": true, - "no-var-keyword": true, - "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], - "prefer-const": true, - "quotemark": [ - true, - "single" - ], - "radix": true, - "semicolon": [ - true, - "always" - ], - "triple-equals": [ - true, - "allow-null-check" - ], - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - } - ], - "unified-signatures": true, - "variable-name": false, - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ], - "no-output-on-prefix": true, - "use-input-property-decorator": true, - "use-output-property-decorator": true, - "use-host-property-decorator": true, - "no-input-rename": true, - "no-output-rename": true, - "use-life-cycle-interface": true, - "use-pipe-transform-interface": true, - "component-class-suffix": true, - "directive-class-suffix": true - } -} diff --git a/spring-security-anguar/client/angular5/.angular-cli.json b/spring-security-anguar/client/angular5/.angular-cli.json deleted file mode 100644 index d390652214..0000000000 --- a/spring-security-anguar/client/angular5/.angular-cli.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "$schema": "./node_modules/@angular/cli/lib/config/schema.json", - "project": { - "name": "angular5" - }, - "apps": [ - { - "root": "src", - "outDir": "dist", - "assets": [ - "assets", - "favicon.ico" - ], - "index": "index.html", - "main": "main.ts", - "polyfills": "polyfills.ts", - "test": "test.ts", - "tsconfig": "tsconfig.app.json", - "testTsconfig": "tsconfig.spec.json", - "prefix": "app", - "styles": [ - "styles.css", - "../node_modules/ngx-toastr/toastr.css" - ], - "scripts": [], - "environmentSource": "environments/environment.ts", - "environments": { - "dev": "environments/environment.ts", - "prod": "environments/environment.prod.ts" - } - } - ], - "e2e": { - "protractor": { - "config": "./protractor.conf.js" - } - }, - "lint": [ - { - "project": "src/tsconfig.app.json", - "exclude": "**/node_modules/**" - }, - { - "project": "src/tsconfig.spec.json", - "exclude": "**/node_modules/**" - }, - { - "project": "e2e/tsconfig.e2e.json", - "exclude": "**/node_modules/**" - } - ], - "test": { - "karma": { - "config": "./karma.conf.js" - } - }, - "defaults": { - "styleExt": "css", - "component": {} - } -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/package.json b/spring-security-anguar/client/angular5/package.json deleted file mode 100644 index 45f455d191..0000000000 --- a/spring-security-anguar/client/angular5/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "angular5", - "version": "0.0.0", - "license": "MIT", - "scripts": { - "ng": "ng", - "start": "ng serve", - "build": "ng build --prod", - "test": "ng test", - "lint": "ng lint", - "e2e": "ng e2e" - }, - "private": true, - "dependencies": { - "@angular/animations": "^5.0.0", - "@angular/common": "^5.0.0", - "@angular/compiler": "^5.0.0", - "@angular/core": "^5.0.0", - "@angular/forms": "^5.0.0", - "@angular/http": "^5.0.0", - "@angular/platform-browser": "^5.0.0", - "@angular/platform-browser-dynamic": "^5.0.0", - "@angular/router": "^5.0.0", - "core-js": "^2.4.1", - "ngx-toastr": "^8.1.1", - "rxjs": "^5.5.2", - "zone.js": "^0.8.14" - }, - "devDependencies": { - "@angular/cli": "^1.6.6", - "@angular/compiler-cli": "^5.0.0", - "@angular/language-service": "^5.0.0", - "@types/jasmine": "~2.5.53", - "@types/jasminewd2": "~2.0.2", - "@types/node": "~6.0.60", - "codelyzer": "^4.0.1", - "jasmine-core": "~2.6.2", - "jasmine-spec-reporter": "~4.1.0", - "karma": "~1.7.0", - "karma-chrome-launcher": "~2.1.1", - "karma-cli": "~1.0.1", - "karma-coverage-istanbul-reporter": "^1.2.1", - "karma-jasmine": "~1.1.0", - "karma-jasmine-html-reporter": "^0.2.2", - "protractor": "~5.1.2", - "ts-node": "~3.2.0", - "tslint": "~5.7.0", - "typescript": "~2.4.2" - } -} diff --git a/spring-security-anguar/client/angular5/src/app/app.component.html b/spring-security-anguar/client/angular5/src/app/app.component.html deleted file mode 100644 index 7f77adea7b..0000000000 --- a/spring-security-anguar/client/angular5/src/app/app.component.html +++ /dev/null @@ -1,7 +0,0 @@ -
    -
    -
    - -
    -
    -
    diff --git a/spring-security-anguar/client/angular5/src/app/app.component.ts b/spring-security-anguar/client/angular5/src/app/app.component.ts deleted file mode 100644 index 36f986c63f..0000000000 --- a/spring-security-anguar/client/angular5/src/app/app.component.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Component } from '@angular/core'; - -@Component({ - selector: 'app-root', - templateUrl: './app.component.html' -}) - -export class AppComponent { } \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/src/app/app.module.ts b/spring-security-anguar/client/angular5/src/app/app.module.ts deleted file mode 100644 index 9e840e6f13..0000000000 --- a/spring-security-anguar/client/angular5/src/app/app.module.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { NgModule } from '@angular/core'; -import { BrowserModule } from '@angular/platform-browser'; -import { FormsModule } from '@angular/forms'; -import { HttpModule } from '@angular/http'; - -// used to create fake backend - -import { AppComponent } from './app.component'; -import { routing } from './app.routing'; - -import { HomeComponent } from './home/home.component'; -import { LoginComponent } from './login/login.component'; - -@NgModule({ - imports: [ - BrowserModule, - FormsModule, - HttpModule, - routing - ], - declarations: [ - AppComponent, - HomeComponent, - LoginComponent - ], - bootstrap: [AppComponent] -}) - -export class AppModule { } \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/src/app/app.routing.ts b/spring-security-anguar/client/angular5/src/app/app.routing.ts deleted file mode 100644 index c794fc5c50..0000000000 --- a/spring-security-anguar/client/angular5/src/app/app.routing.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Routes, RouterModule } from '@angular/router'; - -import { HomeComponent } from './home/home.component'; -import { LoginComponent } from './login/login.component'; - -const appRoutes: Routes = [ - { path: '', component: HomeComponent}, - { path: 'login', component: LoginComponent }, - { path: '**', redirectTo: '' } -]; - -export const routing = RouterModule.forRoot(appRoutes); \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/src/app/home/home.component.html b/spring-security-anguar/client/angular5/src/app/home/home.component.html deleted file mode 100644 index 7ccd2c2a3a..0000000000 --- a/spring-security-anguar/client/angular5/src/app/home/home.component.html +++ /dev/null @@ -1,4 +0,0 @@ -
    -

    Hi {{userName}}!

    -

    Logout

    -
    \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/src/app/home/home.component.ts b/spring-security-anguar/client/angular5/src/app/home/home.component.ts deleted file mode 100644 index 7fe1ac4eff..0000000000 --- a/spring-security-anguar/client/angular5/src/app/home/home.component.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Component, OnInit } from '@angular/core'; -import { Http, Headers, RequestOptions } from '@angular/http'; -import 'rxjs/add/operator/map' - -@Component({ - selector:'home', - templateUrl: './home.component.html' -}) - -export class HomeComponent implements OnInit { - - userName: string; - - constructor(private http: Http) { } - - ngOnInit() { - let url = 'http://localhost:8082/user'; - - let headers:Headers = new Headers({ - 'Authorization': 'Basic ' + sessionStorage.getItem('token') - }) - let options = new RequestOptions({headers: headers}); - this.http.post(url,{}, options).map( - res => res.json(), - error => { - if(error.status == 401) - alert('Unauthorized'); - } - ).subscribe(principal => { - this.userName = principal.name; - }); - } - - logout() { - sessionStorage.setItem('token', ''); - } -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/src/app/login/login.component.html b/spring-security-anguar/client/angular5/src/app/login/login.component.html deleted file mode 100644 index d87b91a7bb..0000000000 --- a/spring-security-anguar/client/angular5/src/app/login/login.component.html +++ /dev/null @@ -1,18 +0,0 @@ -
    -

    Login

    -
    -
    - - -
    Username is required
    -
    -
    - - -
    Password is required
    -
    -
    - -
    -
    -
    diff --git a/spring-security-anguar/client/angular5/src/app/login/login.component.ts b/spring-security-anguar/client/angular5/src/app/login/login.component.ts deleted file mode 100644 index 2db8f32871..0000000000 --- a/spring-security-anguar/client/angular5/src/app/login/login.component.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Component, OnInit } from '@angular/core'; -import { Router, ActivatedRoute } from '@angular/router'; -import { Http } from '@angular/http'; - -@Component({ - selector: 'login', - templateUrl: './login.component.html' -}) - -export class LoginComponent implements OnInit { - model: any = {}; - - constructor( - private route: ActivatedRoute, - private router: Router, - private http: Http) { } - - ngOnInit() { - sessionStorage.setItem('token', ''); - } - - - login() { - let url = 'http://localhost:8082/login'; - let result = this.http.post(url, { - userName: this.model.username, - password: this.model.password - }).map(res => res.json()).subscribe(isValid => { - if (isValid) { - sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password)); - this.router.navigate(['']); - } else { - alert("Authentication failed.") - } - }); - } -} diff --git a/spring-security-anguar/client/angular5/src/index.html b/spring-security-anguar/client/angular5/src/index.html deleted file mode 100644 index c716820396..0000000000 --- a/spring-security-anguar/client/angular5/src/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - AngularCRUD - - - - - - - - - \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/src/main.ts b/spring-security-anguar/client/angular5/src/main.ts deleted file mode 100644 index 49db98ae89..0000000000 --- a/spring-security-anguar/client/angular5/src/main.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - -import { AppModule } from './app/app.module'; - -platformBrowserDynamic().bootstrapModule(AppModule); \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/src/polyfills.ts b/spring-security-anguar/client/angular5/src/polyfills.ts deleted file mode 100644 index a4984ced57..0000000000 --- a/spring-security-anguar/client/angular5/src/polyfills.ts +++ /dev/null @@ -1,68 +0,0 @@ -/** - * This file includes polyfills needed by Angular and is loaded before the app. - * You can add your own extra polyfills to this file. - * - * This file is divided into 2 sections: - * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. - * 2. Application imports. Files imported after ZoneJS that should be loaded before your main - * file. - * - * The current setup is for so-called "evergreen" browsers; the last versions of browsers that - * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), - * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. - * - * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html - */ - -/*************************************************************************************************** - * BROWSER POLYFILLS - */ - -/** IE9, IE10 and IE11 requires all of the following polyfills. **/ -// import 'core-js/es6/symbol'; -// import 'core-js/es6/object'; -// import 'core-js/es6/function'; -// import 'core-js/es6/parse-int'; -// import 'core-js/es6/parse-float'; -// import 'core-js/es6/number'; -// import 'core-js/es6/math'; -// import 'core-js/es6/string'; -// import 'core-js/es6/date'; -// import 'core-js/es6/array'; -// import 'core-js/es6/regexp'; -// import 'core-js/es6/map'; -// import 'core-js/es6/weak-map'; -// import 'core-js/es6/set'; -/** IE10 and IE11 requires the following for NgClass support on SVG elements */ -// import 'classlist.js'; // Run `npm install --save classlist.js`. -/** Evergreen browsers require these. **/ -import 'core-js/es6/reflect'; -import 'core-js/es7/reflect'; - - -/** - * Required to support Web Animations `@angular/animation`. - * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation - **/ -// import 'web-animations-js'; // Run `npm install --save web-animations-js`. - - -/*************************************************************************************************** - * Zone JS is required by Angular itself. - */ -import 'zone.js/dist/zone'; // Included with Angular CLI. - - -/*************************************************************************************************** - * APPLICATION IMPORTS - */ - -/** - * Date, currency, decimal and percent pipes. - * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 - */ -// import 'intl'; // Run `npm install --save intl`. -/** - * Need to import at least one locale-data with intl. - */ -// import 'intl/locale-data/jsonp/en'; \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/src/styles.css b/spring-security-anguar/client/angular5/src/styles.css deleted file mode 100644 index cdd2d591d8..0000000000 --- a/spring-security-anguar/client/angular5/src/styles.css +++ /dev/null @@ -1,7 +0,0 @@ -a { - cursor: pointer; -} - -.help-block { - font-size: 12px; -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/src/tsconfig.app.json b/spring-security-anguar/client/angular5/src/tsconfig.app.json deleted file mode 100644 index 213ce42a1b..0000000000 --- a/spring-security-anguar/client/angular5/src/tsconfig.app.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/app", - "baseUrl": "./", - "module": "es2015", - "types": [] - }, - "exclude": [ - "test.ts", - "**/*.spec.ts" - ] -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/tsconfig.json b/spring-security-anguar/client/angular5/tsconfig.json deleted file mode 100644 index 0fdb5c817d..0000000000 --- a/spring-security-anguar/client/angular5/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compileOnSave": false, - "compilerOptions": { - "outDir": "./dist/out-tsc", - "sourceMap": true, - "declaration": false, - "moduleResolution": "node", - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es5", - "typeRoots": [ - "node_modules/@types" - ], - "lib": [ - "es2017", - "dom" - ] - } -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular5/tslint.json b/spring-security-anguar/client/angular5/tslint.json deleted file mode 100644 index 1c1d53b0d9..0000000000 --- a/spring-security-anguar/client/angular5/tslint.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "rulesDirectory": [ - "node_modules/codelyzer" - ], - "rules": { - "arrow-return-shorthand": true, - "callable-types": true, - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "curly": true, - "deprecation": { - "severity": "warn" - }, - "eofline": true, - "forin": true, - "import-blacklist": [ - true, - "rxjs", - "rxjs/Rx" - ], - "import-spacing": true, - "indent": [ - true, - "spaces" - ], - "interface-over-type-literal": true, - "label-position": true, - "max-line-length": [ - true, - 140 - ], - "member-access": false, - "member-ordering": [ - true, - { - "order": [ - "static-field", - "instance-field", - "static-method", - "instance-method" - ] - } - ], - "no-arg": true, - "no-bitwise": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], - "no-construct": true, - "no-debugger": true, - "no-duplicate-super": true, - "no-empty": false, - "no-empty-interface": true, - "no-eval": true, - "no-inferrable-types": [ - true, - "ignore-params" - ], - "no-misused-new": true, - "no-non-null-assertion": true, - "no-shadowed-variable": true, - "no-string-literal": false, - "no-string-throw": true, - "no-switch-case-fall-through": true, - "no-trailing-whitespace": true, - "no-unnecessary-initializer": true, - "no-unused-expression": true, - "no-use-before-declare": true, - "no-var-keyword": true, - "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], - "prefer-const": true, - "quotemark": [ - true, - "single" - ], - "radix": true, - "semicolon": [ - true, - "always" - ], - "triple-equals": [ - true, - "allow-null-check" - ], - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - } - ], - "typeof-compare": true, - "unified-signatures": true, - "variable-name": false, - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ], - "directive-selector": [ - true, - "attribute", - "app", - "camelCase" - ], - "component-selector": [ - true, - "element", - "app", - "kebab-case" - ], - "no-output-on-prefix": true, - "use-input-property-decorator": true, - "use-output-property-decorator": true, - "use-host-property-decorator": true, - "no-input-rename": true, - "no-output-rename": true, - "use-life-cycle-interface": true, - "use-pipe-transform-interface": true, - "component-class-suffix": true, - "directive-class-suffix": true - } -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/angular.json b/spring-security-anguar/client/angular6/angular.json deleted file mode 100644 index 0168c58817..0000000000 --- a/spring-security-anguar/client/angular6/angular.json +++ /dev/null @@ -1,127 +0,0 @@ -{ - "$schema": "./node_modules/@angular/cli/lib/config/schema.json", - "version": 1, - "newProjectRoot": "projects", - "projects": { - "angular6-login": { - "root": "", - "sourceRoot": "src", - "projectType": "application", - "prefix": "app", - "schematics": {}, - "architect": { - "build": { - "builder": "@angular-devkit/build-angular:browser", - "options": { - "outputPath": "dist/angular6-login", - "index": "src/index.html", - "main": "src/main.ts", - "polyfills": "src/polyfills.ts", - "tsConfig": "src/tsconfig.app.json", - "assets": [ - "src/favicon.ico", - "src/assets" - ], - "styles": [ - "src/styles.css" - ], - "scripts": [] - }, - "configurations": { - "production": { - "fileReplacements": [ - { - "replace": "src/environments/environment.ts", - "with": "src/environments/environment.prod.ts" - } - ], - "optimization": true, - "outputHashing": "all", - "sourceMap": false, - "extractCss": true, - "namedChunks": false, - "aot": true, - "extractLicenses": true, - "vendorChunk": false, - "buildOptimizer": true - } - } - }, - "serve": { - "builder": "@angular-devkit/build-angular:dev-server", - "options": { - "browserTarget": "angular6-login:build" - }, - "configurations": { - "production": { - "browserTarget": "angular6-login:build:production" - } - } - }, - "extract-i18n": { - "builder": "@angular-devkit/build-angular:extract-i18n", - "options": { - "browserTarget": "angular6-login:build" - } - }, - "test": { - "builder": "@angular-devkit/build-angular:karma", - "options": { - "main": "src/test.ts", - "polyfills": "src/polyfills.ts", - "tsConfig": "src/tsconfig.spec.json", - "karmaConfig": "src/karma.conf.js", - "styles": [ - "src/styles.css" - ], - "scripts": [], - "assets": [ - "src/favicon.ico", - "src/assets" - ] - } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": [ - "src/tsconfig.app.json", - "src/tsconfig.spec.json" - ], - "exclude": [ - "**/node_modules/**" - ] - } - } - } - }, - "angular6-login-e2e": { - "root": "e2e/", - "projectType": "application", - "architect": { - "e2e": { - "builder": "@angular-devkit/build-angular:protractor", - "options": { - "protractorConfig": "e2e/protractor.conf.js", - "devServerTarget": "angular6-login:serve" - }, - "configurations": { - "production": { - "devServerTarget": "angular6-login:serve:production" - } - } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": "e2e/tsconfig.e2e.json", - "exclude": [ - "**/node_modules/**" - ] - } - } - } - } - }, - "defaultProject": "angular6-login" -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/package.json b/spring-security-anguar/client/angular6/package.json deleted file mode 100644 index a0adcd03f3..0000000000 --- a/spring-security-anguar/client/angular6/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "angular6-login", - "version": "0.0.0", - "scripts": { - "ng": "ng", - "start": "ng serve", - "build": "ng build", - "test": "ng test", - "lint": "ng lint", - "e2e": "ng e2e" - }, - "private": true, - "dependencies": { - "@angular/animations": "^6.0.3", - "@angular/common": "^6.0.3", - "@angular/compiler": "^6.0.3", - "@angular/core": "^6.0.3", - "@angular/forms": "^6.0.3", - "@angular/http": "^6.0.3", - "@angular/platform-browser": "^6.0.3", - "@angular/platform-browser-dynamic": "^6.0.3", - "@angular/router": "^6.0.3", - "core-js": "^2.5.4", - "rxjs": "^6.0.0", - "zone.js": "^0.8.26" - }, - "devDependencies": { - "@angular/compiler-cli": "^6.0.3", - "@angular-devkit/build-angular": "~0.6.8", - "typescript": "~2.7.2", - "@angular/cli": "~6.0.8", - "@angular/language-service": "^6.0.3", - "@types/jasmine": "~2.8.6", - "@types/jasminewd2": "~2.0.3", - "@types/node": "~8.9.4", - "codelyzer": "~4.2.1", - "jasmine-core": "~2.99.1", - "jasmine-spec-reporter": "~4.2.1", - "karma": "~1.7.1", - "karma-chrome-launcher": "~2.2.0", - "karma-coverage-istanbul-reporter": "~2.0.0", - "karma-jasmine": "~1.1.1", - "karma-jasmine-html-reporter": "^0.2.2", - "protractor": "~5.3.0", - "ts-node": "~5.0.1", - "tslint": "~5.9.1" - } -} diff --git a/spring-security-anguar/client/angular6/src/app/app.component.html b/spring-security-anguar/client/angular6/src/app/app.component.html deleted file mode 100644 index 6bf00f3018..0000000000 --- a/spring-security-anguar/client/angular6/src/app/app.component.html +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/spring-security-anguar/client/angular6/src/app/app.component.ts b/spring-security-anguar/client/angular6/src/app/app.component.ts deleted file mode 100644 index 36f986c63f..0000000000 --- a/spring-security-anguar/client/angular6/src/app/app.component.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Component } from '@angular/core'; - -@Component({ - selector: 'app-root', - templateUrl: './app.component.html' -}) - -export class AppComponent { } \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/src/app/app.module.ts b/spring-security-anguar/client/angular6/src/app/app.module.ts deleted file mode 100644 index 4f9a792e19..0000000000 --- a/spring-security-anguar/client/angular6/src/app/app.module.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { NgModule } from '@angular/core'; -import { BrowserModule } from '@angular/platform-browser'; -import { FormsModule } from '@angular/forms'; -import { HttpClientModule } from '@angular/common/http'; - -import { AppComponent } from './app.component'; -import { routing } from './app.routing'; - -import { HomeComponent } from './home/home.component'; -import { LoginComponent } from './login/login.component'; - -@NgModule({ - imports: [ - BrowserModule, - FormsModule, - HttpClientModule, - routing - ], - declarations: [ - AppComponent, - HomeComponent, - LoginComponent - ], - bootstrap: [AppComponent] -}) - -export class AppModule { } \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/src/app/app.routing.ts b/spring-security-anguar/client/angular6/src/app/app.routing.ts deleted file mode 100644 index e5f5e04aa8..0000000000 --- a/spring-security-anguar/client/angular6/src/app/app.routing.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Routes, RouterModule } from '@angular/router'; -import { HomeComponent } from './home/home.component'; -import { LoginComponent } from './login/login.component'; - -const appRoutes: Routes = [ - { path: '', component: HomeComponent }, - { path: 'login', component: LoginComponent }, - { path: '**', redirectTo: '' } -]; - -export const routing = RouterModule.forRoot(appRoutes); \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/src/app/home/home.component.html b/spring-security-anguar/client/angular6/src/app/home/home.component.html deleted file mode 100644 index 7ccd2c2a3a..0000000000 --- a/spring-security-anguar/client/angular6/src/app/home/home.component.html +++ /dev/null @@ -1,4 +0,0 @@ -
    -

    Hi {{userName}}!

    -

    Logout

    -
    \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/src/app/home/home.component.ts b/spring-security-anguar/client/angular6/src/app/home/home.component.ts deleted file mode 100644 index 6c9fcfd97f..0000000000 --- a/spring-security-anguar/client/angular6/src/app/home/home.component.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Component, OnInit } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; -import { Observable, throwError } from 'rxjs'; -import { catchError, map, tap} from 'rxjs/operators'; -@Component({ - selector: 'home', - templateUrl: './home.component.html' -}) - -export class HomeComponent implements OnInit { - - userName: string; - - constructor(private http: HttpClient) { } - - ngOnInit() { - let url = 'http://localhost:8082/user'; - - let headers: HttpHeaders = new HttpHeaders({ - 'Authorization': 'Basic ' + sessionStorage.getItem('token') - }); - - let options = { headers: headers }; - this.http.post>(url, {}, options). - subscribe(principal => { - this.userName = principal['name']; - }, - error => { - if(error.status == 401) - alert('Unauthorized'); - } - ); - } - - logout() { - sessionStorage.setItem('token', ''); - } - private handleError(error: HttpErrorResponse) { - if (error.error instanceof ErrorEvent) { - console.error('An error occurred:', error.error.message); - } else { - console.error( - `Backend returned code ${error.status}, ` + - `body was: ${error.error}`); - } - return throwError( - 'Something bad happened; please try again later.'); - }; -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/src/app/login/login.component.html b/spring-security-anguar/client/angular6/src/app/login/login.component.html deleted file mode 100644 index 4291206469..0000000000 --- a/spring-security-anguar/client/angular6/src/app/login/login.component.html +++ /dev/null @@ -1,15 +0,0 @@ -
    -
    - - -
    Username is required
    -
    -
    - - -
    Password is required
    -
    -
    - -
    -
    \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/src/app/login/login.component.ts b/spring-security-anguar/client/angular6/src/app/login/login.component.ts deleted file mode 100644 index 27af9ebba5..0000000000 --- a/spring-security-anguar/client/angular6/src/app/login/login.component.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { Component, OnInit } from '@angular/core'; -import { Router, ActivatedRoute } from '@angular/router'; -import { HttpClient } from '@angular/common/http'; -import { Observable } from 'rxjs'; - -@Component({ - selector: 'login', - templateUrl: './login.component.html' -}) - -export class LoginComponent implements OnInit { - - model: any = {}; - - constructor( - private route: ActivatedRoute, - private router: Router, - private http: HttpClient - ) { } - - ngOnInit() { - sessionStorage.setItem('token', ''); - } - - login() { - let url = 'http://localhost:8082/login'; - this.http.post>(url, { - userName: this.model.username, - password: this.model.password - }).subscribe(isValid => { - if (isValid) { - sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password)); - this.router.navigate(['']); - } else { - alert("Authentication failed.") - } - }); - } -} diff --git a/spring-security-anguar/client/angular6/src/index.html b/spring-security-anguar/client/angular6/src/index.html deleted file mode 100644 index c716820396..0000000000 --- a/spring-security-anguar/client/angular6/src/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - AngularCRUD - - - - - - - - - \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/src/main.ts b/spring-security-anguar/client/angular6/src/main.ts deleted file mode 100644 index 49db98ae89..0000000000 --- a/spring-security-anguar/client/angular6/src/main.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - -import { AppModule } from './app/app.module'; - -platformBrowserDynamic().bootstrapModule(AppModule); \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/src/polyfills.ts b/spring-security-anguar/client/angular6/src/polyfills.ts deleted file mode 100644 index a4984ced57..0000000000 --- a/spring-security-anguar/client/angular6/src/polyfills.ts +++ /dev/null @@ -1,68 +0,0 @@ -/** - * This file includes polyfills needed by Angular and is loaded before the app. - * You can add your own extra polyfills to this file. - * - * This file is divided into 2 sections: - * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. - * 2. Application imports. Files imported after ZoneJS that should be loaded before your main - * file. - * - * The current setup is for so-called "evergreen" browsers; the last versions of browsers that - * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), - * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. - * - * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html - */ - -/*************************************************************************************************** - * BROWSER POLYFILLS - */ - -/** IE9, IE10 and IE11 requires all of the following polyfills. **/ -// import 'core-js/es6/symbol'; -// import 'core-js/es6/object'; -// import 'core-js/es6/function'; -// import 'core-js/es6/parse-int'; -// import 'core-js/es6/parse-float'; -// import 'core-js/es6/number'; -// import 'core-js/es6/math'; -// import 'core-js/es6/string'; -// import 'core-js/es6/date'; -// import 'core-js/es6/array'; -// import 'core-js/es6/regexp'; -// import 'core-js/es6/map'; -// import 'core-js/es6/weak-map'; -// import 'core-js/es6/set'; -/** IE10 and IE11 requires the following for NgClass support on SVG elements */ -// import 'classlist.js'; // Run `npm install --save classlist.js`. -/** Evergreen browsers require these. **/ -import 'core-js/es6/reflect'; -import 'core-js/es7/reflect'; - - -/** - * Required to support Web Animations `@angular/animation`. - * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation - **/ -// import 'web-animations-js'; // Run `npm install --save web-animations-js`. - - -/*************************************************************************************************** - * Zone JS is required by Angular itself. - */ -import 'zone.js/dist/zone'; // Included with Angular CLI. - - -/*************************************************************************************************** - * APPLICATION IMPORTS - */ - -/** - * Date, currency, decimal and percent pipes. - * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 - */ -// import 'intl'; // Run `npm install --save intl`. -/** - * Need to import at least one locale-data with intl. - */ -// import 'intl/locale-data/jsonp/en'; \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/src/styles.css b/spring-security-anguar/client/angular6/src/styles.css deleted file mode 100644 index cdd2d591d8..0000000000 --- a/spring-security-anguar/client/angular6/src/styles.css +++ /dev/null @@ -1,7 +0,0 @@ -a { - cursor: pointer; -} - -.help-block { - font-size: 12px; -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/src/tsconfig.app.json b/spring-security-anguar/client/angular6/src/tsconfig.app.json deleted file mode 100644 index 213ce42a1b..0000000000 --- a/spring-security-anguar/client/angular6/src/tsconfig.app.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/app", - "baseUrl": "./", - "module": "es2015", - "types": [] - }, - "exclude": [ - "test.ts", - "**/*.spec.ts" - ] -} \ No newline at end of file diff --git a/spring-security-anguar/client/angular6/tsconfig.json b/spring-security-anguar/client/angular6/tsconfig.json deleted file mode 100644 index ef44e2862b..0000000000 --- a/spring-security-anguar/client/angular6/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compileOnSave": false, - "compilerOptions": { - "baseUrl": "./", - "outDir": "./dist/out-tsc", - "sourceMap": true, - "declaration": false, - "moduleResolution": "node", - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es5", - "typeRoots": [ - "node_modules/@types" - ], - "lib": [ - "es2017", - "dom" - ] - } -} diff --git a/spring-security-anguar/client/angular6/tslint.json b/spring-security-anguar/client/angular6/tslint.json deleted file mode 100644 index 3ea984c776..0000000000 --- a/spring-security-anguar/client/angular6/tslint.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "rulesDirectory": [ - "node_modules/codelyzer" - ], - "rules": { - "arrow-return-shorthand": true, - "callable-types": true, - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "curly": true, - "deprecation": { - "severity": "warn" - }, - "eofline": true, - "forin": true, - "import-blacklist": [ - true, - "rxjs/Rx" - ], - "import-spacing": true, - "indent": [ - true, - "spaces" - ], - "interface-over-type-literal": true, - "label-position": true, - "max-line-length": [ - true, - 140 - ], - "member-access": false, - "member-ordering": [ - true, - { - "order": [ - "static-field", - "instance-field", - "static-method", - "instance-method" - ] - } - ], - "no-arg": true, - "no-bitwise": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], - "no-construct": true, - "no-debugger": true, - "no-duplicate-super": true, - "no-empty": false, - "no-empty-interface": true, - "no-eval": true, - "no-inferrable-types": [ - true, - "ignore-params" - ], - "no-misused-new": true, - "no-non-null-assertion": true, - "no-shadowed-variable": true, - "no-string-literal": false, - "no-string-throw": true, - "no-switch-case-fall-through": true, - "no-trailing-whitespace": true, - "no-unnecessary-initializer": true, - "no-unused-expression": true, - "no-use-before-declare": true, - "no-var-keyword": true, - "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], - "prefer-const": true, - "quotemark": [ - true, - "single" - ], - "radix": true, - "semicolon": [ - true, - "always" - ], - "triple-equals": [ - true, - "allow-null-check" - ], - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - } - ], - "unified-signatures": true, - "variable-name": false, - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ], - "no-output-on-prefix": true, - "use-input-property-decorator": true, - "use-output-property-decorator": true, - "use-host-property-decorator": true, - "no-input-rename": true, - "no-output-rename": true, - "use-life-cycle-interface": true, - "use-pipe-transform-interface": true, - "component-class-suffix": true, - "directive-class-suffix": true - } -} diff --git a/spring-security-anguar/server/pom.xml b/spring-security-anguar/server/pom.xml deleted file mode 100644 index 39de129c87..0000000000 --- a/spring-security-anguar/server/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-security-angular - 0.0.1-SNAPSHOT - jar - spring-boot-security-rest - Spring Boot Security REST - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - - - - - - org.springframework.boot - spring-boot-dependencies - 1.5.9.RELEASE - pom - import - - - - - - - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - UTF-8 - UTF-8 - - - diff --git a/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/SpringBootSecurityApplication.java b/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/SpringBootSecurityApplication.java deleted file mode 100644 index 681c7590a8..0000000000 --- a/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/SpringBootSecurityApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.springbootsecurityrest.basicauth; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurityrest") -@EnableAutoConfiguration -public class SpringBootSecurityApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringBootSecurityApplication.class, args); - } -} diff --git a/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/controller/UserController.java b/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/controller/UserController.java deleted file mode 100644 index 825290ff2d..0000000000 --- a/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/controller/UserController.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.springbootsecurityrest.controller; - -import java.security.Principal; -import java.util.Base64; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.springbootsecurityrest.vo.User; - -@RestController -@CrossOrigin -public class UserController { - - @RequestMapping("/login") - public boolean login(@RequestBody User user) { - if(user.getUserName().equals("user") && user.getPassword().equals("password")) { - return true; - } - return false; - } - - @RequestMapping("/user") - public Principal user(HttpServletRequest request) { - String authToken = request.getHeader("Authorization").substring("Basic".length()).trim(); - return () -> new String(Base64.getDecoder().decode(authToken)).split(":")[0]; - } -} diff --git a/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/vo/User.java b/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/vo/User.java deleted file mode 100644 index 0eda5ce9ec..0000000000 --- a/spring-security-anguar/server/src/main/java/com/baeldung/springbootsecurityrest/vo/User.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.springbootsecurityrest.vo; - - -public class User { - - private String userName; - private String password; - - 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/spring-security-anguar/server/src/main/resources/application.properties b/spring-security-anguar/server/src/main/resources/application.properties deleted file mode 100644 index 565d97a7b0..0000000000 --- a/spring-security-anguar/server/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration -#security.user.password=password -#security.oauth2.client.client-id=client -#security.oauth2.client.client-secret=secret -server.port=8082 diff --git a/spring-security-angular/README.md b/spring-security-angular/README.md new file mode 100644 index 0000000000..80312c4bab --- /dev/null +++ b/spring-security-angular/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring Security Login Page with Angular](https://www.baeldung.com/spring-security-login-angular) diff --git a/spring-security-angular/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-angular/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8c62ac5e91 --- /dev/null +++ b/spring-security-angular/server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.springbootsecurityrest.basicauth.SpringBootSecurityApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootSecurityApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-cache-control/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-cache-control/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c047fc6210 --- /dev/null +++ b/spring-security-cache-control/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.cachecontrol.AppRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AppRunner.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..66243ef00d --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +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 = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-core/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-core/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..5698afa417 --- /dev/null +++ b/spring-security-core/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = App.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/README.MD b/spring-security-mvc-boot/README.MD index 32976b0896..6f01bfdc65 100644 --- a/spring-security-mvc-boot/README.MD +++ b/spring-security-mvc-boot/README.MD @@ -1,7 +1,7 @@ -###The Course +### The Course The "REST With Spring" Classes: http://github.learnspringsecurity.com -###Relevant Articles: +### Relevant Articles: - [A Custom Security Expression with Spring Security](http://www.baeldung.com/spring-security-create-new-custom-security-expression) - [Custom AccessDecisionVoters in Spring Security](http://www.baeldung.com/spring-security-custom-voter) - [Spring Security: Authentication with a Database-backed UserDetailsService](http://www.baeldung.com/spring-security-authentication-with-a-database) @@ -9,3 +9,6 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Multiple Entry Points in Spring Security](http://www.baeldung.com/spring-security-multiple-entry-points) - [Multiple Authentication Providers in Spring Security](http://www.baeldung.com/spring-security-multiple-auth-providers) - [Granted Authority Versus Role in Spring Security](http://www.baeldung.com/spring-security-granted-authority-vs-role) +- [Spring Data with Spring Security](https://www.baeldung.com/spring-data-security) +- [Spring Security – Whitelist IP Range](https://www.baeldung.com/spring-security-whitelist-ip-range) +- [Find the Registered Spring Security Filters](https://www.baeldung.com/spring-security-registered-filters) diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index a894c5713a..4090beab99 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -42,6 +42,10 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.security + spring-security-data + com.h2database h2 diff --git a/spring-data-spring-security/src/main/java/com/baeldung/AppConfig.java b/spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java similarity index 100% rename from spring-data-spring-security/src/main/java/com/baeldung/AppConfig.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java diff --git a/spring-data-spring-security/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-data-spring-security/src/main/java/com/baeldung/SpringSecurityConfig.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java diff --git a/spring-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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-data-spring-security/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/src/main/java/org/baeldung/ip/IpApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java new file mode 100644 index 0000000000..fd270686a2 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java @@ -0,0 +1,12 @@ +package org.baeldung.ip; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class IpApplication extends SpringBootServletInitializer { + public static void main(String[] args) { + SpringApplication.run(IpApplication.class, args); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java new file mode 100644 index 0000000000..078dd81259 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java @@ -0,0 +1,53 @@ +package org.baeldung.ip.config; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.springframework.security.authentication.AuthenticationProvider; +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.web.authentication.WebAuthenticationDetails; +import org.springframework.stereotype.Component; + +@Component +public class CustomIpAuthenticationProvider implements AuthenticationProvider { + + Set whitelist = new HashSet(); + + public CustomIpAuthenticationProvider() { + super(); + whitelist.add("11.11.11.11"); + whitelist.add("127.0.0.1"); + } + + @Override + public Authentication authenticate(Authentication auth) throws AuthenticationException { + WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails(); + String userIp = details.getRemoteAddress(); + if(! whitelist.contains(userIp)){ + throw new BadCredentialsException("Invalid IP Address"); + } + final String name = auth.getName(); + final String password = auth.getCredentials().toString(); + + if (name.equals("john") && password.equals("123")) { + List authorities =new ArrayList(); + authorities.add(new SimpleGrantedAuthority("ROLE_USER")); + return new UsernamePasswordAuthenticationToken(name, password, authorities); + } + else{ + throw new BadCredentialsException("Invalid username or password"); + } + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java new file mode 100644 index 0000000000..3a8032a734 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java @@ -0,0 +1,36 @@ +package org.baeldung.ip.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity//(debug = true) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private CustomIpAuthenticationProvider authenticationProvider; + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("john").password("{noop}123").authorities("ROLE_USER"); + // auth.authenticationProvider(authenticationProvider); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() +// .antMatchers("/foos/**").hasIpAddress("11.11.11.11") + .antMatchers("/foos/**").access("isAuthenticated() and hasIpAddress('11.11.11.11')") + .anyRequest().authenticated() + .and().formLogin().permitAll() + .and().csrf().disable(); + // @formatter:on + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java new file mode 100644 index 0000000000..1d22ca4c67 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java @@ -0,0 +1,9 @@ +package org.baeldung.ip.config; + + +//@Configuration +//@EnableWebSecurity +//@ImportResource({ "classpath:spring-security-ip.xml" }) +public class SecurityXmlConfig { + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java new file mode 100644 index 0000000000..940194c421 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java @@ -0,0 +1,42 @@ +package org.baeldung.ip.web; + +import java.util.List; + +import javax.servlet.Filter; +import javax.servlet.http.HttpServletRequest; + +import org.baeldung.custom.persistence.model.Foo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class MainController { + + @Autowired + @Qualifier("springSecurityFilterChain") + private Filter springSecurityFilterChain; + + @RequestMapping(method = RequestMethod.GET, value = "/filters") + @ResponseBody + public void getFilters() { + FilterChainProxy filterChainProxy = (FilterChainProxy) springSecurityFilterChain; + List list = filterChainProxy.getFilterChains(); + list.stream() + .flatMap(chain -> chain.getFilters().stream()) + .forEach(filter -> System.out.println(filter.getClass())); + } + + @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @ResponseBody + public Foo findById(@PathVariable final long id, HttpServletRequest request) { + return new Foo("Sample"); + } + +} diff --git a/spring-security-mvc-boot/src/main/resources/application.properties b/spring-security-mvc-boot/src/main/resources/application.properties index f015086a4f..25eac743d1 100644 --- a/spring-security-mvc-boot/src/main/resources/application.properties +++ b/spring-security-mvc-boot/src/main/resources/application.properties @@ -6,4 +6,7 @@ spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.database=H2 spring.jpa.show-sql=false -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect + + +#logging.level.org.springframework.security.web.FilterChainProxy=DEBUG \ No newline at end of file diff --git a/spring-data-spring-security/src/main/resources/persistence-h2.properties b/spring-security-mvc-boot/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-data-spring-security/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/src/main/resources/spring-security-ip.xml b/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml new file mode 100644 index 0000000000..31796ad134 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + diff --git a/spring-data-spring-security/src/test/java/com/baeldung/relationships/SpringDataWithSecurityTest.java b/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java similarity index 95% rename from spring-data-spring-security/src/test/java/com/baeldung/relationships/SpringDataWithSecurityTest.java rename to spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java index dbbfe7e85e..8207363a70 100644 --- a/spring-data-spring-security/src/test/java/com/baeldung/relationships/SpringDataWithSecurityTest.java +++ b/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java @@ -36,7 +36,7 @@ import com.baeldung.util.DummyContentUtil; @WebAppConfiguration @ContextConfiguration @DirtiesContext -public class SpringDataWithSecurityTest { +public class SpringDataWithSecurityUnitTest { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); @Autowired private ServletContext servletContext; @@ -50,8 +50,8 @@ public class SpringDataWithSecurityTest { ctx.refresh(); userRepository = ctx.getBean(UserRepository.class); tweetRepository = ctx.getBean(TweetRepository.class); - List appUsers = (List) userRepository.save(DummyContentUtil.generateDummyUsers()); - tweetRepository.save(DummyContentUtil.generateDummyTweets(appUsers)); + List appUsers = (List) userRepository.saveAll(DummyContentUtil.generateDummyUsers()); + tweetRepository.saveAll(DummyContentUtil.generateDummyTweets(appUsers)); } @AfterClass diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java new file mode 100644 index 0000000000..e12e2f87b0 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java @@ -0,0 +1,27 @@ +package org.baeldung.web; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +import org.junit.Test; + + +public class IpLiveTest { + + @Test + public void givenUser_whenGetHomePage_thenOK() { + final Response response = RestAssured.given().auth().form("john", "123").get("http://localhost:8082/"); + assertEquals(200, response.getStatusCode()); + assertTrue(response.asString().contains("Welcome")); + } + + @Test + public void givenUserWithWrongIP_whenGetFooById_thenForbidden() { + final Response response = RestAssured.given().auth().form("john", "123").get("http://localhost:8082/foos/1"); + assertEquals(403, response.getStatusCode()); + assertTrue(response.asString().contains("Forbidden")); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-custom/src/main/resources/logback.xml b/spring-security-mvc-custom/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-custom/src/main/resources/logback.xml +++ b/spring-security-mvc-custom/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9e74e83a53 --- /dev/null +++ b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +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.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index 2d3f1a3a00..33b3b5ff31 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -1,8 +1,6 @@ 4.0.0 - - com.baeldung spring-security-mvc-digest-auth 0.1-SNAPSHOT spring-security-mvc-digest-auth @@ -91,12 +89,6 @@ ${spring.version} - - org.springframework - spring-web - ${spring.version} - - diff --git a/spring-security-mvc-digest-auth/src/main/resources/logback.xml b/spring-security-mvc-digest-auth/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-digest-auth/src/main/resources/logback.xml +++ b/spring-security-mvc-digest-auth/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a4a85a8fa2 --- /dev/null +++ b/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.ClientConfig; +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +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.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { ClientConfig.class, MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-ldap/src/main/resources/logback.xml b/spring-security-mvc-ldap/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-ldap/src/main/resources/logback.xml +++ b/spring-security-mvc-ldap/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0b701e9acf --- /dev/null +++ b/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleLDAPApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-login/src/main/resources/logback.xml b/spring-security-mvc-login/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-login/src/main/resources/logback.xml +++ b/spring-security-mvc-login/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..1d7f9ae497 --- /dev/null +++ b/spring-security-mvc-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.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.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index 2add895ecb..8b15e658e8 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -133,6 +133,14 @@ guava ${guava.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-security-mvc-persisted-remember-me/src/main/resources/logback.xml b/spring-security-mvc-persisted-remember-me/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/resources/logback.xml +++ b/spring-security-mvc-persisted-remember-me/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f1df880862 --- /dev/null +++ b/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.PersistenceConfig; +import org.baeldung.spring.SecurityConfig; +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.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, PersistenceConfig.class, SecurityConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index 7ffbd76aac..85c8475657 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -113,6 +113,14 @@ metrics-core ${codahale.metrics.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-security-mvc-session/src/main/resources/logback.xml b/spring-security-mvc-session/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-mvc-session/src/main/resources/logback.xml +++ b/spring-security-mvc-session/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..9e74e83a53 --- /dev/null +++ b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +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.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-socket/README.md b/spring-security-mvc-socket/README.md index 5ae9d4f4cd..6c2ad7b985 100644 --- a/spring-security-mvc-socket/README.md +++ b/spring-security-mvc-socket/README.md @@ -1,2 +1,10 @@ +To build the project, run the command: mvn clean install. This will build a war file in the target folder that you can deploye on a server like Tomcat. + +Alternatively, run the project from an IDE. + +To login, use credentials from the data.sql file in src/main/resource, eg: user/password. + + ### Relevant Articles: - [Intro to Security and WebSockets](http://www.baeldung.com/spring-security-websockets) +- [Spring WebSockets: Build an User Chat](https://www.baeldung.com/spring-websockets-send-message-to-user) diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index 1f75becc98..d1b8365077 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-spring-5 + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring-5 + ../parent-spring-4 @@ -148,10 +148,18 @@ jackson-annotations ${jackson.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + - + org.apache.tomcat.maven @@ -171,15 +179,16 @@ - spring-security-mvc-socket 5.2.10.Final + 4.2.3.RELEASE 1.11.3.RELEASE 1.4.196 1.2.3 + 2.8.7 \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/Constants.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/Constants.java new file mode 100644 index 0000000000..77bcf7f343 --- /dev/null +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/Constants.java @@ -0,0 +1,8 @@ +package com.baeldung.springsecuredsockets; + +public class Constants { + public static final String SECURED_CHAT_HISTORY = "/secured/history"; + public static final String SECURED_CHAT = "/secured/chat"; + public static final String SECURED_CHAT_ROOM = "/secured/room"; + public static final String SECURED_CHAT_SPECIFIC_USER = "/secured/user/queue/specific-user"; +} diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java index 49b7ab2ff8..afb1970b25 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java @@ -9,7 +9,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.resource.PathResourceResolver; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.UrlBasedViewResolver; @@ -20,7 +20,7 @@ import java.sql.SQLException; @EnableJpaRepositories @ComponentScan("com.baeldung.springsecuredsockets") @Import({ SecurityConfig.class, DataStoreConfig.class, SocketBrokerConfig.class, SocketSecurityConfig.class }) -public class AppConfig implements WebMvcConfigurer { +public class AppConfig extends WebMvcConfigurerAdapter { public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java index d7b57d1829..be00662e3e 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java @@ -88,7 +88,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { .authorizeRequests() .antMatchers("/", "/index", "/authenticate") .permitAll() - .antMatchers("/secured/**/**", "/secured/socket", "/secured/success") + .antMatchers("/secured/**/**", "/secured/**/**/**", "/secured/socket", "/secured/success") .authenticated() .anyRequest().authenticated() .and() diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java index 941cac8392..9b19de7b5a 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java @@ -1,27 +1,33 @@ package com.baeldung.springsecuredsockets.config; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_HISTORY; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_ROOM; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_SPECIFIC_USER; + import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; +import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; -import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; - @Configuration @EnableWebSocketMessageBroker @ComponentScan("com.baeldung.springsecuredsockets.controllers") -public class SocketBrokerConfig implements WebSocketMessageBrokerConfigurer { +public class SocketBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { - config.enableSimpleBroker("/secured/history"); + config.enableSimpleBroker(SECURED_CHAT_HISTORY, SECURED_CHAT_SPECIFIC_USER); config.setApplicationDestinationPrefixes("/spring-security-mvc-socket"); + config.setUserDestinationPrefix("/secured/user"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { - registry.addEndpoint("/secured/chat").withSockJS(); + registry.addEndpoint(SECURED_CHAT_ROOM).withSockJS(); + registry.addEndpoint(SECURED_CHAT).withSockJS(); } } diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketSecurityConfig.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketSecurityConfig.java index a37dfb7672..c833e70d47 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketSecurityConfig.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/config/SocketSecurityConfig.java @@ -15,7 +15,7 @@ public class SocketSecurityConfig extends AbstractSecurityWebSocketMessageBroker @Override protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) { messages - .simpDestMatchers("/secured/**").authenticated() + .simpDestMatchers("/secured/**", "/secured/**/**").authenticated() .anyMessage().authenticated(); } } \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java index 68c5e306d8..6a74009c16 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java @@ -1,11 +1,19 @@ package com.baeldung.springsecuredsockets.controllers; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_HISTORY; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_ROOM; +import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_SPECIFIC_USER; + import com.baeldung.springsecuredsockets.transfer.socket.Message; import com.baeldung.springsecuredsockets.transfer.socket.OutputMessage; +import java.security.Principal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.MessageMapping; +import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; @@ -19,10 +27,19 @@ public class SocketController { private SimpMessagingTemplate simpMessagingTemplate; private static final Logger log = LoggerFactory.getLogger(SocketController.class); - @MessageMapping("/secured/chat") - @SendTo("/secured/history") - public OutputMessage send(Message msg) throws Exception { + @MessageMapping(SECURED_CHAT) + @SendTo(SECURED_CHAT_HISTORY) + public OutputMessage sendAll(Message msg) throws Exception { OutputMessage out = new OutputMessage(msg.getFrom(), msg.getText(), new SimpleDateFormat("HH:mm").format(new Date())); return out; } + + /** + * Example of sending message to specific user using 'convertAndSendToUser()' and '/queue' + */ + @MessageMapping(SECURED_CHAT_ROOM) + public void sendSpecific(@Payload Message msg, Principal user, @Header("simpSessionId") String sessionId) throws Exception { + OutputMessage out = new OutputMessage(msg.getFrom(), msg.getText(), new SimpleDateFormat("HH:mm").format(new Date())); + simpMessagingTemplate.convertAndSendToUser(msg.getTo(), SECURED_CHAT_SPECIFIC_USER, out); + } } diff --git a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/transfer/socket/Message.java b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/transfer/socket/Message.java index 024b386164..fd5d632fce 100644 --- a/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/transfer/socket/Message.java +++ b/spring-security-mvc-socket/src/main/java/com/baeldung/springsecuredsockets/transfer/socket/Message.java @@ -3,6 +3,7 @@ package com.baeldung.springsecuredsockets.transfer.socket; public class Message { private String from; + private String to; private String text; public String getFrom() { @@ -11,6 +12,13 @@ public class Message { public void setFrom(String from) { this.from = from; } + + public String getTo() { + return to; + } + public void setTo(String to) { + this.to = to; + } public String getText() { return text; } diff --git a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/denied.jsp b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/denied.jsp index d61148b04f..e4c40da0a8 100644 --- a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/denied.jsp +++ b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/denied.jsp @@ -4,15 +4,20 @@ - - Spring Secured Sockets - " rel="stylesheet"> - - - -

    ACCESS DENIED!

    -
    -
    - Click to login. - + + + Spring Secured Sockets + " rel="stylesheet"> + " rel="stylesheet"> + + + + +
    +
    +

    ACCESS DENIED!

    + Click to login. +
    +
    + \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/index.jsp index d83338680e..d1435e8c2b 100644 --- a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/index.jsp +++ b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/index.jsp @@ -4,27 +4,32 @@ - - Spring Secured Sockets - " rel="stylesheet"> - - - - - - - - - - - - -

    Welcome!

    -
    - {{greeting}} -
    -
    - Click to login. - + + Spring Secured Sockets + " rel="stylesheet"> + " rel="stylesheet"> + + + + + + + + + + + + + + +
    +
    +

    Welcome!

    + {{greeting}} + Click to login. +
    +
    + + \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/login.jsp b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/login.jsp index d50059c674..76e3334bbe 100644 --- a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/login.jsp +++ b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/login.jsp @@ -4,42 +4,50 @@ - - Spring Secured Sockets - " rel="stylesheet"> - - - - - - - - - - - - - - -

    JSP Login Form


    -
    - - - - - - - - - - - - -
    User:
    Password:
    -
    + + Spring Secured Sockets + " rel="stylesheet"> + " rel="stylesheet"> + + + + + + + + + + + + + + + +
    +
    + +

    JSP Login Form

    +
    + + + + + + + + + + + + +
    User:
    Password:
    +
    + +
    +
    + + + - - - \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/socket.jsp b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/socket.jsp index b5807d74a6..ccd48672a1 100644 --- a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/socket.jsp +++ b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/socket.jsp @@ -4,48 +4,56 @@ - - Spring Secured Sockets - " rel="stylesheet"> - - - - - - - - - - - - - - -

    Socket Chat

    - -
    -
    - -
    -
    -
    - - - -
    -
    -
    - - -

    -
    -
    + + Spring Secured Sockets + " rel="stylesheet"> + " rel="stylesheet"> -Click to go back! -Click to start over (you will still be authenticated)! + + + + + + + + + + + + + + + + +
    +
    +

    Socket Chat

    +
    +

    (Chat With Everyone)

    + + + +
    +
    +

    (Chat With A Specific User)

    + + + +
    +
    +

    (Send and See Messages)

    + + +
    + +
    + Click to go back! + Click to start over (you will still be authenticated)! +
    +
    + + + - - - \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/success.jsp b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/success.jsp index 27e8f7aa44..4cff3f7a25 100644 --- a/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/success.jsp +++ b/spring-security-mvc-socket/src/main/webapp/WEB-INF/jsp/success.jsp @@ -4,28 +4,33 @@ - - Spring Secured Sockets - " rel="stylesheet"> - - - - - - - - - - - - -

    Congrats! You've logged in.

    + + Spring Secured Sockets + " rel="stylesheet"> + " rel="stylesheet"> - Click to chat! - Click to start over (you will still be authenticated)! + + + - - - + + + + + + + + + +
    + +
    + + + \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/indexController.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/indexController.js index 04c02e339b..5de3dcc78b 100644 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/indexController.js +++ b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/indexController.js @@ -1,12 +1,13 @@ 'use strict'; angularApp - .controller('indexController', function ($scope) { - $scope.greeting = ''; +.controller('indexController', function ($scope) { - $scope.initialize = function () { - $scope.greeting = "Howdy!" - }; + $scope.greeting = ''; - $scope.initialize(); - }); \ No newline at end of file + $scope.initialize = function () { + $scope.greeting = "Howdy!" + }; + + $scope.initialize(); +}); \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/loginController.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/loginController.js deleted file mode 100644 index 07187d5327..0000000000 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/loginController.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -angularApp - .controller('loginController', function ($scope) { - - }); diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/socketController.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/socketController.js index 395bf85c4a..ff000c251e 100644 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/socketController.js +++ b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/socketController.js @@ -1,37 +1,52 @@ 'use strict'; angularApp - .controller('socketController', function ($scope, SocketService) { +.controller('socketController', function ($scope, SocketService) { - $scope.stompClient = null; - $scope.sendEndpoint = '/secured/chat'; - $scope.subscribeEndpoint = '/secured/history'; - $scope.elems = { - connect: 'connect', - from: 'from', - text: 'text', - disconnect: 'disconnect', - conversationDiv: 'conversationDiv', - response: 'response' - }; + /** + * URL mapping endpoints. + */ - $scope.connect = function (context) { - $scope.sendEndpoint = '/secured/chat'; - $scope.sendEndpoint = context + $scope.sendEndpoint ; - $scope.stompClient = SocketService.connect($scope.sendEndpoint, $scope.elems); - }; + var SECURED_CHAT = '/secured/chat'; + var SECURED_CHAT_HISTORY = '/secured/history'; + var SECURED_CHAT_ROOM = '/secured/room'; + var SECURED_CHAT_SPECIFIC_USER = '/secured/user/queue/specific-user'; - $scope.subscribe = function () { - $scope.stompClient.subscribe($scope.subscribeEndpoint, function (msgOut) { - SocketService.messageOut(JSON.parse(msgOut.body), $scope.elems); - }); - }; + var opts = { + from: 'from', + to: 'to', + text: 'text', + disconnect: 'disconnect', + conversationDiv: 'conversationDiv', + response: 'response' + }; - $scope.disconnect = function () { - SocketService.disconnect($scope.elems, $scope.stompClient); - }; + $scope.sendEndpoint = ''; + $scope.stompClient = null; - $scope.sendMessage = function () { - SocketService.sendMessage( $scope.elems, $scope.stompClient, $scope.sendEndpoint); - }; - }); \ No newline at end of file + /** + * Broadcast to All Users. + */ + + $scope.connectAll = function (context) { + $scope.sendEndpoint = context + SECURED_CHAT; + $scope.stompClient = SocketService.connect($scope.sendEndpoint , opts, true); + }; + + $scope.subscribeAll = function () { SocketService.subscribeToAll($scope.stompClient, SECURED_CHAT_HISTORY, opts); }; + + /** + * Broadcast to Specific User. + */ + + $scope.connectSpecific = function (context) { + $scope.sendEndpoint = context + SECURED_CHAT_ROOM; + $scope.stompClient = SocketService.connect(context + SECURED_CHAT_ROOM, opts, false); + }; + + $scope.subscribeSpecific = function () { SocketService.subscribeToSpecific($scope.stompClient, SECURED_CHAT_SPECIFIC_USER, opts); }; + + $scope.disconnect = function () { SocketService.disconnect(opts, $scope.stompClient); }; + + $scope.sendMessage = function () { SocketService.sendMessage(opts, $scope.stompClient, $scope.sendEndpoint); }; +}); \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/successController.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/successController.js index ccb972202d..6926239202 100644 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/successController.js +++ b/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/successController.js @@ -1,13 +1,12 @@ 'use strict'; angularApp - .controller('successController', function ($scope) { +.controller('successController', function ($scope) { + $scope.successMsg = ''; - $scope.successMsg = ''; + $scope.initialize = function () { + $scope.successMsg = "You've logged in!"; + }; - $scope.initialize = function () { - $scope.successMsg = "You've logged in!"; - }; - - $scope.initialize(); - }); + $scope.initialize(); +}); diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/routes/router.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/routes/router.js index 70644f996d..004c7b331a 100644 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/routes/router.js +++ b/spring-security-mvc-socket/src/main/webapp/resources/scripts/routes/router.js @@ -1,19 +1,16 @@ 'use strict'; angularApp - .config(function ($routeProvider) { - $routeProvider - .when('/index', { - controller: 'indexController' - }) - .when('/login', { - controller: 'loginController' - }) - .when('/sockets', { - controller: 'socketController' - }) - .when('/success', { - controller: 'successController' - }) - .otherwise('/index'); - }); \ No newline at end of file +.config(function ($routeProvider) { + $routeProvider + .when('/index', { + controller: 'indexController' + }) + .when('/sockets', { + controller: 'socketController' + }) + .when('/success', { + controller: 'successController' + }) + .otherwise('/index'); +}); \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/scripts/services/SocketService.js b/spring-security-mvc-socket/src/main/webapp/resources/scripts/services/SocketService.js index 56930808a3..ba3f397f89 100644 --- a/spring-security-mvc-socket/src/main/webapp/resources/scripts/services/SocketService.js +++ b/spring-security-mvc-socket/src/main/webapp/resources/scripts/services/SocketService.js @@ -1,46 +1,99 @@ 'use strict'; +var idHelper = function (context) { + return document.getElementById(context); +}; + function SocketService() { - var that = this, - idHelper = function(context) { - return document.getElementById(context); - }; - that.setConnected = function (elems, connected) { - idHelper(elems.connect).disabled = connected; - idHelper(elems.disconnect).disabled = !connected; - idHelper(elems.conversationDiv).style.visibility = connected ? 'visible' : 'hidden'; - idHelper(elems.response).innerHTML = ''; + var that = this; + + that.sessionId = ''; + + /** + * Generic methods. + */ + + that.setConnected = function (opts, connected) { + idHelper('connectAll').disabled = connected; + idHelper('connectSpecific').disabled = connected; + idHelper(opts.disconnect).disabled = !connected; + idHelper(opts.response).innerHTML = ''; + idHelper('subscribeAll').disabled = !connected; + idHelper('subscribeSpecific').disabled = !connected; + }; + + that.connect = function (endpoint, opts, isBroadcastAll) { + var socket = new SockJS(endpoint), stompClient = Stomp.over(socket); + stompClient.connect({}, function (frame) { + that.setConnected(opts, true); + + if (!isBroadcastAll) { + var url = stompClient.ws._transport.url; + console.log(stompClient.ws._transport.url); + url = url.replace("ws://localhost:8080/spring-security-mvc-socket/secured/room/", ""); + url = url.replace("/websocket", ""); + url = url.replace(/^[0-9]+\//, ""); + console.log("Your current session is: " + url); + that.sessionId = url; + } + + }); + return stompClient; + }; + + that.disconnect = function (opts, stompClient) { + if (stompClient !== null && stompClient !== undefined) { stompClient.disconnect(); } + that.setConnected(opts, false); + }; + + that.sendMessage = function (opts, stompClient, endpoint) { + var to = idHelper(opts.to).value; + var from = idHelper(opts.from).value; + + var msg = { + 'from': (from === undefined || from === null ) ? to : from, + 'to': (to === undefined || to === null ) ? "ALL" : to, + 'text': idHelper(opts.text).value }; - that.connect = function (endpoint, elems) { - var socket = new SockJS(endpoint), stompClient = Stomp.over(socket); - stompClient.connect({}, function (frame) { - that.setConnected(elems, true); - }); - return stompClient; - }; + console.log(JSON.stringify(msg)); + stompClient.send(endpoint, {}, JSON.stringify(msg)); + }; - that.disconnect = function (elems, stompClient) { - if (stompClient !== null && stompClient !== undefined) stompClient.disconnect(); - that.setConnected(elems, false); - }; + that.messageOut = function (msg, opts) { + var r = idHelper(opts.response), p = document.createElement('p'); + p.style.wordWrap = 'break-word'; + p.appendChild(document.createTextNode(msg.from + ': ' + msg.text + ' (' + msg.time + ')')); + r.appendChild(p); + }; + + /** + * Broadcast to All Users. + */ + + that.subscribeToAll = function(client, url, opts) { + idHelper('subscribeAll').disabled = true; + idHelper('subscribeSpecific').disabled = true; + client.subscribe(url, function (msgOut) { + that.messageOut(JSON.parse(msgOut.body), opts); + }); + }; + + /** + * Broadcast to Specific User. + */ + + that.subscribeToSpecific = function(client, url, opts) { + idHelper('subscribeAll').disabled = true; + idHelper('subscribeSpecific').disabled = true; + client.subscribe(url + "-user" + that.sessionId, function (msgOut) { + that.messageOut(JSON.parse(msgOut.body), opts); + }); + }; - that.sendMessage = function (elems, stompClient, endpoint) { - stompClient.send(endpoint, {}, - JSON.stringify({ - 'from': idHelper(elems.from).value, - 'text': idHelper(elems.text).value - })); - }; - that.messageOut = function (msg, elems) { - var r = idHelper(elems.response), p = document.createElement('p'); - p.style.wordWrap = 'break-word'; - p.appendChild(document.createTextNode(msg.from + ': ' + msg.text + ' (' + msg.time + ')')); - r.appendChild(p); - }; } angularApp - .service('SocketService', SocketService); \ No newline at end of file +.service('SocketService', SocketService); \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/app.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/app.css new file mode 100644 index 0000000000..ee2cb4d717 --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/app.css @@ -0,0 +1,70 @@ +@import url('https://fonts.googleapis.com/css?family=Poiret+One'); + +html, body, main { + padding: 0; + margin: 0; + position: absolute; + height: 100%; + width: 100%; + color: white; + font-family: 'Poiret One', sans-serif; + opacity:.95; +} + +main { + background-size: cover; +} + +main > div.wrapper { + position: relative; + left: 15%; + top: 15%; + width: 40%; +} + +h1 { + text-transform: uppercase; + font-size: 48px; + letter-spacing: 2px; +} + +span, a { + font-size: 24px; + letter-spacing: 1px; +} + +a { + text-decoration: none; + color: white; +} + +a:hover { + color: lightgray; +} + +input { + width: 225px; + background: none !important; + border-radius: 25px; + background-color: #fff; + color: white; + outline: none; + margin-left: 2px; + padding-left: 25px; + padding-bottom: 9px; + padding-top: 9px; +} + +button { + width: 100px; + align-content: center; + text-align: center; + background: transparent; + border-radius: 25px; + padding: 6px; + color: white; +} + +button:hover { + opacity: .6; +} \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/denied.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/denied.css new file mode 100644 index 0000000000..3956715e4a --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/denied.css @@ -0,0 +1,3 @@ +main { + background-color: black; +} diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/index.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/index.css new file mode 100644 index 0000000000..b6da4814b7 --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/index.css @@ -0,0 +1,7 @@ +main { + background-color: black; +} + +span, a { + top: 175px; +} \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/login.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/login.css new file mode 100644 index 0000000000..197f3e41bb --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/login.css @@ -0,0 +1,17 @@ +main { + background-color: black; +} + +input[type="submit"] { + width: 100px; + align-content: center; + text-align: center; + background: transparent; + border-radius: 25px; + padding: 6px; + color: white; +} + +input[type="submit"]:hover { + opacity:.6; +} \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/socket.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/socket.css new file mode 100644 index 0000000000..aa483fd684 --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/socket.css @@ -0,0 +1,19 @@ +main { + background-color: black; +} + +div#all, div#specific, div#conversationDiv { + border: 1px solid white; + border-radius: 25px; + padding: 15px; + margin: 15px +} + +button[disabled=true] { + color: lightgray; + border: 1px solid lightgray; +} + +button[disabled=true]:hover { + opacity: 1; +} \ No newline at end of file diff --git a/spring-security-mvc-socket/src/main/webapp/resources/styles/success.css b/spring-security-mvc-socket/src/main/webapp/resources/styles/success.css new file mode 100644 index 0000000000..3956715e4a --- /dev/null +++ b/spring-security-mvc-socket/src/main/webapp/resources/styles/success.css @@ -0,0 +1,3 @@ +main { + background-color: black; +} diff --git a/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..00202a98cb --- /dev/null +++ b/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,24 @@ +package org.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.web.WebAppConfiguration; + +import com.baeldung.springsecuredsockets.config.AppConfig; +import com.baeldung.springsecuredsockets.config.DataStoreConfig; +import com.baeldung.springsecuredsockets.config.SecurityConfig; +import com.baeldung.springsecuredsockets.config.SocketBrokerConfig; +import com.baeldung.springsecuredsockets.config.SocketSecurityConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppConfig.class, DataStoreConfig.class, SecurityConfig.class, + SocketBrokerConfig.class, SocketSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-openid/pom.xml b/spring-security-openid/pom.xml index 9c498f3700..4343996e02 100644 --- a/spring-security-openid/pom.xml +++ b/spring-security-openid/pom.xml @@ -3,9 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-security-openid - 0.0.1-SNAPSHOT war spring-security-openid Spring OpenID sample project @@ -51,27 +49,6 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - 2.2.1.RELEASE 1.0.9.RELEASE diff --git a/spring-security-openid/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-openid/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..79a725dcae --- /dev/null +++ b/spring-security-openid/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.SpringOpenidApplication; +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 = SpringOpenidApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-react/pom.xml b/spring-security-react/pom.xml index 11ad679128..32817945be 100644 --- a/spring-security-react/pom.xml +++ b/spring-security-react/pom.xml @@ -82,6 +82,14 @@ ${jstl.version} runtime + + + + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + diff --git a/spring-security-react/src/main/resources/logback.xml b/spring-security-react/src/main/resources/logback.xml index 75fcb235e1..25f3f36d1a 100644 --- a/spring-security-react/src/main/resources/logback.xml +++ b/spring-security-react/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-react/src/main/webapp/WEB-INF/view/react/package-lock.json b/spring-security-react/src/main/webapp/WEB-INF/view/react/package-lock.json index 89b9d1a6ed..46f3a86c20 100644 --- a/spring-security-react/src/main/webapp/WEB-INF/view/react/package-lock.json +++ b/spring-security-react/src/main/webapp/WEB-INF/view/react/package-lock.json @@ -9,15 +9,6 @@ "resolved": "https://registry.npmjs.org/abab/-/abab-1.0.4.tgz", "integrity": "sha1-X6rZwsB/YN12dw9xzwJbYqY8/U4=" }, - "accepts": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz", - "integrity": "sha1-63d99gEXI6OxTopywIBcjoZ0a9I=", - "requires": { - "mime-types": "~2.1.18", - "negotiator": "0.6.1" - } - }, "acorn": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.1.tgz", @@ -132,11 +123,6 @@ "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==" }, - "ansi-html": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/ansi-html/-/ansi-html-0.0.7.tgz", - "integrity": "sha1-gTWEAhliqenm/QOflA0S9WynhZ4=" - }, "ansi-regex": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", @@ -283,11 +269,6 @@ "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=" }, - "array-flatten": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-2.1.1.tgz", - "integrity": "sha1-Qmu52oQJDBg42BLIFQryCoMx4pY=" - }, "array-includes": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.0.3.tgz", @@ -1312,11 +1293,6 @@ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.0.tgz", "integrity": "sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw==" }, - "batch": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/batch/-/batch-0.6.1.tgz", - "integrity": "sha1-3DQxT05nkxgJP8dgJyUl+UvyXBY=" - }, "bcrypt-pbkdf": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", @@ -1346,48 +1322,6 @@ "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.8.tgz", "integrity": "sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA==" }, - "body-parser": { - "version": "1.18.2", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.2.tgz", - "integrity": "sha1-h2eKGdhLR9hZuDGZvVm84iKxBFQ=", - "requires": { - "bytes": "3.0.0", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "~1.1.1", - "http-errors": "~1.6.2", - "iconv-lite": "0.4.19", - "on-finished": "~2.3.0", - "qs": "6.5.1", - "raw-body": "2.3.2", - "type-is": "~1.6.15" - }, - "dependencies": { - "iconv-lite": { - "version": "0.4.19", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", - "integrity": "sha512-oTZqweIP51xaGPI4uPa56/Pri/480R+mo7SeU+YETByQNhDG55ycFyNLIgta9vXhILrxXDmF7ZGhqZIcuN0gJQ==" - }, - "qs": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", - "integrity": "sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==" - } - } - }, - "bonjour": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/bonjour/-/bonjour-3.5.0.tgz", - "integrity": "sha1-jokKGD2O6aI5OzhExpGkK897yfU=", - "requires": { - "array-flatten": "^2.1.0", - "deep-equal": "^1.0.1", - "dns-equal": "^1.0.0", - "dns-txt": "^2.0.2", - "multicast-dns": "^6.0.1", - "multicast-dns-service-types": "^1.1.0" - } - }, "boolbase": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", @@ -1576,11 +1510,6 @@ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.0.tgz", "integrity": "sha512-c5mRlguI/Pe2dSZmpER62rSCu0ryKmWddzRYsuXc50U2/g8jMOulc31VZMa4mYx31U5xsmSOpDCgH88Vl9cDGQ==" }, - "buffer-indexof": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/buffer-indexof/-/buffer-indexof-1.1.1.tgz", - "integrity": "sha512-4/rOEg86jivtPTeOUUT61jJO1Ya1TrR/OkqCSZDyq84WJh3LuuiphBYJN+fm5xufIk4XAFcEwte/8WzC8If/1g==" - }, "buffer-xor": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", @@ -1596,11 +1525,6 @@ "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=" }, - "bytes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", - "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=" - }, "cache-base": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", @@ -2012,42 +1936,6 @@ "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=" }, - "compressible": { - "version": "2.0.14", - "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.14.tgz", - "integrity": "sha1-MmxfUH+7BV9UEWeCuWmoG2einac=", - "requires": { - "mime-db": ">= 1.34.0 < 2" - }, - "dependencies": { - "mime-db": { - "version": "1.34.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.34.0.tgz", - "integrity": "sha1-RS0Oz/XDA0am3B5kseruDTcZ/5o=" - } - } - }, - "compression": { - "version": "1.7.2", - "resolved": "http://registry.npmjs.org/compression/-/compression-1.7.2.tgz", - "integrity": "sha1-qv+81qr4VLROuygDU9WtFlH1mmk=", - "requires": { - "accepts": "~1.3.4", - "bytes": "3.0.0", - "compressible": "~2.0.13", - "debug": "2.6.9", - "on-headers": "~1.0.1", - "safe-buffer": "5.1.1", - "vary": "~1.1.2" - }, - "dependencies": { - "safe-buffer": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" - } - } - }, "concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -2077,11 +1965,6 @@ "xdg-basedir": "^3.0.0" } }, - "connect-history-api-fallback": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/connect-history-api-fallback/-/connect-history-api-fallback-1.5.0.tgz", - "integrity": "sha1-sGhzk0vF40T+9hGhlqb6rgruAVo=" - }, "console-browserify": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", @@ -2100,16 +1983,6 @@ "resolved": "https://registry.npmjs.org/contains-path/-/contains-path-0.1.0.tgz", "integrity": "sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo=" }, - "content-disposition": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz", - "integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ=" - }, - "content-type": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", - "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==" - }, "content-type-parser": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/content-type-parser/-/content-type-parser-1.0.2.tgz", @@ -2120,16 +1993,6 @@ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.5.1.tgz", "integrity": "sha1-uCeAl7m8IpNl3lxiz1/K7YtVmeU=" }, - "cookie": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz", - "integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=" - }, - "cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" - }, "copy-descriptor": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", @@ -2514,11 +2377,6 @@ "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=" }, - "deep-equal": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", - "integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=" - }, "deep-extend": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", @@ -2614,11 +2472,6 @@ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" }, - "depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" - }, "des.js": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.0.tgz", @@ -2628,11 +2481,6 @@ "minimalistic-assert": "^1.0.0" } }, - "destroy": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" - }, "detect-indent": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", @@ -2641,11 +2489,6 @@ "repeating": "^2.0.0" } }, - "detect-node": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.0.3.tgz", - "integrity": "sha1-ogM8CcyOFY03dI+951B4Mr1s4Sc=" - }, "detect-port-alt": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/detect-port-alt/-/detect-port-alt-1.1.6.tgz", @@ -2670,28 +2513,6 @@ "randombytes": "^2.0.0" } }, - "dns-equal": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/dns-equal/-/dns-equal-1.0.0.tgz", - "integrity": "sha1-s55/HabrCnW6nBcySzR1PEfgZU0=" - }, - "dns-packet": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-1.3.1.tgz", - "integrity": "sha512-0UxfQkMhYAUaZI+xrNZOz/as5KgDU0M/fQ9b6SpkyLbk3GEswDi6PADJVaYJradtRVsRIlF1zLyOodbcTCDzUg==", - "requires": { - "ip": "^1.1.0", - "safe-buffer": "^5.0.1" - } - }, - "dns-txt": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/dns-txt/-/dns-txt-2.0.2.tgz", - "integrity": "sha1-uR2Ab10nGI5Ks+fRB9iBocxGQrY=", - "requires": { - "buffer-indexof": "^1.0.0" - } - }, "doctrine": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", @@ -2803,11 +2624,6 @@ "jsbn": "~0.1.0" } }, - "ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" - }, "electron-to-chromium": { "version": "1.3.50", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.50.tgz", @@ -2837,11 +2653,6 @@ "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=" }, - "encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=" - }, "encoding": { "version": "0.1.12", "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz", @@ -2974,11 +2785,6 @@ "es6-symbol": "^3.1.1" } }, - "escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" - }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -3332,11 +3138,6 @@ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=" }, - "etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" - }, "event-emitter": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz", @@ -3346,24 +3147,11 @@ "es5-ext": "~0.10.14" } }, - "eventemitter3": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.0.tgz", - "integrity": "sha512-ivIvhpq/Y0uSjcHDcOIccjmYjGLcP09MFGE7ysAwkAvkXfpZlC985pH2/ui64DKazbTW/4kN3yqozUxlXzI6cA==" - }, "events": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=" }, - "eventsource": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-0.1.6.tgz", - "integrity": "sha1-Cs7ehJ7X3RzMMsgRuxG5RNTykjI=", - "requires": { - "original": ">=0.0.5" - } - }, "evp_bytestokey": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", @@ -3481,65 +3269,6 @@ "homedir-polyfill": "^1.0.1" } }, - "express": { - "version": "4.16.3", - "resolved": "https://registry.npmjs.org/express/-/express-4.16.3.tgz", - "integrity": "sha1-avilAjUNsyRuzEvs9rWjTSL37VM=", - "requires": { - "accepts": "~1.3.5", - "array-flatten": "1.1.1", - "body-parser": "1.18.2", - "content-disposition": "0.5.2", - "content-type": "~1.0.4", - "cookie": "0.3.1", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "~1.1.2", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "1.1.1", - "fresh": "0.5.2", - "merge-descriptors": "1.0.1", - "methods": "~1.1.2", - "on-finished": "~2.3.0", - "parseurl": "~1.3.2", - "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.3", - "qs": "6.5.1", - "range-parser": "~1.2.0", - "safe-buffer": "5.1.1", - "send": "0.16.2", - "serve-static": "1.13.2", - "setprototypeof": "1.1.0", - "statuses": "~1.4.0", - "type-is": "~1.6.16", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "dependencies": { - "array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" - }, - "path-to-regexp": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", - "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" - }, - "qs": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", - "integrity": "sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==" - }, - "safe-buffer": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" - } - } - }, "extend": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", @@ -3669,14 +3398,6 @@ "resolved": "https://registry.npmjs.org/fastparse/-/fastparse-1.1.1.tgz", "integrity": "sha1-0eJkOzipTXWDtHkGDmxK/8lAcfg=" }, - "faye-websocket": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.1.tgz", - "integrity": "sha1-8O/hjE9W5PQK/H4Gxxn9XuYYjzg=", - "requires": { - "websocket-driver": ">=0.5.1" - } - }, "fb-watchman": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.0.tgz", @@ -3765,20 +3486,6 @@ } } }, - "finalhandler": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.1.tgz", - "integrity": "sha512-Y1GUDo39ez4aHAw7MysnUD5JzYX+WaIj8I57kO3aEPT1fFRL4sr7mjei97FgnwhAyyzRYmQZaTHb2+9uZ1dPtg==", - "requires": { - "debug": "2.6.9", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "on-finished": "~2.3.0", - "parseurl": "~1.3.2", - "statuses": "~1.4.0", - "unpipe": "~1.0.0" - } - }, "find-cache-dir": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-1.0.0.tgz", @@ -3813,24 +3520,6 @@ "resolved": "https://registry.npmjs.org/flatten/-/flatten-1.0.2.tgz", "integrity": "sha1-2uRqnXj74lKSJYzB54CkHZXAN4I=" }, - "follow-redirects": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.0.tgz", - "integrity": "sha512-fdrt472/9qQ6Kgjvb935ig6vJCuofpBUD14f9Vb+SLlm7xIe4Qva5gey8EKtv8lp7ahE1wilg3xL1znpVGtZIA==", - "requires": { - "debug": "^3.1.0" - }, - "dependencies": { - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "requires": { - "ms": "2.0.0" - } - } - } - }, "for-in": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", @@ -3864,11 +3553,6 @@ "mime-types": "^2.1.12" } }, - "forwarded": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", - "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=" - }, "fragment-cache": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", @@ -3877,11 +3561,6 @@ "map-cache": "^0.2.2" } }, - "fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" - }, "fs-extra": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-3.0.1.tgz", @@ -3914,7 +3593,8 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true + "bundled": true, + "optional": true }, "aproba": { "version": "1.2.0", @@ -3932,11 +3612,13 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true + "bundled": true, + "optional": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, + "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -3949,15 +3631,18 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "concat-map": { "version": "0.0.1", - "bundled": true + "bundled": true, + "optional": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "core-util-is": { "version": "1.0.2", @@ -4060,7 +3745,8 @@ }, "inherits": { "version": "2.0.3", - "bundled": true + "bundled": true, + "optional": true }, "ini": { "version": "1.3.5", @@ -4070,6 +3756,7 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, + "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -4082,17 +3769,20 @@ "minimatch": { "version": "3.0.4", "bundled": true, + "optional": true, "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", - "bundled": true + "bundled": true, + "optional": true }, "minipass": { "version": "2.2.4", "bundled": true, + "optional": true, "requires": { "safe-buffer": "^5.1.1", "yallist": "^3.0.0" @@ -4109,6 +3799,7 @@ "mkdirp": { "version": "0.5.1", "bundled": true, + "optional": true, "requires": { "minimist": "0.0.8" } @@ -4181,7 +3872,8 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true + "bundled": true, + "optional": true }, "object-assign": { "version": "4.1.1", @@ -4191,6 +3883,7 @@ "once": { "version": "1.4.0", "bundled": true, + "optional": true, "requires": { "wrappy": "1" } @@ -4266,7 +3959,8 @@ }, "safe-buffer": { "version": "5.1.1", - "bundled": true + "bundled": true, + "optional": true }, "safer-buffer": { "version": "2.1.2", @@ -4296,6 +3990,7 @@ "string-width": { "version": "1.0.2", "bundled": true, + "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -4313,6 +4008,7 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, + "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -4351,11 +4047,13 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true + "bundled": true, + "optional": true }, "yallist": { "version": "3.0.2", - "bundled": true + "bundled": true, + "optional": true } } }, @@ -4511,11 +4209,6 @@ "duplexer": "^0.1.1" } }, - "handle-thing": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-1.2.5.tgz", - "integrity": "sha1-/Xqtcmvxpf0W38KbL3pmAdJxOcQ=" - }, "handlebars": { "version": "4.0.11", "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.0.11.tgz", @@ -4692,17 +4385,6 @@ "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.6.1.tgz", "integrity": "sha512-Ba4+0M4YvIDUUsprMjhVTU1yN9F2/LJSAl69ZpzaLT4l4j5mwTS6jqqW9Ojvj6lKz/veqPzpJBqGbXspOb533A==" }, - "hpack.js": { - "version": "2.1.6", - "resolved": "https://registry.npmjs.org/hpack.js/-/hpack.js-2.1.6.tgz", - "integrity": "sha1-h3dMCUnlE/QuhFdbPEVoH63ioLI=", - "requires": { - "inherits": "^2.0.1", - "obuf": "^1.0.0", - "readable-stream": "^2.0.1", - "wbuf": "^1.1.0" - } - }, "html-comment-regex": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/html-comment-regex/-/html-comment-regex-1.1.1.tgz", @@ -4716,11 +4398,6 @@ "whatwg-encoding": "^1.0.1" } }, - "html-entities": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-1.2.1.tgz", - "integrity": "sha1-DfKTUfByEWNRXfueVUPl9u7VFi8=" - }, "html-minifier": { "version": "3.5.17", "resolved": "https://registry.npmjs.org/html-minifier/-/html-minifier-3.5.17.tgz", @@ -4810,152 +4487,6 @@ } } }, - "http-deceiver": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/http-deceiver/-/http-deceiver-1.2.7.tgz", - "integrity": "sha1-+nFolEq5pRnTN8sL7HKE3D5yPYc=" - }, - "http-errors": { - "version": "1.6.3", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", - "integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=", - "requires": { - "depd": "~1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.0", - "statuses": ">= 1.4.0 < 2" - } - }, - "http-parser-js": { - "version": "0.4.13", - "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.4.13.tgz", - "integrity": "sha1-O9bW/ebjFyyTNMOzO2wZPYD+ETc=" - }, - "http-proxy": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.17.0.tgz", - "integrity": "sha512-Taqn+3nNvYRfJ3bGvKfBSRwy1v6eePlm3oc/aWVxZp57DQr5Eq3xhKJi7Z4hZpS8PC3H4qI+Yly5EmFacGuA/g==", - "requires": { - "eventemitter3": "^3.0.0", - "follow-redirects": "^1.0.0", - "requires-port": "^1.0.0" - } - }, - "http-proxy-middleware": { - "version": "0.17.4", - "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-0.17.4.tgz", - "integrity": "sha1-ZC6ISIUdZvCdTxJJEoRtuutBuDM=", - "requires": { - "http-proxy": "^1.16.2", - "is-glob": "^3.1.0", - "lodash": "^4.17.2", - "micromatch": "^2.3.11" - }, - "dependencies": { - "arr-diff": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", - "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", - "requires": { - "arr-flatten": "^1.0.1" - } - }, - "array-unique": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", - "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=" - }, - "braces": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", - "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", - "requires": { - "expand-range": "^1.8.1", - "preserve": "^0.2.0", - "repeat-element": "^1.1.2" - } - }, - "expand-brackets": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", - "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", - "requires": { - "is-posix-bracket": "^0.1.0" - } - }, - "extglob": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", - "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", - "requires": { - "is-extglob": "^1.0.0" - }, - "dependencies": { - "is-extglob": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", - "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=" - } - } - }, - "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" - }, - "is-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", - "requires": { - "is-extglob": "^2.1.0" - } - }, - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "requires": { - "is-buffer": "^1.1.5" - } - }, - "micromatch": { - "version": "2.3.11", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", - "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", - "requires": { - "arr-diff": "^2.0.0", - "array-unique": "^0.2.1", - "braces": "^1.8.2", - "expand-brackets": "^0.1.4", - "extglob": "^0.3.1", - "filename-regex": "^2.0.0", - "is-extglob": "^1.0.0", - "is-glob": "^2.0.1", - "kind-of": "^3.0.2", - "normalize-path": "^2.0.1", - "object.omit": "^2.0.0", - "parse-glob": "^3.0.4", - "regex-cache": "^0.4.2" - }, - "dependencies": { - "is-extglob": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", - "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=" - }, - "is-glob": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", - "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", - "requires": { - "is-extglob": "^1.0.0" - } - } - } - } - } - }, "http-signature": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", @@ -5007,15 +4538,6 @@ "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", "integrity": "sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM=" }, - "import-local": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-0.1.1.tgz", - "integrity": "sha1-sReVcqrNwRxqkQCftDDbyrX2aKg=", - "requires": { - "pkg-dir": "^2.0.0", - "resolve-cwd": "^2.0.0" - } - }, "imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", @@ -5104,14 +4626,6 @@ } } }, - "internal-ip": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/internal-ip/-/internal-ip-1.2.0.tgz", - "integrity": "sha1-rp+/k7mEh4eF1QqN4bNWlWBYz1w=", - "requires": { - "meow": "^3.3.0" - } - }, "interpret": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.1.0.tgz", @@ -5130,16 +4644,6 @@ "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz", "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=" }, - "ip": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/ip/-/ip-1.1.5.tgz", - "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=" - }, - "ipaddr.js": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.6.0.tgz", - "integrity": "sha1-4/o1e3c9phnybpXwSdBVxyeW+Gs=" - }, "is-absolute-url": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-absolute-url/-/is-absolute-url-2.1.0.tgz", @@ -6237,11 +5741,6 @@ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" }, - "json3": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/json3/-/json3-3.3.2.tgz", - "integrity": "sha1-PAQ0dD35Pi9cQq7nsZvLSDV19OE=" - }, "json5": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", @@ -6276,11 +5775,6 @@ "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-1.4.1.tgz", "integrity": "sha1-OGchPo3Xm/Ho8jAMDPwe+xgsDfE=" }, - "killable": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/killable/-/killable-1.0.0.tgz", - "integrity": "sha1-2ouEvUfeU5WHj5XWTQLyRJ/gXms=" - }, "kind-of": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", @@ -6468,11 +5962,6 @@ "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", "integrity": "sha1-0CJTc662Uq3BvILklFM5qEJ1R3M=" }, - "loglevel": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.6.1.tgz", - "integrity": "sha1-4PyVEztu8nbNyIh82vJKpvFW+Po=" - }, "longest": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", @@ -6574,11 +6063,6 @@ "inherits": "^2.0.1" } }, - "media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" - }, "mem": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/mem/-/mem-1.1.0.tgz", @@ -6625,16 +6109,6 @@ "resolved": "https://registry.npmjs.org/merge/-/merge-1.2.0.tgz", "integrity": "sha1-dTHjnUlJwoGma4xabgJl6LBYlNo=" }, - "merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" - }, - "methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" - }, "micromatch": { "version": "3.1.10", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", @@ -6742,20 +6216,6 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" }, - "multicast-dns": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-6.2.3.tgz", - "integrity": "sha512-ji6J5enbMyGRHIAkAOu3WdV8nggqviKCEKtXcOqfphZZtQrmHKycfynJ2V7eVPUA4NhJ6V7Wf4TmGbTwKE9B6g==", - "requires": { - "dns-packet": "^1.3.1", - "thunky": "^1.0.2" - } - }, - "multicast-dns-service-types": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz", - "integrity": "sha1-iZ8R2WhuXgXLkbNdXw5jt3PPyQE=" - }, "mute-stream": { "version": "0.0.7", "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", @@ -6790,11 +6250,6 @@ "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=" }, - "negotiator": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz", - "integrity": "sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk=" - }, "neo-async": { "version": "2.5.1", "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.5.1.tgz", @@ -6822,11 +6277,6 @@ "is-stream": "^1.0.1" } }, - "node-forge": { - "version": "0.7.5", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.7.5.tgz", - "integrity": "sha512-MmbQJ2MTESTjt3Gi/3yG1wGpIMhUfcIypUCGtTizFR9IiccFwxSpfp0vtIZlkFclEqERemxfnSdZEMR9VqqEFQ==" - }, "node-int64": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", @@ -7019,24 +6469,6 @@ "isobject": "^3.0.1" } }, - "obuf": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.2.tgz", - "integrity": "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==" - }, - "on-finished": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", - "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", - "requires": { - "ee-first": "1.1.1" - } - }, - "on-headers": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.1.tgz", - "integrity": "sha1-ko9dD0cNSTQmUepnlLCFfBAGk/c=" - }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -7090,14 +6522,6 @@ "wordwrap": "~1.0.0" } }, - "original": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/original/-/original-1.0.1.tgz", - "integrity": "sha512-IEvtB5vM5ULvwnqMxWBLxkS13JIEXbakizMSo3yoPNPCIWzg8TG3Usn/UhXoZFM/m+FuEA20KdzPSFq/0rS+UA==", - "requires": { - "url-parse": "~1.4.0" - } - }, "os-browserify": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", @@ -7217,11 +6641,6 @@ "resolved": "https://registry.npmjs.org/parse5/-/parse5-1.5.1.tgz", "integrity": "sha1-m387DeMr543CQBsXVzzK8Pb1nZQ=" }, - "parseurl": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", - "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=" - }, "pascalcase": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", @@ -7335,23 +6754,6 @@ "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz", "integrity": "sha512-ARhBOdzS3e41FbkW/XWrTEtukqqLoK5+Z/4UeDaLuSW+39JPeFgs4gCGqsrJHVZX0fUrx//4OF0K1CUGwlIFow==" }, - "portfinder": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.13.tgz", - "integrity": "sha1-uzLs2HwnEErm7kS1o8y/Drsa7ek=", - "requires": { - "async": "^1.5.2", - "debug": "^2.2.0", - "mkdirp": "0.5.x" - }, - "dependencies": { - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - } - } - }, "posix-character-classes": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", @@ -8576,15 +7978,6 @@ "object-assign": "^4.1.1" } }, - "proxy-addr": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.3.tgz", - "integrity": "sha512-jQTChiCJteusULxjBp8+jftSQE5Obdl3k4cnmLA6WXtK6XFuWRnvVL7aCiBqaLPM8c4ph0S4tKna8XvmIwEnXQ==", - "requires": { - "forwarded": "~0.1.2", - "ipaddr.js": "1.6.0" - } - }, "prr": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", @@ -8646,11 +8039,6 @@ "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=" }, - "querystringify": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.0.0.tgz", - "integrity": "sha512-eTPo5t/4bgaMNZxyjWx6N2a6AuE0mq51KWvpc7nU/MAqixcI6v6KrGUKES0HaomdnolQBBXU/++X6/QQ9KL4tw==" - }, "raf": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/raf/-/raf-3.4.0.tgz", @@ -8693,50 +8081,6 @@ "safe-buffer": "^5.1.0" } }, - "range-parser": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz", - "integrity": "sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4=" - }, - "raw-body": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.2.tgz", - "integrity": "sha1-vNYMd9Prk83gBQKVw/N5OJvIj4k=", - "requires": { - "bytes": "3.0.0", - "http-errors": "1.6.2", - "iconv-lite": "0.4.19", - "unpipe": "1.0.0" - }, - "dependencies": { - "depd": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.1.tgz", - "integrity": "sha1-V4O04cRZ8G+lyif5kfPQbnoxA1k=" - }, - "http-errors": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.2.tgz", - "integrity": "sha1-CgAsyFcHGSp+eUbO7cERVfYOxzY=", - "requires": { - "depd": "1.1.1", - "inherits": "2.0.3", - "setprototypeof": "1.0.3", - "statuses": ">= 1.3.1 < 2" - } - }, - "iconv-lite": { - "version": "0.4.19", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", - "integrity": "sha512-oTZqweIP51xaGPI4uPa56/Pri/480R+mo7SeU+YETByQNhDG55ycFyNLIgta9vXhILrxXDmF7ZGhqZIcuN0gJQ==" - }, - "setprototypeof": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.0.3.tgz", - "integrity": "sha1-ZlZ+NwQ+608E2RvWWMDL77VbjgQ=" - } - } - }, "rc": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", @@ -8786,9 +8130,19 @@ "react-error-overlay": "^4.0.0", "recursive-readdir": "2.2.1", "shell-quote": "1.6.1", - "sockjs-client": "1.1.4", "strip-ansi": "3.0.1", "text-table": "0.2.0" + }, + "dependencies": { + "sockjs-client": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/sockjs-client/-/sockjs-client-1.1.5.tgz", + "integrity": "sha1-G7fA9yIsQPQq3xT0RCy9Eml3GoM=", + "requires": { + "debug": "^2.6.6", + "inherits": "^2.0.1" + } + } } }, "react-dom": { @@ -8848,7 +8202,6 @@ "sw-precache-webpack-plugin": "0.11.4", "url-loader": "0.6.2", "webpack": "3.8.1", - "webpack-dev-server": "2.9.4", "webpack-manifest-plugin": "1.3.2", "whatwg-fetch": "2.0.3" }, @@ -8880,6 +8233,18 @@ "asap": "~2.0.3" } }, + "webpack-dev-server": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-3.1.5.tgz", + "integrity": "sha512-LVHg+EPwZLHIlfvokSTgtJqO/vI5CQi89fASb5JEDtVMDjY0yuIEqPPdMiKaBJIB/Ab7v/UN/sYZ7WsZvntQKw==", + "requires": { + "array-includes": "^3.0.3", + "chokidar": "^2.0.0", + "opn": "^5.1.0", + "strip-ansi": "^3.0.0", + "supports-color": "^5.1.0" + } + }, "whatwg-fetch": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-2.0.3.tgz", @@ -9206,11 +8571,6 @@ "resolve-from": "^1.0.0" } }, - "requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=" - }, "resolve": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.6.0.tgz", @@ -9219,21 +8579,6 @@ "path-parse": "^1.0.5" } }, - "resolve-cwd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-2.0.0.tgz", - "integrity": "sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=", - "requires": { - "resolve-from": "^3.0.0" - }, - "dependencies": { - "resolve-from": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz", - "integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=" - } - } - }, "resolve-dir": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", @@ -9381,19 +8726,6 @@ "ajv": "^5.0.0" } }, - "select-hose": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", - "integrity": "sha1-Yl2GWPhlr0Psliv8N2o3NZpJlMo=" - }, - "selfsigned": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-1.10.3.tgz", - "integrity": "sha512-vmZenZ+8Al3NLHkWnhBQ0x6BkML1eCP2xEi3JE+f3D9wW9fipD9NNJHYtE9XJM4TsPaHGZJIamrSI6MTg1dU2Q==", - "requires": { - "node-forge": "0.7.5" - } - }, "semver": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", @@ -9407,58 +8739,6 @@ "semver": "^5.0.3" } }, - "send": { - "version": "0.16.2", - "resolved": "https://registry.npmjs.org/send/-/send-0.16.2.tgz", - "integrity": "sha512-E64YFPUssFHEFBvpbbjr44NCLtI1AohxQ8ZSiJjQLskAdKuriYEP6VyGEsRDH8ScozGpkaX1BGvhanqCwkcEZw==", - "requires": { - "debug": "2.6.9", - "depd": "~1.1.2", - "destroy": "~1.0.4", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "0.5.2", - "http-errors": "~1.6.2", - "mime": "1.4.1", - "ms": "2.0.0", - "on-finished": "~2.3.0", - "range-parser": "~1.2.0", - "statuses": "~1.4.0" - }, - "dependencies": { - "mime": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz", - "integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==" - } - } - }, - "serve-index": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz", - "integrity": "sha1-03aNabHn2C5c4FD/9bRTvqEqkjk=", - "requires": { - "accepts": "~1.3.4", - "batch": "0.6.1", - "debug": "2.6.9", - "escape-html": "~1.0.3", - "http-errors": "~1.6.2", - "mime-types": "~2.1.17", - "parseurl": "~1.3.2" - } - }, - "serve-static": { - "version": "1.13.2", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.13.2.tgz", - "integrity": "sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==", - "requires": { - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "parseurl": "~1.3.2", - "send": "0.16.2" - } - }, "serviceworker-cache-polyfill": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/serviceworker-cache-polyfill/-/serviceworker-cache-polyfill-4.0.0.tgz", @@ -9500,11 +8780,6 @@ "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=" }, - "setprototypeof": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", - "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==" - }, "sha.js": { "version": "2.4.11", "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", @@ -9663,43 +8938,6 @@ } } }, - "sockjs": { - "version": "0.3.18", - "resolved": "https://registry.npmjs.org/sockjs/-/sockjs-0.3.18.tgz", - "integrity": "sha1-2bKJMWyn33dZXvKZ4HXw+TfrQgc=", - "requires": { - "faye-websocket": "^0.10.0", - "uuid": "^2.0.2" - }, - "dependencies": { - "faye-websocket": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.10.0.tgz", - "integrity": "sha1-TkkvjQTftviQA1B/btvy1QHnxvQ=", - "requires": { - "websocket-driver": ">=0.5.1" - } - }, - "uuid": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-2.0.3.tgz", - "integrity": "sha1-Z+LoY3lyFVMN/zGOW/nc6/1Hsho=" - } - } - }, - "sockjs-client": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/sockjs-client/-/sockjs-client-1.1.4.tgz", - "integrity": "sha1-W6vjhrd15M8U51IJEUUmVAFsixI=", - "requires": { - "debug": "^2.6.6", - "eventsource": "0.1.6", - "faye-websocket": "~0.11.0", - "inherits": "^2.0.1", - "json3": "^3.3.2", - "url-parse": "^1.1.8" - } - }, "sort-keys": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/sort-keys/-/sort-keys-1.1.2.tgz", @@ -9778,33 +9016,6 @@ "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.0.tgz", "integrity": "sha512-2+EPwgbnmOIl8HjGBXXMd9NAu02vLjOO1nWw4kmeRDFyHn+M/ETfHxQUK0oXg8ctgVnl9t3rosNVsZ1jG61nDA==" }, - "spdy": { - "version": "3.4.7", - "resolved": "https://registry.npmjs.org/spdy/-/spdy-3.4.7.tgz", - "integrity": "sha1-Qv9B7OXMD5mjpsKKq7c/XDsDrLw=", - "requires": { - "debug": "^2.6.8", - "handle-thing": "^1.2.5", - "http-deceiver": "^1.2.7", - "safe-buffer": "^5.0.1", - "select-hose": "^2.0.0", - "spdy-transport": "^2.0.18" - } - }, - "spdy-transport": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/spdy-transport/-/spdy-transport-2.1.0.tgz", - "integrity": "sha512-bpUeGpZcmZ692rrTiqf9/2EUakI6/kXX1Rpe0ib/DyOzbiexVfXkw6GnvI9hVGvIwVaUhkaBojjCZwLNRGQg1g==", - "requires": { - "debug": "^2.6.8", - "detect-node": "^2.0.3", - "hpack.js": "^2.1.6", - "obuf": "^1.1.1", - "readable-stream": "^2.2.9", - "safe-buffer": "^5.0.1", - "wbuf": "^1.7.2" - } - }, "split-string": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", @@ -9853,11 +9064,6 @@ } } }, - "statuses": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz", - "integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==" - }, "stream-browserify": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.1.tgz", @@ -10116,16 +9322,6 @@ "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" }, - "thunky": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.0.2.tgz", - "integrity": "sha1-qGLgGOP7HqLsP85dVWBc9X8kc3E=" - }, - "time-stamp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/time-stamp/-/time-stamp-2.0.0.tgz", - "integrity": "sha1-lcakRTDhW6jW9KPsuMOj+sRto1c=" - }, "timed-out": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", @@ -10263,15 +9459,6 @@ "prelude-ls": "~1.1.2" } }, - "type-is": { - "version": "1.6.16", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz", - "integrity": "sha512-HRkVv/5qY2G6I8iab9cI7v1bOIdhm94dVjQCPFElW9W+3GeDOSHmy2EBYe4VTApuzolPcmgFTN3ftVJRKR2J9Q==", - "requires": { - "media-typer": "0.3.0", - "mime-types": "~2.1.18" - } - }, "typedarray": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", @@ -10397,11 +9584,6 @@ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==" }, - "unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" - }, "unset-value": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", @@ -10526,15 +9708,6 @@ "schema-utils": "^0.3.0" } }, - "url-parse": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.4.1.tgz", - "integrity": "sha512-x95Td74QcvICAA0+qERaVkRpTGKyBHHYdwL2LXZm5t/gBtCB9KQSO/0zQgSTYEV1p0WcvSg79TLNPSvd5IDJMQ==", - "requires": { - "querystringify": "^2.0.0", - "requires-port": "^1.0.0" - } - }, "url-parse-lax": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-1.0.0.tgz", @@ -10569,11 +9742,6 @@ "resolved": "https://registry.npmjs.org/utila/-/utila-0.4.0.tgz", "integrity": "sha1-ihagXURWV6Oupe7MWxKk+lN5dyw=" }, - "utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" - }, "uuid": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", @@ -10588,11 +9756,6 @@ "spdx-expression-parse": "^3.0.0" } }, - "vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" - }, "vendors": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/vendors/-/vendors-1.0.2.tgz", @@ -10639,14 +9802,6 @@ "neo-async": "^2.5.0" } }, - "wbuf": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/wbuf/-/wbuf-1.7.3.tgz", - "integrity": "sha512-O84QOnr0icsbFGLS0O3bI5FswxzRr8/gHwWkDlQFskhSPryQXvrTMxjxGP4+iWYoauLoBvfDpkrOauZ+0iZpDA==", - "requires": { - "minimalistic-assert": "^1.0.0" - } - }, "webidl-conversions": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", @@ -10827,189 +9982,6 @@ } } }, - "webpack-dev-middleware": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-1.12.2.tgz", - "integrity": "sha512-FCrqPy1yy/sN6U/SaEZcHKRXGlqU0DUaEBL45jkUYoB8foVb6wCnbIJ1HKIx+qUFTW+3JpVcCJCxZ8VATL4e+A==", - "requires": { - "memory-fs": "~0.4.1", - "mime": "^1.5.0", - "path-is-absolute": "^1.0.0", - "range-parser": "^1.0.3", - "time-stamp": "^2.0.0" - } - }, - "webpack-dev-server": { - "version": "2.9.4", - "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-2.9.4.tgz", - "integrity": "sha512-thrqC0EQEoSjXeYgP6pUXcUCZ+LNrKsDPn+mItLnn5VyyNZOJKd06hUP5vqkYwL8nWWXsii0loSF9NHNccT6ow==", - "requires": { - "ansi-html": "0.0.7", - "array-includes": "^3.0.3", - "bonjour": "^3.5.0", - "chokidar": "^1.6.0", - "compression": "^1.5.2", - "connect-history-api-fallback": "^1.3.0", - "debug": "^3.1.0", - "del": "^3.0.0", - "express": "^4.13.3", - "html-entities": "^1.2.0", - "http-proxy-middleware": "~0.17.4", - "import-local": "^0.1.1", - "internal-ip": "1.2.0", - "ip": "^1.1.5", - "killable": "^1.0.0", - "loglevel": "^1.4.1", - "opn": "^5.1.0", - "portfinder": "^1.0.9", - "selfsigned": "^1.9.1", - "serve-index": "^1.7.2", - "sockjs": "0.3.18", - "sockjs-client": "1.1.4", - "spdy": "^3.4.1", - "strip-ansi": "^3.0.1", - "supports-color": "^4.2.1", - "webpack-dev-middleware": "^1.11.0", - "yargs": "^6.6.0" - }, - "dependencies": { - "camelcase": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", - "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=" - }, - "chokidar": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-1.7.0.tgz", - "integrity": "sha1-eY5ol3gVHIB2tLNg5e3SjNortGg=", - "requires": { - "anymatch": "^1.3.0", - "async-each": "^1.0.0", - "fsevents": "^1.0.0", - "glob-parent": "^2.0.0", - "inherits": "^2.0.1", - "is-binary-path": "^1.0.0", - "is-glob": "^2.0.0", - "path-is-absolute": "^1.0.0", - "readdirp": "^2.0.0" - } - }, - "cliui": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", - "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", - "requires": { - "string-width": "^1.0.1", - "strip-ansi": "^3.0.1", - "wrap-ansi": "^2.0.0" - } - }, - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "requires": { - "ms": "2.0.0" - } - }, - "del": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/del/-/del-3.0.0.tgz", - "integrity": "sha1-U+z2mf/LyzljdpGrE7rxYIGXZuU=", - "requires": { - "globby": "^6.1.0", - "is-path-cwd": "^1.0.0", - "is-path-in-cwd": "^1.0.0", - "p-map": "^1.1.1", - "pify": "^3.0.0", - "rimraf": "^2.2.8" - } - }, - "globby": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-6.1.0.tgz", - "integrity": "sha1-9abXDoOV4hyFj7BInWTfAkJNUGw=", - "requires": { - "array-union": "^1.0.1", - "glob": "^7.0.3", - "object-assign": "^4.0.1", - "pify": "^2.0.0", - "pinkie-promise": "^2.0.0" - }, - "dependencies": { - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" - } - } - }, - "has-flag": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", - "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=" - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", - "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", - "requires": { - "number-is-nan": "^1.0.0" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=" - }, - "string-width": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", - "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", - "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.0.0" - } - }, - "supports-color": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.5.0.tgz", - "integrity": "sha1-vnoN5ITexcXN34s9WRJQRJEvY1s=", - "requires": { - "has-flag": "^2.0.0" - } - }, - "yargs": { - "version": "6.6.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-6.6.0.tgz", - "integrity": "sha1-eC7CHvQDNF+DCoCMo9UTr1YGUgg=", - "requires": { - "camelcase": "^3.0.0", - "cliui": "^3.2.0", - "decamelize": "^1.1.1", - "get-caller-file": "^1.0.1", - "os-locale": "^1.4.0", - "read-pkg-up": "^1.0.1", - "require-directory": "^2.1.1", - "require-main-filename": "^1.0.1", - "set-blocking": "^2.0.0", - "string-width": "^1.0.2", - "which-module": "^1.0.0", - "y18n": "^3.2.1", - "yargs-parser": "^4.2.0" - } - }, - "yargs-parser": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-4.2.1.tgz", - "integrity": "sha1-KczqwNxPA8bIe0qfIX3RjJ90hxw=", - "requires": { - "camelcase": "^3.0.0" - } - } - } - }, "webpack-manifest-plugin": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/webpack-manifest-plugin/-/webpack-manifest-plugin-1.3.2.tgz", @@ -11050,20 +10022,6 @@ "source-map": "~0.6.1" } }, - "websocket-driver": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.0.tgz", - "integrity": "sha1-DK+dLXVdk67gSdS90NP+LMoqJOs=", - "requires": { - "http-parser-js": ">=0.4.0", - "websocket-extensions": ">=0.1.1" - } - }, - "websocket-extensions": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.3.tgz", - "integrity": "sha512-nqHUnMXmBzT0w570r2JpJxfiSD1IzoI+HGVdd3aZ0yNi3ngvQ4jv1dtHt5VGxfI2yj5yqImPhOK4vmIh2xMbGg==" - }, "whatwg-encoding": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.3.tgz", diff --git a/spring-security-react/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-react/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a921976fc3 --- /dev/null +++ b/spring-security-react/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-rest-basic-auth/src/main/resources/logback.xml b/spring-security-rest-basic-auth/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-rest-basic-auth/src/main/resources/logback.xml +++ b/spring-security-rest-basic-auth/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..6cf624c179 --- /dev/null +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ "/WebSecurityConfig.xml" }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-rest-custom/src/main/resources/logback.xml b/spring-security-rest-custom/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-rest-custom/src/main/resources/logback.xml +++ b/spring-security-rest-custom/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 5bde78db7e..57ce5ddb92 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -300,7 +300,7 @@ 2.9.0 - 2.7.0 + 2.9.2 2.6 diff --git a/spring-security-rest/src/main/resources/logback.xml b/spring-security-rest/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-security-rest/src/main/resources/logback.xml +++ b/spring-security-rest/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-security-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e2e9f2af2b --- /dev/null +++ b/spring-security-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.ClientWebConfig; +import org.baeldung.spring.SecurityJavaConfig; +import org.baeldung.spring.WebConfig; +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.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/test/AuthServerIntegrationTest.java b/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 88% rename from spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/test/AuthServerIntegrationTest.java rename to spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 9e2d6feca1..66ee232b10 100644 --- a/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/test/AuthServerIntegrationTest.java +++ b/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.test; +package org.baeldung; import org.baeldung.config.AuthorizationServerApplication; import org.junit.Test; @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = AuthorizationServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class AuthServerIntegrationTest { +public class SpringContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { diff --git a/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/test/UiIntegrationTest.java b/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 88% rename from spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/test/UiIntegrationTest.java rename to spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 6386eac0b8..2fb0210929 100644 --- a/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/test/UiIntegrationTest.java +++ b/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.test; +package org.baeldung; import org.baeldung.config.UiApplication; import org.junit.Test; @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class UiIntegrationTest { +public class SpringContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { diff --git a/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/test/UiIntegrationTest.java b/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 88% rename from spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/test/UiIntegrationTest.java rename to spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 6386eac0b8..2fb0210929 100644 --- a/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/test/UiIntegrationTest.java +++ b/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.test; +package org.baeldung; import org.baeldung.config.UiApplication; import org.junit.Test; @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class UiIntegrationTest { +public class SpringContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { diff --git a/spring-security-x509/spring-security-x509-basic-auth/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml index 9ae1ec65b2..67f2b4fbcd 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-basic-auth/pom.xml @@ -3,10 +3,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - basic-secured-server + spring-security-x509-basic-auth 0.0.1-SNAPSHOT jar - basic-secured-server + Spring Security x.509 Basic Authentication Spring x.509 Authentication Demo diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7ec6125f84 --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.security.x509.X509AuthenticationServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = X509AuthenticationServer.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-x509/spring-security-x509-client-auth/pom.xml b/spring-security-x509/spring-security-x509-client-auth/pom.xml index 4ade2aacd6..5cb4001a94 100644 --- a/spring-security-x509/spring-security-x509-client-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-client-auth/pom.xml @@ -3,10 +3,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - client-auth-server + spring-security-x509-client-auth 0.0.1-SNAPSHOT jar - client-auth-server + Spring Security x.509 Client Authentication Spring x.509 Client Authentication Demo diff --git a/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..7ec6125f84 --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.security.x509.X509AuthenticationServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = X509AuthenticationServer.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..b921f76a0d --- /dev/null +++ b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.springsessionjdbc.SpringSessionJdbcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSessionJdbcApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a62e728826 --- /dev/null +++ b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.session.SessionWebApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SessionWebApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-sleuth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-sleuth/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ef722ecba0 --- /dev/null +++ b/spring-sleuth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.spring.session.SleuthWebApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SleuthWebApp.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java b/spring-social-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 87% rename from spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java rename to spring-social-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 43aaea18b1..29ed401118 100644 --- a/spring-social-login/src/test/java/org/baeldung/test/ApplicationIntegrationTest.java +++ b/spring-social-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.test; +package org.baeldung; import org.baeldung.config.Application; import org.junit.Test; @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class ApplicationIntegrationTest { +public class SpringContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { diff --git a/spring-spel/pom.xml b/spring-spel/pom.xml index da8be2ca8d..4af318fde2 100644 --- a/spring-spel/pom.xml +++ b/spring-spel/pom.xml @@ -3,8 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - spel + spring-spel 1.0-SNAPSHOT + Spring SpEL com.baeldung diff --git a/spring-spel/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-spel/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f394374a94 --- /dev/null +++ b/spring-spel/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"classpath:applicationContext.xml"}) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-state-machine/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-state-machine/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..72292a5089 --- /dev/null +++ b/spring-state-machine/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,23 @@ +package org.baeldung; + +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.spring.statemachine.config.ForkJoinStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.HierarchicalStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.SimpleEnumStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SimpleStateMachineConfiguration.class, SimpleEnumStateMachineConfiguration.class, + JunctionStateMachineConfiguration.class, HierarchicalStateMachineConfiguration.class, + ForkJoinStateMachineConfiguration.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-static-resources/src/main/resources/logback.xml b/spring-static-resources/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-static-resources/src/main/resources/logback.xml +++ b/spring-static-resources/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml index d14dcc3176..8e551d850f 100644 --- a/spring-swagger-codegen/pom.xml +++ b/spring-swagger-codegen/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-swagger-codegen 0.0.1-SNAPSHOT pom diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md b/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md index b1b7a63a9c..455a69b2f3 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/README.md @@ -153,3 +153,5 @@ It's recommended to create an instance of `ApiClient` per thread in a multithrea apiteam@swagger.io + + diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index aac6fe9843..06a92ffae7 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -2,11 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - com.baeldung spring-swagger-codegen-api-client jar spring-swagger-codegen-api-client - 0.0.1-SNAPSHOT https://github.com/swagger-api/swagger-codegen Swagger Java @@ -14,9 +12,7 @@ scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen - - 2.2.0 - + Unlicense @@ -42,37 +38,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - - org.apache.maven.plugins diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml index ece534dc74..4aff696828 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml @@ -1,11 +1,8 @@ 4.0.0 - - com.baeldung spring-swagger-codegen-app - 0.0.1-SNAPSHOT - + com.baeldung spring-swagger-codegen @@ -24,6 +21,12 @@ spring-boot-starter-web ${spring.version} + + org.springframework.boot + spring-boot-starter-test + ${spring.version} + test + @@ -31,14 +34,13 @@ org.springframework.boot spring-boot-maven-plugin + ${spring.version} - 1.8 0.0.1-SNAPSHOT 1.5.10.RELEASE - - \ No newline at end of file + diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2143dc7f4d --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.petstore.app.PetStoreApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PetStoreApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 0dcb742c09..f9e7dd90a7 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -17,6 +17,7 @@ - [Working With Arrays in Thymeleaf](http://www.baeldung.com/thymeleaf-arrays) - [Spring with Thymeleaf Pagination for a List](http://www.baeldung.com/spring-thymeleaf-pagination) - [Working with Select and Option in Thymeleaf](http://www.baeldung.com/thymeleaf-select-option) +- [Working With Custom HTML Attributes in Thymeleaf](https://www.baeldung.com/thymeleaf-custom-html-attributes) ### Build the Project diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index c023dcdb5f..0926728aba 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-thymeleaf @@ -8,8 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 @@ -17,7 +18,7 @@ org.springframework spring-context - ${org.springframework-version} + ${spring.version} @@ -29,19 +30,38 @@ org.springframework spring-webmvc - ${org.springframework-version} + ${spring.version} + + + org.springframework.data + spring-data-commons + ${spring-data.version} + + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + org.springframework.security spring-security-web - ${springframework-security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${springframework-security.version} + ${spring-security.version} + org.thymeleaf @@ -50,10 +70,9 @@ org.thymeleaf - thymeleaf-spring4 + thymeleaf-spring5 ${org.thymeleaf-version} - nz.net.ultraq.thymeleaf thymeleaf-layout-dialect @@ -64,60 +83,29 @@ thymeleaf-extras-java8time ${org.thymeleaf.extras-version} + javax.servlet javax.servlet-api - ${javax.servlet-version} + ${javax.servlet-api.version} provided - - - javax.validation - validation-api - ${javax.validation-version} - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - + org.springframework spring-test - ${org.springframework-version} + ${spring.version} test - org.springframework.security spring-security-test - ${springframework-security.version} + ${spring-security.version} test - - - - - - org.springframework.data - spring-data-commons - ${springFramework-data.version} - @@ -131,7 +119,7 @@ false - + org.codehaus.cargo cargo-maven2-plugin @@ -151,7 +139,7 @@ - + org.apache.tomcat.maven tomcat7-maven-plugin @@ -176,22 +164,14 @@ - - 4.3.4.RELEASE - 4.2.0.RELEASE - 2.0.7.RELEASE - 3.1.0 - + 2.0.9.RELEASE 3.0.9.RELEASE - 3.0.0.RELEASE - 2.1.2 - - 1.1.0.Final - 5.3.3.Final - 5.2.5.Final + 3.0.1.RELEASE + 2.3.0 + 2.0.1.Final + 6.0.11.Final - 2.6 1.6.1 2.2 diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java index 2e76877199..34a59ea391 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -2,6 +2,9 @@ package com.baeldung.thymeleaf.config; import java.util.Locale; +import nz.net.ultraq.thymeleaf.LayoutDialect; +import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; + import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; @@ -15,23 +18,20 @@ import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; -import org.thymeleaf.TemplateEngine; import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect; -import org.thymeleaf.spring4.SpringTemplateEngine; -import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; -import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.spring5.ISpringTemplateEngine; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring5.view.ThymeleafViewResolver; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ITemplateResolver; import com.baeldung.thymeleaf.formatter.NameFormatter; import com.baeldung.thymeleaf.utils.ArrayUtil; -import nz.net.ultraq.thymeleaf.LayoutDialect; -import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; - @Configuration @EnableWebMvc @ComponentScan({ "com.baeldung.thymeleaf" }) @@ -39,10 +39,11 @@ import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; * Java configuration file that is used for Spring MVC and Thymeleaf * configurations */ -public class WebMVCConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware { +public class WebMVCConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; + @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @@ -77,7 +78,7 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application return resolver; } - private TemplateEngine templateEngine(ITemplateResolver templateResolver) { + private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.addDialect(new LayoutDialect(new GroupingStrategy())); engine.addDialect(new Java8TimeDialect()); diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java index 46bff38a3f..ea51ca3cd9 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java @@ -27,7 +27,7 @@ public class WebMVCSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER"); + auth.inMemoryAuthentication().withUser("user1").password("{noop}user1Pass").authorities("ROLE_USER"); } @Override diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/CourseRegistrationController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/CourseRegistrationController.java new file mode 100644 index 0000000000..2d2b5906e1 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/CourseRegistrationController.java @@ -0,0 +1,30 @@ +package com.baeldung.thymeleaf.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.baeldung.thymeleaf.model.Course; + +/** + * Handles requests for the student model. + * + */ +@Controller +public class CourseRegistrationController { + + @RequestMapping(value = "/registerCourse", method = RequestMethod.POST) + public String register(@ModelAttribute Course course, Model model) { + model.addAttribute("successMessage", "You have successfully registered for course: " + course.getName() + "."); + return "courseRegistration.html"; + } + + @RequestMapping(value = "/registerCourse", method = RequestMethod.GET) + public String register(Model model) { + model.addAttribute("course", new Course()); + return "courseRegistration.html"; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Course.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Course.java new file mode 100644 index 0000000000..df2e9cd097 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Course.java @@ -0,0 +1,52 @@ +package com.baeldung.thymeleaf.model; + +import java.util.Date; + +public class Course { + + private String name; + private String description; + private Date startDate; + private Date endDate; + private String teacher; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public String getTeacher() { + return teacher; + } + + public void setTeacher(String teacher) { + this.teacher = teacher; + } +} diff --git a/spring-thymeleaf/src/main/resources/logback.xml b/spring-thymeleaf/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/spring-thymeleaf/src/main/resources/logback.xml +++ b/spring-thymeleaf/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/courseRegistration.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/courseRegistration.html new file mode 100644 index 0000000000..cfce92d055 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/courseRegistration.html @@ -0,0 +1,42 @@ + + + +Register for course + + + + +

    Register Here

    +
    + + + + + + + + + +
    +
    + + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html index b458f7270c..25ff6a19bb 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html @@ -24,6 +24,9 @@ + + + diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsIntegrationTest.java index 5bc45d0004..c6158b76b1 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsIntegrationTest.java @@ -1,10 +1,22 @@ package com.baeldung.thymeleaf.controller; +import static org.hamcrest.Matchers.containsString; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import javax.servlet.Filter; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -15,21 +27,6 @@ import com.baeldung.thymeleaf.config.WebApp; import com.baeldung.thymeleaf.config.WebMVCConfig; import com.baeldung.thymeleaf.config.WebMVCSecurity; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import javax.servlet.Filter; - -import static org.hamcrest.Matchers.containsString; - @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) diff --git a/spring-thymeleaf/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..c7a0b4fc60 --- /dev/null +++ b/spring-thymeleaf/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,22 @@ +package org.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.web.WebAppConfiguration; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..825b89eb10 --- /dev/null +++ b/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.custom.config.MvcConfig; +import org.baeldung.custom.config.PersistenceDerbyJPAConfig; +import org.baeldung.custom.config.SecSecurityConfig; +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 = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-vault/README.md b/spring-vault/README.md new file mode 100644 index 0000000000..8db065a3dd --- /dev/null +++ b/spring-vault/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring Vault](https://www.baeldung.com/spring-vault) diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml new file mode 100644 index 0000000000..31616cdb16 --- /dev/null +++ b/spring-vault/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + com.baeldung + spring-vault + 0.0.1-SNAPSHOT + jar + spring-vault + Spring Vault sample project + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.vault + spring-vault-core + ${spring.vault.core.version} + + + com.fasterxml.jackson.core + jackson-databind + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + + + + + + UTF-8 + 2.0.1.RELEASE + + diff --git a/spring-vault/src/main/java/org/baeldung/springvault/Credentials.java b/spring-vault/src/main/java/org/baeldung/springvault/Credentials.java new file mode 100644 index 0000000000..f90ab66a4e --- /dev/null +++ b/spring-vault/src/main/java/org/baeldung/springvault/Credentials.java @@ -0,0 +1,30 @@ +package org.baeldung.springvault; + +public class Credentials { + + private String username; + private String password; + + public Credentials() { + + } + + public Credentials(String username, String password) { + this.username = username; + this.password = password; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + @Override + public String toString() { + return "Credential [username=" + username + ", password=" + password + "]"; + } + +} diff --git a/spring-vault/src/main/java/org/baeldung/springvault/CredentialsService.java b/spring-vault/src/main/java/org/baeldung/springvault/CredentialsService.java new file mode 100644 index 0000000000..87c24bd947 --- /dev/null +++ b/spring-vault/src/main/java/org/baeldung/springvault/CredentialsService.java @@ -0,0 +1,50 @@ +package org.baeldung.springvault; + +import java.net.URI; +import java.net.URISyntaxException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.vault.authentication.TokenAuthentication; +import org.springframework.vault.client.VaultEndpoint; +import org.springframework.vault.core.VaultTemplate; +import org.springframework.vault.core.env.VaultPropertySource; +import org.springframework.vault.support.VaultResponse; +import org.springframework.vault.support.VaultResponseSupport; + +/** + * Sample service to demonstrate storing and retrieval of secrets. + * + * NOTE: We need to configure Vault and provide the Vault uri in the properties file. + * + */ +@Service +public class CredentialsService { + + @Autowired + private VaultTemplate vaultTemplate; + + /** + * To Secure Credentials + * @param credentials + * @return VaultResponse + * @throws URISyntaxException + */ + public void secureCredentials(Credentials credentials) throws URISyntaxException { + + vaultTemplate.write("credentials/myapp", credentials); + } + + /** + * To Retrieve Credentials + * @return Credentials + * @throws URISyntaxException + */ + public Credentials accessCredentials() throws URISyntaxException { + + VaultResponseSupport response = vaultTemplate.read("credentials/myapp", Credentials.class); + return response.getData(); + } + +} diff --git a/spring-vault/src/main/java/org/baeldung/springvault/SpringVaultApplication.java b/spring-vault/src/main/java/org/baeldung/springvault/SpringVaultApplication.java new file mode 100644 index 0000000000..916a809be5 --- /dev/null +++ b/spring-vault/src/main/java/org/baeldung/springvault/SpringVaultApplication.java @@ -0,0 +1,17 @@ +package org.baeldung.springvault; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Sample application to demonstrate basics of Spring Vault + * + */ +@SpringBootApplication +public class SpringVaultApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringVaultApplication.class, args); + } + +} diff --git a/spring-vault/src/main/java/org/baeldung/springvault/VaultConfig.java b/spring-vault/src/main/java/org/baeldung/springvault/VaultConfig.java new file mode 100644 index 0000000000..106a1a3d42 --- /dev/null +++ b/spring-vault/src/main/java/org/baeldung/springvault/VaultConfig.java @@ -0,0 +1,26 @@ +package org.baeldung.springvault; + +import org.springframework.context.annotation.Configuration; +import org.springframework.vault.authentication.ClientAuthentication; +import org.springframework.vault.authentication.TokenAuthentication; +import org.springframework.vault.client.VaultEndpoint; +import org.springframework.vault.config.AbstractVaultConfiguration; + +/** + * Example class to configure Vault beans using AbstractVaultConfiguration + * + */ +@Configuration +public class VaultConfig extends AbstractVaultConfiguration { + + @Override + public ClientAuthentication clientAuthentication() { + return new TokenAuthentication("00000000-0000-0000-0000-000000000000"); + } + + @Override + public VaultEndpoint vaultEndpoint() { + return VaultEndpoint.create("host", 8020); + } + +} diff --git a/spring-vault/src/main/java/org/baeldung/springvault/VaultEnvironmentConfig.java b/spring-vault/src/main/java/org/baeldung/springvault/VaultEnvironmentConfig.java new file mode 100644 index 0000000000..6c796bc718 --- /dev/null +++ b/spring-vault/src/main/java/org/baeldung/springvault/VaultEnvironmentConfig.java @@ -0,0 +1,21 @@ +package org.baeldung.springvault; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.PropertySource; +import org.springframework.vault.authentication.ClientAuthentication; +import org.springframework.vault.authentication.TokenAuthentication; +import org.springframework.vault.client.VaultEndpoint; +import org.springframework.vault.config.AbstractVaultConfiguration; +import org.springframework.vault.config.EnvironmentVaultConfiguration; + +/** + * Example class to configure Vault beans using EnvironmentVaultConfiguration + * + */ +@Configuration +@PropertySource(value = { "vault-config.properties" }) +@Import(value = EnvironmentVaultConfiguration.class) +public class VaultEnvironmentConfig { + +} diff --git a/spring-vault/src/main/resources/vault-config.properties b/spring-vault/src/main/resources/vault-config.properties new file mode 100644 index 0000000000..68a080ebe8 --- /dev/null +++ b/spring-vault/src/main/resources/vault-config.properties @@ -0,0 +1,2 @@ +vault.uri=https://localhost:8200 +vault.token=00000000-0000-0000-0000-000000000000 \ No newline at end of file diff --git a/spring-vault/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-vault/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a2d727ea79 --- /dev/null +++ b/spring-vault/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.springvault.SpringVaultApplication; +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 = SpringVaultApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-vault/src/test/java/org/baeldung/springvault/VaultInitializer.java b/spring-vault/src/test/java/org/baeldung/springvault/VaultInitializer.java new file mode 100644 index 0000000000..c7db5eb199 --- /dev/null +++ b/spring-vault/src/test/java/org/baeldung/springvault/VaultInitializer.java @@ -0,0 +1,113 @@ +package org.baeldung.springvault; + +import java.io.BufferedReader; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Map; + +/** + * + * This is a test class to initialize Vault. + */ +public class VaultInitializer implements Closeable { + + private static final String UNSEAL_KEY = "Unseal Key:"; + private static final String ROOT_TOKEN = "Root Token:"; + + private Process vaultProcess; + private String unSealKey; + private String rootToken; + + public String getRootToken() { + return rootToken; + } + + public String getUnSealKey() { + return unSealKey; + } + + public static final VaultInitializer initializeValut() { + VaultInitializer vaultProcess = new VaultInitializer(); + vaultProcess.start(); + // Secrets is by default enabled. + vaultProcess.enableSecrets(); + return vaultProcess; + } + + @SuppressWarnings("unused") + private void enableSecrets() { + System.out.println("Enabling Secrets at path credentials/myapp..."); + ProcessBuilder pb = new ProcessBuilder("vault", "secrets", "enable", "-path=credentials/myapp", "kv"); + Map map = pb.environment(); + map.put("VAULT_ADDR", "http://127.0.0.1:8200"); + try { + Process p = pb.inheritIO() + .start(); + p.waitFor(); + } catch (IOException e) { + System.out.println("unable to enableSecrets" + e); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public void start() { + System.out.println("starting vault"); + // This starts the vault server. + ProcessBuilder pb = new ProcessBuilder("vault", "server", "-dev"); + + try { + vaultProcess = pb.start(); + // wait for initialization to complete. + Thread.sleep(5000); + } catch (IOException e) { + System.out.println("unable to start vault in new process" + e); + } catch (InterruptedException e) { + System.out.println("Thread interrupted " + e); + } + extractUnsealKeyAndToken(); + } + + /** + * To get the root token which is generated every time server is initialized. + */ + private void extractUnsealKeyAndToken() { + BufferedReader reader = new BufferedReader(new InputStreamReader(vaultProcess.getInputStream())); + StringBuilder builder = new StringBuilder(); + String line = null; + boolean tokenExtracted = false; + try { + while ((line = reader.readLine()) != null) { + builder.append(line); + builder.append(System.getProperty("line.separator")); + if (line.contains(UNSEAL_KEY)) { + String tmp = line.replace(UNSEAL_KEY, ""); + unSealKey = tmp.trim(); + } else if (line.contains(ROOT_TOKEN)) { + String tmp = line.replace(ROOT_TOKEN, ""); + rootToken = tmp.trim(); + tokenExtracted = true; + } + if (tokenExtracted) + break; + System.out.println(line); + } + } catch (IOException e) { + System.out.println("unable to read vault output" + e); + } + + String result = builder.toString(); + + System.out.println("Unseal Key {}" + unSealKey); + System.out.println("Root Token {}" + rootToken); + System.out.println(result); + } + + @Override + public void close() throws IOException { + + System.out.println("stoping vault"); + vaultProcess.destroy(); + } +} diff --git a/spring-vault/src/test/java/org/baeldung/springvault/VaultIntegrationTest.java b/spring-vault/src/test/java/org/baeldung/springvault/VaultIntegrationTest.java new file mode 100644 index 0000000000..75c700ee26 --- /dev/null +++ b/spring-vault/src/test/java/org/baeldung/springvault/VaultIntegrationTest.java @@ -0,0 +1,80 @@ +package org.baeldung.springvault; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.annotation.Order; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.vault.authentication.TokenAuthentication; +import org.springframework.vault.client.VaultEndpoint; +import org.springframework.vault.core.VaultTemplate; +import org.springframework.vault.support.VaultResponse; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CredentialsService.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ContextConfiguration(classes = VaultTestConfiguration.class, loader = AnnotationConfigContextLoader.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@DirtiesContext(classMode = ClassMode.AFTER_CLASS) +public class VaultIntegrationTest { + + @Autowired + private CredentialsService credentialsService; + + /** + * Test to secure credentials. + * + * @throws URISyntaxException + */ + @Test + public void givenCredentials_whenSecureCredentials_thenCredentialsSecured() throws URISyntaxException { + try { + // Given + Credentials credentials = new Credentials("username", "password"); + + // When + credentialsService.secureCredentials(credentials); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + /** + * Test to access credentials + * @throws URISyntaxException + */ + @Test + public void whenAccessCredentials_thenCredentialsRetrieved() throws URISyntaxException { + + // Given + Credentials credentials = credentialsService.accessCredentials(); + + // Then + assertNotNull(credentials); + assertEquals("username", credentials.getUsername()); + assertEquals("password", credentials.getPassword()); + } + +} diff --git a/spring-vault/src/test/java/org/baeldung/springvault/VaultTestConfiguration.java b/spring-vault/src/test/java/org/baeldung/springvault/VaultTestConfiguration.java new file mode 100644 index 0000000000..09a1445788 --- /dev/null +++ b/spring-vault/src/test/java/org/baeldung/springvault/VaultTestConfiguration.java @@ -0,0 +1,29 @@ +package org.baeldung.springvault; + +import java.net.URI; +import java.net.URISyntaxException; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.vault.authentication.TokenAuthentication; +import org.springframework.vault.client.VaultEndpoint; +import org.springframework.vault.core.VaultTemplate; + +@Configuration +public class VaultTestConfiguration { + + @Bean + public VaultInitializer vaultInitializer() { + VaultInitializer vaultInitializer = VaultInitializer.initializeValut(); + return vaultInitializer; + } + + @Bean + public VaultTemplate vaultTemplate() throws URISyntaxException { + + VaultInitializer vaultInitializer = vaultInitializer(); + VaultTemplate vaultTemplate = new VaultTemplate(VaultEndpoint.from(new URI("http://localhost:8200")), new TokenAuthentication(vaultInitializer.getRootToken())); + return vaultTemplate; + + } +} diff --git a/spring-vertx/pom.xml b/spring-vertx/pom.xml index 4ba90b841e..790eeff128 100644 --- a/spring-vertx/pom.xml +++ b/spring-vertx/pom.xml @@ -3,11 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung - vertx-spring - 0.0.1-SNAPSHOT + spring-vertx jar - spring-vertx + Spring Vertx A demo project with vertx spring integration @@ -57,31 +55,10 @@ org.springframework.boot spring-boot-maven-plugin
    - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - UTF-8 - UTF-8 - 1.8 3.4.1 diff --git a/spring-vertx/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-vertx/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..b1f7b39f7e --- /dev/null +++ b/spring-vertx/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +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.vertxspring.VertxSpringApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = VertxSpringApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..35efff49c2 --- /dev/null +++ b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.amqp.SpringWebfluxAmqpApplication; +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 = SpringWebfluxAmqpApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..623966373b --- /dev/null +++ b/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.ResourceServerApplication; +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 = ResourceServerApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a3d49627e5 --- /dev/null +++ b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.UiApplication; +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 = UiApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java b/static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java similarity index 92% rename from static-analysis/src/test/java/com/baeldung/pmd/CntTest.java rename to static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java index ed72602f99..cdbf9f6f5e 100644 --- a/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java +++ b/static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java @@ -4,7 +4,7 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; -public class CntTest { +public class CntUnitTest { private Cnt service; diff --git a/struts-2/pom.xml b/struts-2/pom.xml index 26998fa544..fee68c8303 100644 --- a/struts-2/pom.xml +++ b/struts-2/pom.xml @@ -2,10 +2,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - struts + struts-2 0.0.1-SNAPSHOT pom - struts + Struts 2 com.baeldung diff --git a/testing-modules/README.md b/testing-modules/README.md index b269f547ec..b189b9819e 100644 --- a/testing-modules/README.md +++ b/testing-modules/README.md @@ -13,3 +13,4 @@ - [Headers, Cookies and Parameters with REST-assured](http://www.baeldung.com/rest-assured-header-cookie-parameter) - [JSON Schema Validation with REST-assured](http://www.baeldung.com/rest-assured-json-schema) - [Testing Callbacks with Mockito](http://www.baeldung.com/mockito-callbacks) +- [Running JUnit Tests in Parallel with Maven](https://www.baeldung.com/maven-junit-parallel-tests) diff --git a/testing-modules/gatling/README.md b/testing-modules/gatling/README.md index 5c81c4bd6a..941ab75f06 100644 --- a/testing-modules/gatling/README.md +++ b/testing-modules/gatling/README.md @@ -1,2 +1,5 @@ ### Relevant Articles: - [Intro to Gatling](http://www.baeldung.com/introduction-to-gatling) + +### Running a simualtion +- To run a simulation use "simulation" profile, command - `mvn install -Psimulation -Dgib.enabled=false` diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index 1afaefd47e..8d4c89ec62 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -7,13 +7,13 @@ gatling 1.0-SNAPSHOT - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + io.gatling.highcharts @@ -68,6 +68,14 @@ + + + + + + simulation + + io.gatling gatling-maven-plugin @@ -78,11 +86,16 @@ execute + + true + + + @@ -113,10 +126,10 @@ 1.8 1.8 UTF-8 - 2.11.12 - 2.2.5 + 2.12.6 + 2.3.1 3.2.2 - 2.2.1 + 2.2.4
    diff --git a/testing-modules/java-faker/pom.xml b/testing-modules/java-faker/pom.xml deleted file mode 100644 index 4ac5368e24..0000000000 --- a/testing-modules/java-faker/pom.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - 4.0.0 - - com.baeldung - java-faker - 1.0-SNAPSHOT - - - - com.github.javafaker - javafaker - 0.15 - - - - - junit - junit - 4.12 - test - - - - - - diff --git a/testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java b/testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java deleted file mode 100644 index 8d89fa0ab2..0000000000 --- a/testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.baeldung; - -import com.github.javafaker.Faker; -import com.github.javafaker.service.FakeValuesService; -import com.github.javafaker.service.FakerIDN; -import com.github.javafaker.service.LocaleDoesNotExistException; -import com.github.javafaker.service.RandomService; -import javafx.scene.Parent; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.util.Locale; -import java.util.Random; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -public class JavaFakerTest { - - private Faker faker; - - @Before - public void setUp() throws Exception { - faker = new Faker(); - } - - @Test - public void givenJavaFaker_whenAddressObjectCalled_checkValidAddressInfoGiven() throws Exception { - - Faker faker = new Faker(); - - String streetName = faker.address().streetName(); - String number = faker.address().buildingNumber(); - String city = faker.address().city(); - String country = faker.address().country(); - - System.out.println(String.format("%s\n%s\n%s\n%s", - number, - streetName, - city, - country)); - - } - - @Test - public void givenJavaFakersWithSameSeed_whenNameCalled_CheckSameName() throws Exception { - - Faker faker1 = new Faker(new Random(24)); - Faker faker2 = new Faker(new Random(24)); - - assertEquals(faker1.name().firstName(), faker2.name().firstName()); - } - - @Test - public void givenJavaFakersWithDifferentLocals_checkZipCodesMatchRegex() throws Exception { - - Faker ukFaker = new Faker(new Locale("en-GB")); - Faker usFaker = new Faker(new Locale("en-US")); - - System.out.println(String.format("American zipcode: %s", usFaker.address().zipCode())); - System.out.println(String.format("British postcode: %s", ukFaker.address().zipCode())); - - Pattern ukPattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2})"); - Matcher ukMatcher = ukPattern.matcher(ukFaker.address().zipCode()); - - assertTrue(ukMatcher.find()); - - Matcher usMatcher = Pattern.compile("^\\d{5}(?:[-\\s]\\d{4})?$").matcher(usFaker.address().zipCode()); - - assertTrue(usMatcher.find()); - - } - - @Test - public void givenJavaFakerService_testFakersCreated() throws Exception { - - RandomService randomService = new RandomService(); - - System.out.println(randomService.nextBoolean()); - System.out.println(randomService.nextDouble()); - - Faker faker = new Faker(new Random(randomService.nextLong())); - - System.out.println(faker.address().city()); - - } - - @Test - public void testFakeValuesService() throws Exception { - - FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService()); - - String email = fakeValuesService.bothify("????##@gmail.com"); - Matcher emailMatcher = Pattern.compile("\\w{4}\\d{2}@gmail.com").matcher(email); - assertTrue(emailMatcher.find()); - - String alphaNumericString = fakeValuesService.regexify("[a-z1-9]{10}"); - Matcher alphaNumericMatcher = Pattern.compile("[a-z1-9]{10}").matcher(alphaNumericString); - assertTrue(alphaNumericMatcher.find()); - - } - - - @Test(expected = LocaleDoesNotExistException.class) - public void givenWrongLocale_whenFakerIsInitialised_testLocaleDoesNotExistExceptionIsThrown() throws Exception { - - Faker wrongLocaleFaker = new Faker(new Locale("en-seaWorld")); - - } -} diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 5a73bca4d6..836848282b 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -1,7 +1,6 @@ ### Relevant Articles: - [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) - [A Guide to JUnit 5](http://www.baeldung.com/junit-5) -- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) @@ -14,4 +13,5 @@ - [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) - [JUnit5 Programmatic Extension Registration with @RegisterExtension](http://www.baeldung.com/junit-5-registerextension-annotation) - [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order) - +- [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) +- [Testing an Abstract Class With JUnit](https://www.baeldung.com/junit-test-abstract-class) diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index c60cc00c2c..93365264ac 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -118,14 +118,14 @@ - 5.1.0 - 1.1.0 + 5.2.0 + 1.2.0 5.2.0 2.8.2 1.4.196 2.8.9 1.7.4 - 2.19.1 + 2.21.0 1.6.0 5.0.1.RELEASE diff --git a/testing-modules/junit5-migration/pom.xml b/testing-modules/junit5-migration/pom.xml index ae46b479bb..9d9d418774 100644 --- a/testing-modules/junit5-migration/pom.xml +++ b/testing-modules/junit5-migration/pom.xml @@ -80,10 +80,10 @@ - 5.1.0 - 1.1.0 + 5.2.0 + 1.2.0 5.2.0 - 2.19.1 + 2.21.0 1.6.0 diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 4b7dc70155..cab4d7977b 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -15,6 +15,6 @@
    - 2.8.9 + 2.21.0 diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index fab2fcc795..acdd7eb2ac 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -14,6 +14,27 @@
    + + + org.springframework + spring-core + ${spring-framework.version} + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework.data + spring-data-jpa + ${spring-data.version} + + + org.eclipse.persistence + javax.persistence + 2.1.1 + @@ -46,35 +67,15 @@ org.springframework.boot spring-boot-starter - LATEST + ${spring-boot.version} test org.springframework.boot spring-boot-starter-test - LATEST + ${spring-boot.version} test - - org.springframework - spring-core - LATEST - - - org.springframework - spring-context - LATEST - - - org.eclipse.persistence - javax.persistence - 2.1.1 - - - org.springframework.data - spring-data-jpa - LATEST - @@ -88,6 +89,9 @@ + 2.0.4.RELEASE + 5.0.8.RELEASE + 2.0.9.RELEASE 19.0 3.5 diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java index 206e0f4daf..118d50ea40 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java @@ -1,15 +1,15 @@ package org.baeldung.mockito; +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.Spy; -import org.mockito.runners.MockitoJUnitRunner; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class MockitoSpyIntegrationTest { diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java index 49360f8d6c..b020338fd9 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java @@ -1,14 +1,22 @@ package org.baeldung.mockito; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doCallRealMethod; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import org.junit.Test; import org.junit.runner.RunWith; -import static org.junit.Assert.assertEquals; - -import static org.mockito.Mockito.*; import org.mockito.ArgumentCaptor; -import static org.mockito.Matchers.any; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; -import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class MockitoVoidMethodsUnitTest { diff --git a/testing-modules/mocks/README.md b/testing-modules/mocks/README.md index fe8e197061..2b24ed8536 100644 --- a/testing-modules/mocks/README.md +++ b/testing-modules/mocks/README.md @@ -5,4 +5,4 @@ - [JMockit 101](http://www.baeldung.com/jmockit-101) - [Mockito vs EasyMock vs JMockit](http://www.baeldung.com/mockito-vs-easymock-vs-jmockit) - [EasyMock Argument Matchers](http://www.baeldung.com/easymock-argument-matchers) - +- [Mock Static Method using JMockit](https://www.baeldung.com/jmockit-static-method) diff --git a/testing-modules/mocks/jmockit/src/main/java/com/baeldung/mocks/jmockit/AppManager.java b/testing-modules/mocks/jmockit/src/main/java/com/baeldung/mocks/jmockit/AppManager.java new file mode 100644 index 0000000000..615650ea6d --- /dev/null +++ b/testing-modules/mocks/jmockit/src/main/java/com/baeldung/mocks/jmockit/AppManager.java @@ -0,0 +1,26 @@ +package com.baeldung.mocks.jmockit; + +import java.util.Random; + +public class AppManager { + + public boolean managerResponse(String question) { + return AppManager.isResponsePositive(question); + } + + public static boolean isResponsePositive(String value) { + if (value == null) + return false; + int orgLength = value.length(); + int randomNumber = randomNumber(); + return orgLength == randomNumber ? true : false; + } + + private static int randomNumber() { + return new Random().nextInt(7); + } + + private static Integer stringToInteger(String num) { + return Integer.parseInt(num); + } +} diff --git a/testing-modules/mocks/jmockit/src/test/java/com/baeldung/mocks/jmockit/AppManagerUnitTest.java b/testing-modules/mocks/jmockit/src/test/java/com/baeldung/mocks/jmockit/AppManagerUnitTest.java new file mode 100644 index 0000000000..2c5aa2a3ed --- /dev/null +++ b/testing-modules/mocks/jmockit/src/test/java/com/baeldung/mocks/jmockit/AppManagerUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.mocks.jmockit; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import mockit.Deencapsulation; +import mockit.Mock; +import mockit.MockUp; + +public class AppManagerUnitTest { + + private AppManager appManager; + + @BeforeEach + public void setUp() { + appManager = new AppManager(); + } + + @Test + public void givenAppManager_whenStaticMethodCalled_thenValidateExpectedResponse() { + new MockUp() { + @Mock + public boolean isResponsePositive(String value) { + return false; + } + }; + + Assertions.assertFalse(appManager.managerResponse("Why are you coming late?")); + } + + @Test + public void givenAppManager_whenPrivateStaticMethod_thenValidateExpectedResponse() { + final int response = Deencapsulation.invoke(AppManager.class, "stringToInteger", "110"); + Assertions.assertEquals(110, response); + } + + @Test + public void givenAppManager_whenPrivateStaticMethod_thenExpectException() { + Assertions.assertThrows(IllegalArgumentException.class, () -> { + Deencapsulation.invoke(AppManager.class, "stringToInteger", "11r"); + }); + } +} diff --git a/testing-modules/mocks/mock-comparisons/pom.xml b/testing-modules/mocks/mock-comparisons/pom.xml index 9424757a7a..ae36280300 100644 --- a/testing-modules/mocks/mock-comparisons/pom.xml +++ b/testing-modules/mocks/mock-comparisons/pom.xml @@ -46,9 +46,10 @@ - 2.9.0 + 2.21.0 3.5.1 - 1.34 + 1.41 + - \ No newline at end of file + diff --git a/testing-modules/parallel-tests-junit/math-test-functions/pom.xml b/testing-modules/parallel-tests-junit/math-test-functions/pom.xml new file mode 100644 index 0000000000..18d2b562f3 --- /dev/null +++ b/testing-modules/parallel-tests-junit/math-test-functions/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + com.baeldung + parallel-tests-junit + 0.0.1-SNAPSHOT + + math-test-functions + math-test-functions + http://maven.apache.org + + UTF-8 + + + + junit + junit + 4.12 + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.0 + + all + 10 + 2 + 2 + 6 + 3.5 + 5 + true + + FunctionTestSuite.class + + + + + + diff --git a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/MathFunctionTest.java b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ArithmeticFunctionTest.java similarity index 78% rename from testing-modules/parallel-tests-junit/src/test/java/com/baeldung/MathFunctionTest.java rename to testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ArithmeticFunctionTest.java index 9a609c3e93..df0aa695fc 100644 --- a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/MathFunctionTest.java +++ b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ArithmeticFunctionTest.java @@ -1,29 +1,28 @@ -package com.baeldung; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class MathFunctionTest { - - @Test - public void test_addingIntegers_returnsSum() throws InterruptedException { - assertEquals(22, Math.addExact(10, 12)); - - } - - @Test - public void test_multiplyingIntegers_returnsProduct() { - assertEquals(120, Math.multiplyExact(10, 12)); - } - - @Test - public void test_subtractingIntegers_returnsDifference() { - assertEquals(2, Math.subtractExact(12, 10)); - } - - @Test - public void test_minimumInteger() { - assertEquals(10, Math.min(10, 12)); - } -} +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ArithmeticFunctionTest { + + @Test + public void test_addingIntegers_returnsSum() { + assertEquals(22, Math.addExact(10, 12)); + } + + @Test + public void test_multiplyingIntegers_returnsProduct() { + assertEquals(120, Math.multiplyExact(10, 12)); + } + + @Test + public void test_subtractingIntegers_returnsDifference() { + assertEquals(2, Math.subtractExact(12, 10)); + } + + @Test + public void test_minimumInteger() { + assertEquals(10, Math.min(10, 12)); + } +} diff --git a/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ComparisonFunctionTest.java b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ComparisonFunctionTest.java new file mode 100644 index 0000000000..4f72c87279 --- /dev/null +++ b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ComparisonFunctionTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ComparisonFunctionTest { + + @Test + public void test_findMax() { + assertEquals(20, Math.max(10, 20)); + } + + @Test + public void test_findMin() { + assertEquals(10, Math.min(10, 20)); + } + +} diff --git a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/FunctionTestSuite.java b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/FunctionTestSuite.java similarity index 71% rename from testing-modules/parallel-tests-junit/src/test/java/com/baeldung/FunctionTestSuite.java rename to testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/FunctionTestSuite.java index c7f4050b18..4fe551b365 100644 --- a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/FunctionTestSuite.java +++ b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/FunctionTestSuite.java @@ -1,11 +1,11 @@ -package com.baeldung; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({StringFunctionTest.class, MathFunctionTest.class}) -public class FunctionTestSuite { - -} +package com.baeldung; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ ComparisonFunctionTest.class, ArithmeticFunctionTest.class }) +public class FunctionTestSuite { + +} diff --git a/testing-modules/parallel-tests-junit/pom.xml b/testing-modules/parallel-tests-junit/pom.xml index 1a42437b1b..3fd4e695e5 100644 --- a/testing-modules/parallel-tests-junit/pom.xml +++ b/testing-modules/parallel-tests-junit/pom.xml @@ -1,50 +1,12 @@ - - 4.0.0 - - com.baeldung - parallel-tests-junit - 0.0.1-SNAPSHOT - jar - - parallel-tests-junit - http://maven.apache.org - - - UTF-8 - - - - - junit - junit - 4.12 - test - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.0 - - all - 10 - 2 - 2 - 6 - 3.5 - 5 - true - - FunctionTestSuite.class - - - - - - - + + + 4.0.0 + com.baeldung + parallel-tests-junit + 0.0.1-SNAPSHOT + pom + + math-test-functions + string-test-functions + diff --git a/testing-modules/parallel-tests-junit/string-test-functions/pom.xml b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml new file mode 100644 index 0000000000..af61cfce8e --- /dev/null +++ b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + com.baeldung + parallel-tests-junit + 0.0.1-SNAPSHOT + + string-test-functions + string-test-functions + http://maven.apache.org + + UTF-8 + + + + + junit + junit + 4.12 + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.0 + + all + true + 2 + + + + + diff --git a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/StringFunctionTest.java b/testing-modules/parallel-tests-junit/string-test-functions/src/test/java/com/baeldung/StringFunctionTest.java similarity index 94% rename from testing-modules/parallel-tests-junit/src/test/java/com/baeldung/StringFunctionTest.java rename to testing-modules/parallel-tests-junit/string-test-functions/src/test/java/com/baeldung/StringFunctionTest.java index 9adfea8ff0..7f2bc5e5e7 100644 --- a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/StringFunctionTest.java +++ b/testing-modules/parallel-tests-junit/string-test-functions/src/test/java/com/baeldung/StringFunctionTest.java @@ -1,18 +1,18 @@ -package com.baeldung; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class StringFunctionTest { - - @Test - public void test_upperCase() { - assertEquals("TESTCASE", "testCase".toUpperCase()); - } - - @Test - public void test_indexOf() { - assertEquals(1, "testCase".indexOf("e")); - } -} +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class StringFunctionTest { + + @Test + public void test_upperCase() { + assertEquals("TESTCASE", "testCase".toUpperCase()); + } + + @Test + public void test_indexOf() { + assertEquals(1, "testCase".indexOf("e")); + } +} diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index 0e54980683..9bfd715682 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -106,6 +106,46 @@ true + + + + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + classes + 4 + + + + + integration-test + verify + + + + + + com.github.temyers + cucumber-jvm-parallel-plugin + 5.0.0 + + + generateRunners + generate-test-sources + + generateRunners + + + + com.baeldung.rest.cucumber + + src/test/resources/Feature/ + SCENARIO + + + + + diff --git a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java index b461da8403..35a913ae25 100644 --- a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java +++ b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java @@ -1,19 +1,5 @@ package com.baeldung.rest.cucumber; -import com.github.tomakehurst.wiremock.WireMockServer; -import cucumber.api.java.en.Then; -import cucumber.api.java.en.When; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Scanner; - import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.containing; @@ -25,10 +11,27 @@ import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import java.io.IOException; +import java.io.InputStream; +import java.util.Scanner; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; + +import com.github.tomakehurst.wiremock.WireMockServer; + +import cucumber.api.java.en.Then; +import cucumber.api.java.en.When; + public class StepDefinition { private static final String CREATE_PATH = "/create"; @@ -37,20 +40,20 @@ public class StepDefinition { private final InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("cucumber.json"); private final String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); - private final WireMockServer wireMockServer = new WireMockServer(); + private final WireMockServer wireMockServer = new WireMockServer(options().dynamicPort()); private final CloseableHttpClient httpClient = HttpClients.createDefault(); @When("^users upload data on a project$") public void usersUploadDataOnAProject() throws IOException { wireMockServer.start(); - configureFor("localhost", 8080); + configureFor("localhost", wireMockServer.port()); stubFor(post(urlEqualTo(CREATE_PATH)) .withHeader("content-type", equalTo(APPLICATION_JSON)) .withRequestBody(containing("testing-framework")) .willReturn(aResponse().withStatus(200))); - HttpPost request = new HttpPost("http://localhost:8080/create"); + HttpPost request = new HttpPost("http://localhost:" + wireMockServer.port() + "/create"); StringEntity entity = new StringEntity(jsonString); request.addHeader("content-type", APPLICATION_JSON); request.setEntity(entity); @@ -67,11 +70,11 @@ public class StepDefinition { public void usersGetInformationOnAProject(String projectName) throws IOException { wireMockServer.start(); - configureFor("localhost", 8080); + configureFor("localhost", wireMockServer.port()); stubFor(get(urlEqualTo("/projects/cucumber")).withHeader("accept", equalTo(APPLICATION_JSON)) .willReturn(aResponse().withBody(jsonString))); - HttpGet request = new HttpGet("http://localhost:8080/projects/" + projectName.toLowerCase()); + HttpGet request = new HttpGet("http://localhost:" + wireMockServer.port() + "/projects/" + projectName.toLowerCase()); request.addHeader("accept", APPLICATION_JSON); HttpResponse httpResponse = httpClient.execute(request); String responseString = convertResponseToString(httpResponse); diff --git a/testing-modules/rest-testing/src/test/resources/Feature/cucumber.feature b/testing-modules/rest-testing/src/test/resources/Feature/cucumber.feature new file mode 100644 index 0000000000..99dd8249fe --- /dev/null +++ b/testing-modules/rest-testing/src/test/resources/Feature/cucumber.feature @@ -0,0 +1,10 @@ +Feature: Testing a REST API + Users should be able to submit GET and POST requests to a web service, represented by WireMock + + Scenario: Data Upload to a web service + When users upload data on a project + Then the server should handle it and return a success status + + Scenario: Data retrieval from a web service + When users want to get information on the Cucumber project + Then the requested data is returned \ No newline at end of file diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index aed330d260..e22c3e84e7 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: -* [Mockito.mock() vs @Mock vs @MockBean](http://www.baeldung.com/java-spring-mockito-mock-mockbean) +- [Mockito.mock() vs @Mock vs @MockBean](http://www.baeldung.com/java-spring-mockito-mock-mockbean) +- [A Quick Guide to @TestPropertySource](https://www.baeldung.com/spring-test-property-source) diff --git a/testing-modules/spring-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java b/testing-modules/spring-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java new file mode 100644 index 0000000000..d545daf0df --- /dev/null +++ b/testing-modules/spring-testing/src/main/java/com/baeldung/testpropertysource/ClassUsingProperty.java @@ -0,0 +1,15 @@ +package com.baeldung.testpropertysource; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class ClassUsingProperty { + + @Value("${baeldung.testpropertysource.one}") + private String propertyOne; + + public String retrievePropertyOne() { + return propertyOne; + } +} diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java new file mode 100644 index 0000000000..f983abdd54 --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.testpropertysource; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ClassUsingProperty.class) +@TestPropertySource +public class DefaultTestPropertySourceIntegrationTest { + + @Autowired + ClassUsingProperty classUsingProperty; + + @Test + public void givenDefaultTestPropertySource_whenVariableOneRetrieved_thenValueInDefaultFileReturned() { + String output = classUsingProperty.retrievePropertyOne(); + + assertThat(output).isEqualTo("default-value"); + } +} diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java new file mode 100644 index 0000000000..93d4cc58da --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/LocationTestPropertySourceIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.testpropertysource; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ClassUsingProperty.class) +@TestPropertySource(locations = "/other-location.properties") +public class LocationTestPropertySourceIntegrationTest { + + @Autowired + ClassUsingProperty classUsingProperty; + + @Test + public void givenDefaultTestPropertySource_whenVariableOneRetrieved_thenValueInDefaultFileReturned() { + String output = classUsingProperty.retrievePropertyOne(); + + assertThat(output).isEqualTo("other-location-value"); + } +} diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java new file mode 100644 index 0000000000..d98e2b9f98 --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/testpropertysource/PropertiesTestPropertySourceIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.testpropertysource; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ClassUsingProperty.class) +@TestPropertySource(locations = "/other-location.properties", properties = "baeldung.testpropertysource.one=other-properties-value") +public class PropertiesTestPropertySourceIntegrationTest { + + @Autowired + ClassUsingProperty classUsingProperty; + + @Test + public void givenDefaultTestPropertySource_whenVariableOneRetrieved_thenValueInDefaultFileReturned() { + String output = classUsingProperty.retrievePropertyOne(); + + assertThat(output).isEqualTo("other-properties-value"); + } +} diff --git a/testing-modules/spring-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties b/testing-modules/spring-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties new file mode 100644 index 0000000000..a443a2b776 --- /dev/null +++ b/testing-modules/spring-testing/src/test/resources/com/baeldung/testpropertysource/DefaultTestPropertySourceIntegrationTest.properties @@ -0,0 +1 @@ +baeldung.testpropertysource.one=default-value \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/resources/other-location.properties b/testing-modules/spring-testing/src/test/resources/other-location.properties new file mode 100644 index 0000000000..6ef791ec75 --- /dev/null +++ b/testing-modules/spring-testing/src/test/resources/other-location.properties @@ -0,0 +1 @@ +baeldung.testpropertysource.one=other-location-value \ No newline at end of file diff --git a/testing-modules/test-containers/pom.xml b/testing-modules/test-containers/pom.xml index 2a8f434040..1f4c483988 100644 --- a/testing-modules/test-containers/pom.xml +++ b/testing-modules/test-containers/pom.xml @@ -104,12 +104,12 @@ 4.12.1 2.8.2 1.4.196 - 2.11.0 + 2.21.0 5.0.1.RELEASE 1.7.2 42.2.2 3.12.0 - 2.19.1 + 2.21.0 diff --git a/testing-modules/testing/README.md b/testing-modules/testing/README.md index c9c656dde9..849b578a55 100644 --- a/testing-modules/testing/README.md +++ b/testing-modules/testing/README.md @@ -19,3 +19,5 @@ - [Guide to JSpec](http://www.baeldung.com/jspec) - [Custom Assertions with AssertJ](http://www.baeldung.com/assertj-custom-assertion) - [Using Conditions with AssertJ](http://www.baeldung.com/assertj-conditions) +- [Guide to JavaFaker](https://www.baeldung.com/java-faker) +- [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) diff --git a/testing-modules/testing/pom.xml b/testing-modules/testing/pom.xml index 7b2fe76d0f..2e783b2116 100644 --- a/testing-modules/testing/pom.xml +++ b/testing-modules/testing/pom.xml @@ -88,6 +88,11 @@ javalite-common ${javalite.version} + + com.github.javafaker + javafaker + 0.15 + diff --git a/testing-modules/testing/src/test/java/com/baeldung/javafaker/JavaFakerUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/javafaker/JavaFakerUnitTest.java new file mode 100644 index 0000000000..7a3b9771fb --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/javafaker/JavaFakerUnitTest.java @@ -0,0 +1,121 @@ +package com.baeldung.javafaker; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Locale; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Before; +import org.junit.Test; + +import com.github.javafaker.Faker; +import com.github.javafaker.service.FakeValuesService; +import com.github.javafaker.service.LocaleDoesNotExistException; +import com.github.javafaker.service.RandomService; + +public class JavaFakerUnitTest { + + private Faker faker; + + @Before + public void setUp() throws Exception { + faker = new Faker(); + } + + @Test + public void givenJavaFaker_whenAddressObjectCalled_checkValidAddressInfoGiven() throws Exception { + + Faker faker = new Faker(); + + String streetName = faker.address() + .streetName(); + String number = faker.address() + .buildingNumber(); + String city = faker.address() + .city(); + String country = faker.address() + .country(); + + System.out.println(String.format("%s\n%s\n%s\n%s", number, streetName, city, country)); + + } + + @Test + public void givenJavaFakersWithSameSeed_whenNameCalled_CheckSameName() throws Exception { + + Faker faker1 = new Faker(new Random(24)); + Faker faker2 = new Faker(new Random(24)); + + assertEquals(faker1.name() + .firstName(), + faker2.name() + .firstName()); + } + + @Test + public void givenJavaFakersWithDifferentLocals_checkZipCodesMatchRegex() throws Exception { + + Faker ukFaker = new Faker(new Locale("en-GB")); + Faker usFaker = new Faker(new Locale("en-US")); + + System.out.println(String.format("American zipcode: %s", usFaker.address() + .zipCode())); + System.out.println(String.format("British postcode: %s", ukFaker.address() + .zipCode())); + + Pattern ukPattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2})"); + Matcher ukMatcher = ukPattern.matcher(ukFaker.address() + .zipCode()); + + assertTrue(ukMatcher.find()); + + Matcher usMatcher = Pattern.compile("^\\d{5}(?:[-\\s]\\d{4})?$") + .matcher(usFaker.address() + .zipCode()); + + assertTrue(usMatcher.find()); + + } + + @Test + public void givenJavaFakerService_testFakersCreated() throws Exception { + + RandomService randomService = new RandomService(); + + System.out.println(randomService.nextBoolean()); + System.out.println(randomService.nextDouble()); + + Faker faker = new Faker(new Random(randomService.nextLong())); + + System.out.println(faker.address() + .city()); + + } + + @Test + public void testFakeValuesService() throws Exception { + + FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService()); + + String email = fakeValuesService.bothify("????##@gmail.com"); + Matcher emailMatcher = Pattern.compile("\\w{4}\\d{2}@gmail.com") + .matcher(email); + assertTrue(emailMatcher.find()); + + String alphaNumericString = fakeValuesService.regexify("[a-z1-9]{10}"); + Matcher alphaNumericMatcher = Pattern.compile("[a-z1-9]{10}") + .matcher(alphaNumericString); + assertTrue(alphaNumericMatcher.find()); + + } + + @Test(expected = LocaleDoesNotExistException.class) + public void givenWrongLocale_whenFakerIsInitialised_testLocaleDoesNotExistExceptionIsThrown() throws Exception { + + Faker wrongLocaleFaker = new Faker(new Locale("en-seaWorld")); + + } +} \ No newline at end of file diff --git a/testing-modules/testng/pom.xml b/testing-modules/testng/pom.xml index 028db38727..a9f680aafb 100644 --- a/testing-modules/testng/pom.xml +++ b/testing-modules/testng/pom.xml @@ -38,24 +38,6 @@ true - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - - diff --git a/twilio/pom.xml b/twilio/pom.xml index 8683192b5c..610cc04b60 100644 --- a/twilio/pom.xml +++ b/twilio/pom.xml @@ -2,11 +2,15 @@ 4.0.0 - - com.baeldung twilio 1.0-SNAPSHOT + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + com.twilio.sdk @@ -15,9 +19,4 @@ - - 1.8 - 1.8 - - diff --git a/vaadin/README.md b/vaadin/README.md index 0dfeea8996..43d2cc8961 100644 --- a/vaadin/README.md +++ b/vaadin/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Introduction to Vaadin](http://www.baeldung.com/vaadin) +- [Sample Application with Spring Boot and Vaadin](https://www.baeldung.com/spring-boot-vaadin) diff --git a/vaadin/pom.xml b/vaadin/pom.xml index 07f0ccbd1c..c34ffa3636 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -4,25 +4,34 @@ 4.0.0 org.test - vaadin-app + vaadin war 1.0-SNAPSHOT - vaadin-app - - 3 - - + Vaadin + + parent-boot-2 com.baeldung - parent-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + com.vaadin + vaadin-bom + ${vaadin.version} + pom + import + + + + javax.servlet javax.servlet-api - ${servlet.version} provided @@ -41,6 +50,25 @@ com.vaadin vaadin-themes + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.vaadin + vaadin-spring-boot-starter + ${vaadin-spring-boot-starter.version} + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + @@ -97,21 +125,13 @@ 2 + + org.springframework.boot + spring-boot-maven-plugin + - - - - com.vaadin - vaadin-bom - ${vaadin.version} - pom - import - - - - vaadin-addons @@ -166,6 +186,7 @@ 3.0.1 7.7.10 8.0.6 + 10.0.1 9.3.9.v20160517 UTF-8 1.8 diff --git a/vaadin-spring/src/main/java/com/baeldung/Application.java b/vaadin/src/main/java/com/baeldung/Application.java similarity index 100% rename from vaadin-spring/src/main/java/com/baeldung/Application.java rename to vaadin/src/main/java/com/baeldung/Application.java diff --git a/vaadin-spring/src/main/java/com/baeldung/Employee.java b/vaadin/src/main/java/com/baeldung/Employee.java similarity index 100% rename from vaadin-spring/src/main/java/com/baeldung/Employee.java rename to vaadin/src/main/java/com/baeldung/Employee.java diff --git a/vaadin-spring/src/main/java/com/baeldung/EmployeeEditor.java b/vaadin/src/main/java/com/baeldung/EmployeeEditor.java similarity index 100% rename from vaadin-spring/src/main/java/com/baeldung/EmployeeEditor.java rename to vaadin/src/main/java/com/baeldung/EmployeeEditor.java diff --git a/vaadin-spring/src/main/java/com/baeldung/EmployeeRepository.java b/vaadin/src/main/java/com/baeldung/EmployeeRepository.java similarity index 100% rename from vaadin-spring/src/main/java/com/baeldung/EmployeeRepository.java rename to vaadin/src/main/java/com/baeldung/EmployeeRepository.java diff --git a/vaadin-spring/src/main/java/com/baeldung/MainView.java b/vaadin/src/main/java/com/baeldung/MainView.java similarity index 100% rename from vaadin-spring/src/main/java/com/baeldung/MainView.java rename to vaadin/src/main/java/com/baeldung/MainView.java diff --git a/vertx-and-rxjava/src/test/resources/logback-test.xml b/vertx-and-rxjava/src/test/resources/logback-test.xml index 71e05a4e24..8b6abffc76 100644 --- a/vertx-and-rxjava/src/test/resources/logback-test.xml +++ b/vertx-and-rxjava/src/test/resources/logback-test.xml @@ -1,7 +1,7 @@ - [%thread{32}] %-5level %msg - %logger%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/vertx/src/main/resources/logback.xml b/vertx/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/vertx/src/main/resources/logback.xml +++ b/vertx/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/xml/pom.xml b/xml/pom.xml index dba0308337..5490f3a89f 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -1,8 +1,6 @@ 4.0.0 - - com.baeldung xml 0.1-SNAPSHOT xml @@ -168,23 +166,7 @@ template-binding.xml - true - - - - process-classes - - bind - - - - - - org.jibx - maven-jibx-plugin - 1.3.1 - - src/main/resources + src/main/resources *-binding.xml @@ -192,6 +174,14 @@ + process-classes + process-classes + + bind + + + + process-test-classes process-test-classes test-bind diff --git a/xml/src/main/java/com/baeldung/xml/XMLDocumentWriter.java b/xml/src/main/java/com/baeldung/xml/XMLDocumentWriter.java new file mode 100644 index 0000000000..e33fc5fe1d --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/XMLDocumentWriter.java @@ -0,0 +1,41 @@ +package com.baeldung.xml; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; + +public class XMLDocumentWriter { + + public void write(Document document, String fileName, boolean excludeDeclaration, boolean prettyPrint) { + try(FileWriter writer = new FileWriter(new File(fileName))) { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + if(excludeDeclaration) { + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + } + if(prettyPrint) { + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + } + DOMSource source = new DOMSource(document); + StreamResult result = new StreamResult(writer); + transformer.transform(source, result); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } catch (TransformerConfigurationException e) { + throw new IllegalStateException(e); + } catch (TransformerException e) { + throw new IllegalArgumentException(e); + } + } +} diff --git a/xml/src/test/java/com/baeldung/xml/XMLDocumentWriterUnitTest.java b/xml/src/test/java/com/baeldung/xml/XMLDocumentWriterUnitTest.java new file mode 100644 index 0000000000..68f787a054 --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/XMLDocumentWriterUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.xml; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import java.io.File; + +public class XMLDocumentWriterUnitTest { + + @Test + public void givenXMLDocumentWhenWriteIsCalledThenXMLIsWrittenToFile() throws Exception { + Document document = createSampleDocument(); + new XMLDocumentWriter().write(document, "company_simple.xml", false, false); + } + + @Test + public void givenXMLDocumentWhenWriteIsCalledWithPrettyPrintThenFormattedXMLIsWrittenToFile() throws Exception { + Document document = createSampleDocument(); + new XMLDocumentWriter().write(document, "company_prettyprinted.xml", false, true); + } + + private Document createSampleDocument() throws ParserConfigurationException { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); + Element companyElement = document.createElement("Company"); + document.appendChild(companyElement); + Element departmentElement = document.createElement("Department"); + departmentElement.setAttribute("name", "Sales"); + companyElement.appendChild(departmentElement); + Element employee1 = document.createElement("Employee"); + employee1.setAttribute("name", "John Smith"); + departmentElement.appendChild(employee1); + Element employee2 = document.createElement("Employee"); + employee2.setAttribute("name", "Tim Dellor"); + departmentElement.appendChild(employee2); + return document; + } + + @After + public void cleanUp() throws Exception { + FileUtils.deleteQuietly(new File("company_simple.xml")); + FileUtils.deleteQuietly(new File("company_prettyprinted.xml")); + } +} diff --git a/xstream/src/main/resources/logback.xml b/xstream/src/main/resources/logback.xml index ec0dc2469a..56af2d397e 100644 --- a/xstream/src/main/resources/logback.xml +++ b/xstream/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - web - %date [%thread] %-5level %logger{36} - %message%n + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n