diff --git a/.gitignore b/.gitignore index 50cb889e5b..2edea19340 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ */bin/* +bin/ *.class @@ -21,6 +22,9 @@ *.iws out/ +# VSCode +.vscode/ + # Mac .DS_Store @@ -77,4 +81,5 @@ apache-avro/src/main/java/com/baeldung/avro/model/ jta/transaction-logs/ software-security/sql-injection-samples/derby.log spring-soap/src/main/java/com/baeldung/springsoap/gen/ -/report-*.json \ No newline at end of file +/report-*.json +transaction.log \ No newline at end of file diff --git a/README.md b/README.md index 1030cbb09c..7f78cf1515 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Running a Spring Boot module ==================== To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory -#Running Tests +###Running Tests The command `mvn clean install` will run the unit tests in a module. To run the integration tests, use the command `mvn clean install -Pintegration-lite-first` diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml index 30130208f8..affa66f147 100644 --- a/algorithms-miscellaneous-1/pom.xml +++ b/algorithms-miscellaneous-1/pom.xml @@ -42,7 +42,7 @@ com.github.dpaukov combinatoricslib3 - 3.3.0 + ${combinatoricslib3.version} @@ -83,6 +83,7 @@ 3.9.0 1.11 27.0.1-jre + 3.3.0 \ No newline at end of file diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index 4dd4b66ff2..cd3711d573 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -4,3 +4,6 @@ - [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine) - [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic) - [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) +- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted) +- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) +- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique) diff --git a/algorithms-miscellaneous-3/pom.xml b/algorithms-miscellaneous-3/pom.xml index c4017144c8..3cebdd09ac 100644 --- a/algorithms-miscellaneous-3/pom.xml +++ b/algorithms-miscellaneous-3/pom.xml @@ -18,6 +18,18 @@ ${org.assertj.core.version} test + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + + com.google.guava + guava + ${guava.version} + @@ -34,6 +46,7 @@ 3.9.0 + 4.3 + 28.0-jre - \ No newline at end of file diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/Employee.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/Employee.java new file mode 100644 index 0000000000..796932728b --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/Employee.java @@ -0,0 +1,34 @@ +package com.baeldung.algorithms.checksortedlist; + +public class Employee { + + long id; + + String name; + + public Employee() { + } + + public Employee(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; + } + +} diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/SortedListChecker.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/SortedListChecker.java new file mode 100644 index 0000000000..ab6eb6bc14 --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/SortedListChecker.java @@ -0,0 +1,87 @@ +package com.baeldung.algorithms.checksortedlist; + +import static org.apache.commons.collections4.CollectionUtils.isEmpty; + +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +import com.google.common.collect.Comparators; +import com.google.common.collect.Ordering;; + +public class SortedListChecker { + + private SortedListChecker() { + throw new AssertionError(); + } + + public static boolean checkIfSortedUsingIterativeApproach(List listOfStrings) { + if (isEmpty(listOfStrings) || listOfStrings.size() == 1) { + return true; + } + + Iterator iter = listOfStrings.iterator(); + String current, previous = iter.next(); + while (iter.hasNext()) { + current = iter.next(); + if (previous.compareTo(current) > 0) { + return false; + } + previous = current; + } + return true; + } + + public static boolean checkIfSortedUsingIterativeApproach(List employees, Comparator employeeComparator) { + if (isEmpty(employees) || employees.size() == 1) { + return true; + } + + Iterator iter = employees.iterator(); + Employee current, previous = iter.next(); + while (iter.hasNext()) { + current = iter.next(); + if (employeeComparator.compare(previous, current) > 0) { + return false; + } + previous = current; + } + return true; + } + + public static boolean checkIfSortedUsingRecursion(List listOfStrings) { + return isSortedRecursive(listOfStrings, listOfStrings.size()); + } + + public static boolean isSortedRecursive(List listOfStrings, int index) { + if (index < 2) { + return true; + } else if (listOfStrings.get(index - 2) + .compareTo(listOfStrings.get(index - 1)) > 0) { + return false; + } else { + return isSortedRecursive(listOfStrings, index - 1); + } + } + + public static boolean checkIfSortedUsingOrderingClass(List listOfStrings) { + return Ordering. natural() + .isOrdered(listOfStrings); + } + + public static boolean checkIfSortedUsingOrderingClass(List employees, Comparator employeeComparator) { + return Ordering.from(employeeComparator) + .isOrdered(employees); + } + + public static boolean checkIfSortedUsingOrderingClassHandlingNull(List listOfStrings) { + return Ordering. natural() + .nullsLast() + .isOrdered(listOfStrings); + } + + public static boolean checkIfSortedUsingComparators(List listOfStrings) { + return Comparators.isInOrder(listOfStrings, Comparator. naturalOrder()); + } + +} diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java new file mode 100644 index 0000000000..c77173b288 --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java @@ -0,0 +1,51 @@ +package com.baeldung.algorithms.graphcycledetection.domain; + +import java.util.ArrayList; +import java.util.List; + +public class Graph { + + private List vertices; + + public Graph() { + this.vertices = new ArrayList<>(); + } + + public Graph(List vertices) { + this.vertices = vertices; + } + + public void addVertex(Vertex vertex) { + this.vertices.add(vertex); + } + + public void addEdge(Vertex from, Vertex to) { + from.addNeighbour(to); + } + + public boolean hasCycle() { + for (Vertex vertex : vertices) { + if (!vertex.isVisited() && hasCycle(vertex)) { + return true; + } + } + return false; + } + + public boolean hasCycle(Vertex sourceVertex) { + sourceVertex.setBeingVisited(true); + + for (Vertex neighbour : sourceVertex.getAdjacencyList()) { + if (neighbour.isBeingVisited()) { + // backward edge exists + return true; + } else if (!neighbour.isVisited() && hasCycle(neighbour)) { + return true; + } + } + + sourceVertex.setBeingVisited(false); + sourceVertex.setVisited(true); + return false; + } +} diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java new file mode 100644 index 0000000000..398cdf0d9c --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java @@ -0,0 +1,56 @@ +package com.baeldung.algorithms.graphcycledetection.domain; + +import java.util.ArrayList; +import java.util.List; + +public class Vertex { + + private String label; + + private boolean visited; + + private boolean beingVisited; + + private List adjacencyList; + + public Vertex(String label) { + this.label = label; + this.adjacencyList = new ArrayList<>(); + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public boolean isVisited() { + return visited; + } + + public void setVisited(boolean visited) { + this.visited = visited; + } + + public boolean isBeingVisited() { + return beingVisited; + } + + public void setBeingVisited(boolean beingVisited) { + this.beingVisited = beingVisited; + } + + public List getAdjacencyList() { + return adjacencyList; + } + + public void setAdjacencyList(List adjacencyList) { + this.adjacencyList = adjacencyList; + } + + public void addNeighbour(Vertex adjacent) { + this.adjacencyList.add(adjacent); + } +} diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/FoldingHash.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/FoldingHash.java new file mode 100644 index 0000000000..0ea128c1d9 --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/FoldingHash.java @@ -0,0 +1,78 @@ +package com.baeldung.folding; + +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * Calculate a hash value for the strings using the folding technique. + * + * The implementation serves only to the illustration purposes and is far + * from being the most efficient. + * + * @author A.Shcherbakov + * + */ +public class FoldingHash { + + /** + * Calculate the hash value of a given string. + * + * @param str Assume it is not null + * @param groupSize the group size in the folding technique + * @param maxValue defines a max value that the hash may acquire (exclusive) + * @return integer value from 0 (inclusive) to maxValue (exclusive) + */ + public int hash(String str, int groupSize, int maxValue) { + final int[] codes = this.toAsciiCodes(str); + return IntStream.range(0, str.length()) + .filter(i -> i % groupSize == 0) + .mapToObj(i -> extract(codes, i, groupSize)) + .map(block -> concatenate(block)) + .reduce(0, (a, b) -> (a + b) % maxValue); + } + + /** + * Returns a new array of given length whose elements are take from + * the original one starting from the offset. + * + * If the original array has not enough elements, the returning array will contain + * element from the offset till the end of the original array. + * + * @param numbers original array. Assume it is not null. + * @param offset index of the element to start from. Assume it is less than the size of the array + * @param length max size of the resulting array + * @return + */ + public int[] extract(int[] numbers, int offset, int length) { + final int defect = numbers.length - (offset + length); + final int s = defect < 0 ? length + defect : length; + int[] result = new int[s]; + for (int index = 0; index < s; index++) { + result[index] = numbers[index + offset]; + } + return result; + } + + /** + * Concatenate the numbers into a single number as if they were strings. + * Assume that the procedure does not suffer from the overflow. + * @param numbers integers to concatenate + * @return + */ + public int concatenate(int[] numbers) { + final String merged = IntStream.of(numbers) + .mapToObj(number -> "" + number) + .collect(Collectors.joining()); + return Integer.parseInt(merged, 10); + } + + /** + * Convert the string into its characters' ASCII codes. + * @param str input string + * @return + */ + private int[] toAsciiCodes(String str) { + return str.chars() + .toArray(); + } +} diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/Main.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/Main.java new file mode 100644 index 0000000000..3b055a0dbe --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/Main.java @@ -0,0 +1,17 @@ +package com.baeldung.folding; + +/** + * Code snippet for article "A Guide to the Folding Technique". + * + * @author A.Shcherbakov + * + */ +public class Main { + + public static void main(String... arg) { + FoldingHash hasher = new FoldingHash(); + final String str = "Java language"; + System.out.println(hasher.hash(str, 2, 100_000)); + System.out.println(hasher.hash(str, 3, 1_000)); + } +} diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checksortedlist/SortedListCheckerUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checksortedlist/SortedListCheckerUnitTest.java new file mode 100644 index 0000000000..44c4388e6c --- /dev/null +++ b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checksortedlist/SortedListCheckerUnitTest.java @@ -0,0 +1,106 @@ +package com.baeldung.algorithms.checksortedlist; + +import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingComparators; +import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingIterativeApproach; +import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingOrderingClass; +import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingRecursion; +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class SortedListCheckerUnitTest { + + private List sortedListOfString; + private List unsortedListOfString; + private List singletonList; + + private List employeesSortedByName; + private List employeesNotSortedByName; + + @Before + public void setUp() { + sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY"); + unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada"); + singletonList = Collections.singletonList("NY"); + + employeesSortedByName = asList(new Employee(1L, "John"), new Employee(2L, "Kevin"), new Employee(3L, "Mike")); + employeesNotSortedByName = asList(new Employee(1L, "Kevin"), new Employee(2L, "John"), new Employee(3L, "Mike")); + } + + @Test + public void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() { + assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue(); + } + + @Test + public void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() { + assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue(); + } + + @Test + public void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() { + assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse(); + } + + @Test + public void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() { + assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue(); + } + + @Test + public void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() { + assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse(); + } + + @Test + public void givenSortedList_whenUsingRecursion_thenReturnTrue() { + assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue(); + } + + @Test + public void givenSingleElementList_whenUsingRecursion_thenReturnTrue() { + assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue(); + } + + @Test + public void givenUnsortedList_whenUsingRecursion_thenReturnFalse() { + assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse(); + } + + @Test + public void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() { + assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue(); + } + + @Test + public void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() { + assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse(); + } + + @Test + public void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() { + assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue(); + } + + @Test + public void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() { + assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse(); + } + + @Test + public void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() { + assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue(); + } + + @Test + public void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() { + assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse(); + } + +} diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java new file mode 100644 index 0000000000..8d464d7b97 --- /dev/null +++ b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.algorithms.graphcycledetection; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.baeldung.algorithms.graphcycledetection.domain.Graph; +import com.baeldung.algorithms.graphcycledetection.domain.Vertex; + +public class GraphCycleDetectionUnitTest { + + @Test + public void givenGraph_whenCycleExists_thenReturnTrue() { + + Vertex vertexA = new Vertex("A"); + Vertex vertexB = new Vertex("B"); + Vertex vertexC = new Vertex("C"); + Vertex vertexD = new Vertex("D"); + + Graph graph = new Graph(); + graph.addVertex(vertexA); + graph.addVertex(vertexB); + graph.addVertex(vertexC); + graph.addVertex(vertexD); + + graph.addEdge(vertexA, vertexB); + graph.addEdge(vertexB, vertexC); + graph.addEdge(vertexC, vertexA); + graph.addEdge(vertexD, vertexC); + + assertTrue(graph.hasCycle()); + } + + @Test + public void givenGraph_whenNoCycleExists_thenReturnFalse() { + + Vertex vertexA = new Vertex("A"); + Vertex vertexB = new Vertex("B"); + Vertex vertexC = new Vertex("C"); + Vertex vertexD = new Vertex("D"); + + Graph graph = new Graph(); + graph.addVertex(vertexA); + graph.addVertex(vertexB); + graph.addVertex(vertexC); + graph.addVertex(vertexD); + + graph.addEdge(vertexA, vertexB); + graph.addEdge(vertexB, vertexC); + graph.addEdge(vertexA, vertexC); + graph.addEdge(vertexD, vertexC); + + assertFalse(graph.hasCycle()); + } +} diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java new file mode 100644 index 0000000000..43e33d8378 --- /dev/null +++ b/algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.folding; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class FoldingHashUnitTest { + + @Test + public void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int value = hasher.hash("Java language", 2, 100_000); + assertEquals(value, 48933); + } + + @Test + public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int java = hasher.hash("Java language", 2, 100_000); + final int vaja = hasher.hash("vaJa language", 2, 100_000); + assertTrue(java == vaja); + } + + @Test + public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int[] value = hasher.extract(new int[] { 5 }, 0, 2); + assertArrayEquals(new int[] { 5 }, value); + } + + @Test + public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3); + assertArrayEquals(new int[] { 1, 2, 3 }, value); + } + + @Test + public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2); + assertArrayEquals(new int[] { 2, 3 }, value); + } + + @Test + public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000); + assertArrayEquals(new int[] { 3, 4, 5 }, value); + } + +} diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml index 5d170f0a81..e6fb4d24ff 100644 --- a/apache-avro/pom.xml +++ b/apache-avro/pom.xml @@ -17,7 +17,7 @@ junit junit - 4.10 + ${junit.version} test diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index 1efd4ea602..24e7b4e0b2 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -3,37 +3,28 @@ 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 - - org.springframework.boot - spring-boot-starter-parent - 2.1.3.RELEASE - - org.baeldung.examples.olingo2 olingo2-sample 0.0.1-SNAPSHOT olingo2-sample Sample Olingo 2 Project - - 1.8 - 2.0.11 - + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + - org.springframework.boot spring-boot-starter-jersey - - org.springframework.boot spring-boot-starter-data-jpa - - com.h2database h2 @@ -90,4 +81,8 @@ + + 2.0.11 + + diff --git a/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java b/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java similarity index 86% rename from apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java rename to apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java index 687f6ab1ff..7cb685e3e9 100644 --- a/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java +++ b/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class Olingo2SampleApplicationTests { +public class Olingo2SampleApplicationUnitTest { @Test public void contextLoads() { diff --git a/apache-pulsar/pom.xml b/apache-pulsar/pom.xml index 11df6d0b87..8a0882dae1 100644 --- a/apache-pulsar/pom.xml +++ b/apache-pulsar/pom.xml @@ -7,6 +7,13 @@ 0.0.1 apache-pulsar + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + org.apache.pulsar diff --git a/apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java b/apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java old mode 100755 new mode 100644 similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java rename to apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java index 72dc10b542..82a0028837 --- a/apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java @@ -7,7 +7,7 @@ import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.client.api.SubscriptionType; -public class ConsumerTest { +public class ConsumerUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "test-topic"; diff --git a/apache-pulsar/src/main/java/com/baeldung/ProducerTest.java b/apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java old mode 100755 new mode 100644 similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/ProducerTest.java rename to apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java index 08ee0e89b9..10a4b46c4d --- a/apache-pulsar/src/main/java/com/baeldung/ProducerTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java @@ -11,7 +11,7 @@ import org.apache.pulsar.client.api.PulsarClientException; import java.io.IOException; import java.util.stream.IntStream; -public class ProducerTest { +public class ProducerUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "test-topic"; diff --git a/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionTest.java b/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionUnitTest.java similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionTest.java rename to apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionUnitTest.java index efb898eaf4..79121347e7 100644 --- a/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionUnitTest.java @@ -10,7 +10,7 @@ import org.apache.pulsar.client.api.SubscriptionType; import java.util.stream.IntStream; -public class ExclusiveSubscriptionTest { +public class ExclusiveSubscriptionUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "test-topic"; private static final String SUBSCRIPTION_NAME = "test-subscription"; diff --git a/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionTest.java b/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionUnitTest.java similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionTest.java rename to apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionUnitTest.java index 545661e0c3..1d13b4b83a 100644 --- a/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionUnitTest.java @@ -11,7 +11,7 @@ import org.apache.pulsar.client.api.SubscriptionType; import java.util.stream.IntStream; -public class FailoverSubscriptionTest { +public class FailoverSubscriptionUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "failover-subscription-test-topic"; private static final String SUBSCRIPTION_NAME = "test-subscription"; diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index f0f002a7e9..b8c1962dd4 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -49,6 +49,7 @@ ${com.datastax.spark.spark-cassandra-connector-java.version} + @@ -78,6 +79,7 @@ + 2.3.0 2.3.0 diff --git a/autovalue/README.md b/autovalue/README.md index c6a08359ef..f33ff6899f 100644 --- a/autovalue/README.md +++ b/autovalue/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue) - [Introduction to AutoFactory](http://www.baeldung.com/autofactory) +- [Google AutoService](https://www.baeldung.com/google-autoservice) diff --git a/autovalue/pom.xml b/autovalue/pom.xml index 3ec2d26b35..a10e8ef055 100644 --- a/autovalue/pom.xml +++ b/autovalue/pom.xml @@ -29,6 +29,12 @@ + + com.google.auto.service + auto-service + ${auto-service.version} + true + com.google.inject @@ -40,6 +46,7 @@ 1.3 1.0-beta5 + 1.0-rc5 4.2.0 diff --git a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java new file mode 100644 index 0000000000..86d42e80fa --- /dev/null +++ b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java @@ -0,0 +1,14 @@ +package com.baeldung.autoservice; + +import com.google.auto.service.AutoService; + +import java.util.Locale; + +@AutoService(TranslationService.class) +public class BingTranslationServiceProvider implements TranslationService { + @Override + public String translate(String message, Locale from, Locale to) { + // implementation details + return message + " (translated by Bing)"; + } +} diff --git a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java new file mode 100644 index 0000000000..0bf91ee5ec --- /dev/null +++ b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java @@ -0,0 +1,14 @@ +package com.baeldung.autoservice; + +import com.google.auto.service.AutoService; + +import java.util.Locale; + +@AutoService(TranslationService.class) +public class GoogleTranslationServiceProvider implements TranslationService { + @Override + public String translate(String message, Locale from, Locale to) { + // implementation details + return message + " (translated by Google)"; + } +} diff --git a/autovalue/src/main/java/com/baeldung/autoservice/TranslationService.java b/autovalue/src/main/java/com/baeldung/autoservice/TranslationService.java new file mode 100644 index 0000000000..580db46cd1 --- /dev/null +++ b/autovalue/src/main/java/com/baeldung/autoservice/TranslationService.java @@ -0,0 +1,7 @@ +package com.baeldung.autoservice; + +import java.util.Locale; + +public interface TranslationService { + String translate(String message, Locale from, Locale to); +} \ No newline at end of file diff --git a/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java b/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java new file mode 100644 index 0000000000..9e1bd6d291 --- /dev/null +++ b/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.autoservice; + +import com.baeldung.autoservice.TranslationService; +import org.junit.Before; +import org.junit.Test; + +import java.util.ServiceLoader; +import java.util.stream.StreamSupport; + +import static org.junit.Assert.assertEquals; + +public class TranslationServiceUnitTest { + + private ServiceLoader loader; + + @Before + public void setUp() { + loader = ServiceLoader.load(TranslationService.class); + } + + @Test + public void whenServiceLoaderLoads_thenLoadsAllProviders() { + long count = StreamSupport.stream(loader.spliterator(), false).count(); + assertEquals(2, count); + } + + @Test + public void whenServiceLoaderLoadsGoogleService_thenGoogleIsLoaded() { + TranslationService googleService = StreamSupport.stream(loader.spliterator(), false) + .filter(p -> p.getClass().getSimpleName().equals("GoogleTranslationServiceProvider")) + .findFirst() + .get(); + + String message = "message"; + assertEquals(message + " (translated by Google)", googleService.translate(message, null, null)); + } +} \ No newline at end of file diff --git a/aws/pom.xml b/aws/pom.xml index 560f9145f9..75d5aac1eb 100644 --- a/aws/pom.xml +++ b/aws/pom.xml @@ -112,7 +112,6 @@ - 2.5 1.3.0 1.1.0 2.8.0 diff --git a/bootique/pom.xml b/bootique/pom.xml index 4ae8703074..4dd9ba4833 100644 --- a/bootique/pom.xml +++ b/bootique/pom.xml @@ -65,7 +65,6 @@ com.baeldung.bootique.App 0.23 - 2.4.3 diff --git a/core-groovy-2/README.md b/core-groovy-2/README.md index c8df242e1a..33df8b107b 100644 --- a/core-groovy-2/README.md +++ b/core-groovy-2/README.md @@ -3,5 +3,8 @@ ## Relevant articles: - [String Matching in Groovy](http://www.baeldung.com/) +- [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines) - [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword) - [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching) +- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml) +- [Integrating Groovy into Java Applications](https://www.baeldung.com/groovy-java-applications) diff --git a/core-groovy-2/gmavenplus-pom.xml b/core-groovy-2/gmavenplus-pom.xml new file mode 100644 index 0000000000..54c89b9834 --- /dev/null +++ b/core-groovy-2/gmavenplus-pom.xml @@ -0,0 +1,178 @@ + + + 4.0.0 + core-groovy-2 + 1.0-SNAPSHOT + core-groovy-2 + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.codehaus.groovy + groovy-all + ${groovy.version} + pom + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.hsqldb + hsqldb + ${hsqldb.version} + test + + + org.spockframework + spock-core + ${spock-core.version} + test + + + + + src/main/groovy + src/main/java + + + org.codehaus.gmavenplus + gmavenplus-plugin + 1.7.0 + + + + execute + addSources + addTestSources + generateStubs + compile + generateTestStubs + compileTests + removeStubs + removeTestStubs + + + + + + org.codehaus.groovy + groovy-all + + ${groovy.version} + runtime + pom + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + junit5 + + integration-test + verify + + + + **/*Test5.java + + + + + + + maven-surefire-plugin + 2.20.1 + + false + + **/*Test.java + **/*Spec.java + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.1.0 + + + + jar-with-dependencies + + + + + com.baeldung.MyJointCompilationApp + + + + + + + make-assembly + + package + + single + + + + + + + + + + central + http://jcenter.bintray.com + + + + + UTF-8 + 1.0.0 + 2.4.0 + 1.1-groovy-2.4 + 3.9 + 1.8 + 1.2.3 + 2.5.7 + 1.6 + + + diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index 77de9c8fc8..ba3fd0802b 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/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 core-groovy-2 1.0-SNAPSHOT @@ -15,25 +15,20 @@ - org.codehaus.groovy - groovy - ${groovy.version} + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + ch.qos.logback + logback-classic + ${logback.version} org.codehaus.groovy groovy-all - ${groovy-all.version} - pom - - - org.codehaus.groovy - groovy-dateutil ${groovy.version} - - - org.codehaus.groovy - groovy-sql - ${groovy-sql.version} + pom org.junit.platform @@ -56,21 +51,35 @@ + src/main/groovy + src/main/java - org.codehaus.gmavenplus - gmavenplus-plugin - ${gmavenplus-plugin.version} - - - - addSources - addTestSources - compile - compileTests - - - + org.codehaus.groovy + groovy-eclipse-compiler + 3.3.0-01 + true + + + maven-compiler-plugin + 3.8.0 + + groovy-eclipse-compiler + ${java.version} + ${java.version} + + + + org.codehaus.groovy + groovy-eclipse-compiler + 3.3.0-01 + + + org.codehaus.groovy + groovy-eclipse-batch + ${groovy.version}-01 + + maven-failsafe-plugin @@ -101,13 +110,42 @@ maven-surefire-plugin 2.20.1 - false - - **/*Test.java - **/*Spec.java - + false + + **/*Test.java + **/*Spec.java + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.1.0 + + + + jar-with-dependencies + + + + + com.baeldung.MyJointCompilationApp + + + + + + + make-assembly + + package + + single + + + + @@ -118,14 +156,29 @@ + + + bintray + Groovy Bintray + https://dl.bintray.com/groovy/maven + + + never + + + false + + + + 1.0.0 - 2.5.6 - 2.5.6 - 2.5.6 2.4.0 1.1-groovy-2.4 - 1.6 + 3.8.1 + 1.2.3 + 2.5.7 + UTF-8 diff --git a/core-groovy-2/src/main/groovy/com/baeldung/CalcMath.groovy b/core-groovy-2/src/main/groovy/com/baeldung/CalcMath.groovy new file mode 100644 index 0000000000..0e233793b2 --- /dev/null +++ b/core-groovy-2/src/main/groovy/com/baeldung/CalcMath.groovy @@ -0,0 +1,25 @@ +package com.baeldung + +import org.slf4j.LoggerFactory + +class CalcMath { + def log = LoggerFactory.getLogger(this.getClass()) + + def calcSum(x, y) { + log.info "Executing $x + $y" + x + y + } + + /** + * example of method that in java would throw error at compile time + * @param x + * @param y + * @return + */ + def calcSum2(x, y) { + log.info "Executing $x + $y" + // DANGER! This won't throw a compilation issue and fail only at runtime!!! + calcSum3() + log.info("Logging an undefined variable: $z") + } +} \ No newline at end of file diff --git a/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy b/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy new file mode 100644 index 0000000000..84615b2217 --- /dev/null +++ b/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy @@ -0,0 +1,16 @@ +package com.baeldung + +def calcSum(x, y) { + x + y +} + +def calcSum2(x, y) { + // DANGER! The variable "log" may be undefined + log.info "Executing $x + $y" + // DANGER! This method doesn't exist! + calcSum3() + // DANGER! The logged variable "z" is undefined! + log.info("Logging an undefined variable: $z") +} + +calcSum(1,5) diff --git a/core-groovy-2/src/main/groovy/com/baeldung/concatenate/Wonder.groovy b/core-groovy-2/src/main/groovy/com/baeldung/concatenate/Wonder.groovy new file mode 100644 index 0000000000..1d7527726e --- /dev/null +++ b/core-groovy-2/src/main/groovy/com/baeldung/concatenate/Wonder.groovy @@ -0,0 +1,52 @@ +package com.baeldung.concatenate + +class Wonder { + + String numOfWonder = 'seven' + + String operator_plus() { + return 'The ' + numOfWonder + ' wonders of the world' + } + + String operator_left() { + return 'The ' << numOfWonder << ' wonders of ' << 'the world' + } + + String interpolation_one() { + return "The $numOfWonder wonders of the world" + + } + + String interpolation_two() { + return "The ${numOfWonder} wonders of the world" + } + + String multilineString() { + return """ + There are $numOfWonder wonders of the world. + Can you name them all? + 1. The Great Pyramid of Giza + 2. Hanging Gardens of Babylon + 3. Colossus of Rhode + 4. Lighthouse of Alexendra + 5. Temple of Artemis + 6. Status of Zeus at Olympia + 7. Mausoleum at Halicarnassus + """ + } + + String method_concat() { + return 'The '.concat(numOfWonder).concat(' wonders of the world') + + } + + String method_builder() { + return new StringBuilder() + .append('The ').append(numOfWonder).append(' wonders of the world') + } + + String method_buffer() { + return new StringBuffer() + .append('The ').append(numOfWonder).append(' wonders of the world') + } +} \ No newline at end of file diff --git a/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java b/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java new file mode 100644 index 0000000000..c49f6edc30 --- /dev/null +++ b/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java @@ -0,0 +1,120 @@ +package com.baeldung; + +import groovy.lang.*; +import groovy.util.GroovyScriptEngine; +import groovy.util.ResourceException; +import groovy.util.ScriptException; +import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.script.ScriptEngine; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; + +/** + * Hello world! + * + */ +public class MyJointCompilationApp { + private final static Logger LOG = LoggerFactory.getLogger(MyJointCompilationApp.class); + private final GroovyClassLoader loader; + private final GroovyShell shell; + private final GroovyScriptEngine engine; + private final ScriptEngine engineFromFactory; + + public MyJointCompilationApp() { + loader = new GroovyClassLoader(this.getClass().getClassLoader()); + shell = new GroovyShell(loader, new Binding()); + + URL url = null; + try { + url = new File("src/main/groovy/com/baeldung/").toURI().toURL(); + } catch (MalformedURLException e) { + LOG.error("Exception while creating url", e); + } + engine = new GroovyScriptEngine(new URL[] {url}, this.getClass().getClassLoader()); + engineFromFactory = new GroovyScriptEngineFactory().getScriptEngine(); + } + + private void addWithCompiledClasses(int x, int y) { + LOG.info("Executing {} + {}", x, y); + Object result1 = new CalcScript().calcSum(x, y); + LOG.info("Result of CalcScript.calcSum() method is {}", result1); + + Object result2 = new CalcMath().calcSum(x, y); + LOG.info("Result of CalcMath.calcSum() method is {}", result2); + } + + private void addWithGroovyShell(int x, int y) throws IOException { + Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy")); + LOG.info("Executing {} + {}", x, y); + Object result = script.invokeMethod("calcSum", new Object[] { x, y }); + LOG.info("Result of CalcScript.calcSum() method is {}", result); + } + + private void addWithGroovyShellRun() throws IOException { + Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy")); + LOG.info("Executing script run method"); + Object result = script.run(); + LOG.info("Result of CalcScript.run() method is {}", result); + } + + private void addWithGroovyClassLoader(int x, int y) throws IllegalAccessException, InstantiationException, IOException { + Class calcClass = loader.parseClass( + new File("src/main/groovy/com/baeldung/", "CalcMath.groovy")); + GroovyObject calc = (GroovyObject) calcClass.newInstance(); + Object result = calc.invokeMethod("calcSum", new Object[] { x + 14, y + 14 }); + LOG.info("Result of CalcMath.calcSum() method is {}", result); + } + + private void addWithGroovyScriptEngine(int x, int y) throws IllegalAccessException, + InstantiationException, ResourceException, ScriptException { + Class calcClass = engine.loadScriptByName("CalcMath.groovy"); + GroovyObject calc = calcClass.newInstance(); + //WARNING the following will throw a ClassCastException + //((CalcMath)calc).calcSum(1,2); + Object result = calc.invokeMethod("calcSum", new Object[] { x, y }); + LOG.info("Result of CalcMath.calcSum() method is {}", result); + } + + private void addWithEngineFactory(int x, int y) throws IllegalAccessException, + InstantiationException, javax.script.ScriptException, FileNotFoundException { + Class calcClass = (Class) engineFromFactory.eval( + new FileReader(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy"))); + GroovyObject calc = (GroovyObject) calcClass.newInstance(); + Object result = calc.invokeMethod("calcSum", new Object[] { x, y }); + LOG.info("Result of CalcMath.calcSum() method is {}", result); + } + + private void addWithStaticCompiledClasses() { + LOG.info("Running the Groovy classes compiled statically..."); + addWithCompiledClasses(5, 10); + + } + + private void addWithDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException, + ResourceException, ScriptException, javax.script.ScriptException { + LOG.info("Invocation of a dynamic groovy script..."); + addWithGroovyShell(5, 10); + LOG.info("Invocation of the run method of a dynamic groovy script..."); + addWithGroovyShellRun(); + LOG.info("Invocation of a dynamic groovy class loaded with GroovyClassLoader..."); + addWithGroovyClassLoader(10, 30); + LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine..."); + addWithGroovyScriptEngine(15, 0); + LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine JSR223..."); + addWithEngineFactory(5, 6); + } + + public static void main(String[] args) throws InstantiationException, IllegalAccessException, + ResourceException, ScriptException, IOException, javax.script.ScriptException { + MyJointCompilationApp myJointCompilationApp = new MyJointCompilationApp(); + LOG.info("Example of addition operation via Groovy scripts integration with Java."); + myJointCompilationApp.addWithStaticCompiledClasses(); + myJointCompilationApp.addWithDynamicCompiledClasses(); + } +} diff --git a/core-groovy-2/src/test/groovy/com/baeldung/concatenate/WonderUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/concatenate/WonderUnitTest.groovy new file mode 100644 index 0000000000..5fc74abd69 --- /dev/null +++ b/core-groovy-2/src/test/groovy/com/baeldung/concatenate/WonderUnitTest.groovy @@ -0,0 +1,69 @@ +package com.baeldung.concatenate + +import org.junit.Before +import org.junit.Test + +import static org.junit.Assert.* + +class WonderUnitTest { + + static final String EXPECTED_SINGLE_LINE = "The seven wonders of the world" + + Wonder wonder + + @Before + void before() { + wonder = new Wonder() + } + + @Test + void whenUsingOperatorPlus_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_plus()) + } + + @Test + void whenUsingOperatorLeft_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_left()) + } + + @Test + void whenUsingInterpolationOne_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_one()) + } + + @Test + void whenUsingInterpolationTwo_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_two()) + } + + @Test + void whenUsingMultiline_thenConcatCorrectly() { + def expectedMultiline = """ + There are seven wonders of the world. + Can you name them all? + 1. The Great Pyramid of Giza + 2. Hanging Gardens of Babylon + 3. Colossus of Rhode + 4. Lighthouse of Alexendra + 5. Temple of Artemis + 6. Status of Zeus at Olympia + 7. Mausoleum at Halicarnassus + """ + assertEquals(expectedMultiline, wonder.multilineString()) + } + + @Test + void whenUsingMethodConcat_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.method_concat()) + } + + @Test + void whenUsingMethodBuilder_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.method_builder()) + } + + @Test + void whenUsingMethodBuffer_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.method_buffer()) + } +} diff --git a/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java b/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java new file mode 100644 index 0000000000..71e2840f45 --- /dev/null +++ b/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java @@ -0,0 +1,45 @@ +package com.baeldung.array.looping; + +public class LoopDiagonally { + + + public String loopDiagonally(String[][] twoDArray) { + + int length = twoDArray.length; + int diagonalLines = (length + length) - 1; + int itemsInDiagonal = 0; + int midPoint = (diagonalLines / 2) + 1; + StringBuilder output = new StringBuilder(); + + for (int i = 1; i <= diagonalLines; i++) { + + StringBuilder items = new StringBuilder(); + int rowIndex; + int columnIndex; + + if (i <= midPoint) { + itemsInDiagonal++; + for (int j = 0; j < itemsInDiagonal; j++) { + rowIndex = (i - j) - 1; + columnIndex = j; + items.append(twoDArray[rowIndex][columnIndex]); + } + } else { + itemsInDiagonal--; + for (int j = 0; j < itemsInDiagonal; j++) { + rowIndex = (length - 1) - j; + columnIndex = (i - length) + j; + items.append(twoDArray[rowIndex][columnIndex]); + } + } + + if (i != diagonalLines) { + output.append(items).append(" "); + } else { + output.append(items); + } + } + + return output.toString(); + } +} diff --git a/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java b/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java new file mode 100644 index 0000000000..df6079270b --- /dev/null +++ b/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java @@ -0,0 +1,20 @@ +package com.baeldung.array.looping; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class LoopDiagonallyTest { + + @Test + public void twoArrayIsLoopedDiagonallyAsExpected() { + + LoopDiagonally loopDiagonally = new LoopDiagonally(); + String[][] twoDArray = {{"a", "b", "c"}, + {"d", "e", "f"}, + {"g", "h", "i"}}; + + String output = loopDiagonally.loopDiagonally(twoDArray); + assertEquals("a db gec hf i", output); + } +} \ No newline at end of file diff --git a/core-java-modules/README.md b/core-java-modules/README.md index a90535a44f..9ce6057f32 100644 --- a/core-java-modules/README.md +++ b/core-java-modules/README.md @@ -1,3 +1,6 @@ ## Relevant articles: - [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) +- [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel) +- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception) +- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) diff --git a/core-java-modules/core-java-10/README.md b/core-java-modules/core-java-10/README.md index f0a25712a7..8fb4f8a7dd 100644 --- a/core-java-modules/core-java-10/README.md +++ b/core-java-modules/core-java-10/README.md @@ -5,3 +5,4 @@ - [Guide to Java 10](http://www.baeldung.com/java-10-overview) - [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) - [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler) +- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) diff --git a/core-java-modules/core-java-10/src/main/java/com/baeldung/set/CopySets.java b/core-java-modules/core-java-10/src/main/java/com/baeldung/set/CopySets.java new file mode 100644 index 0000000000..d49724f81d --- /dev/null +++ b/core-java-modules/core-java-10/src/main/java/com/baeldung/set/CopySets.java @@ -0,0 +1,13 @@ +package com.baeldung.set; + +import java.util.Set; + +public class CopySets { + + // Using Java 10 + public static Set copyBySetCopyOf(Set original) { + Set copy = Set.copyOf(original); + return copy; + } + +} diff --git a/core-java-modules/core-java-11/README.md b/core-java-modules/core-java-11/README.md index d68a1c87eb..11c7d9d388 100644 --- a/core-java-modules/core-java-11/README.md +++ b/core-java-modules/core-java-11/README.md @@ -7,4 +7,5 @@ - [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client) - [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector) - [Guide to jlink](https://www.baeldung.com/jlink) +- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference) - [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional) diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md new file mode 100644 index 0000000000..6f8f95970e --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference) diff --git a/core-java-modules/core-java-12/README.md b/core-java-modules/core-java-12/README.md new file mode 100644 index 0000000000..4514fd1a2b --- /dev/null +++ b/core-java-modules/core-java-12/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api) diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md index 383fe5da34..245fa93ba7 100644 --- a/core-java-modules/core-java-8-2/README.md +++ b/core-java-modules/core-java-8-2/README.md @@ -3,5 +3,7 @@ ## Core Java 8 Cookbooks and Examples (part 2) ### Relevant Articles: -- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes) +- [Anonymous Classes in Java](http://www.baeldung.com/) +- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) - [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments) +- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit) diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml index ff2e290086..07bb3b7543 100644 --- a/core-java-modules/core-java-8-2/pom.xml +++ b/core-java-modules/core-java-8-2/pom.xml @@ -9,7 +9,6 @@ core-java-8-2 jar - com.baeldung parent-java @@ -17,16 +16,6 @@ ../../parent-java - - UTF-8 - 1.8 - 1.8 - 64.2 - 5.4.0.Final - 1.4.197 - 2.9.8 - - com.ibm.icu @@ -34,19 +23,10 @@ ${icu.version} - org.hibernate - hibernate-core - ${hibernate.core.version} - - - com.h2database - h2 - ${h2database.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.databind.version} + org.assertj + assertj-core + ${assertj.version} + test @@ -62,6 +42,13 @@ - + + + UTF-8 + 1.8 + 1.8 + 64.2 + 3.12.2 + diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/forEach/ReverseList.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/forEach/ReverseList.java new file mode 100644 index 0000000000..b2ce77a9f6 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/forEach/ReverseList.java @@ -0,0 +1,84 @@ +package com.baeldung.forEach; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.function.Consumer; + +class ReverseList extends ArrayList { + + List list = Arrays.asList("A", "B", "C", "D"); + + Consumer removeElement = s -> { + System.out.println(s + " " + list.size()); + if (s != null && s.equals("A")) { + list.remove("D"); + } + }; + + @Override + public Iterator iterator() { + + final int startIndex = this.size() - 1; + final List list = this; + return new Iterator() { + + int currentIndex = startIndex; + + @Override + public boolean hasNext() { + return currentIndex >= 0; + } + + @Override + public String next() { + String next = list.get(currentIndex); + currentIndex--; + return next; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + + public void forEach(Consumer action) { + for (String s : this) { + action.accept(s); + } + } + + public void iterateParallel() { + list.forEach(System.out::print); + System.out.print(" "); + list.parallelStream().forEach(System.out::print); + } + + public void iterateReverse() { + List myList = new ReverseList(); + myList.addAll(list); + myList.forEach(System.out::print); + System.out.print(" "); + myList.stream().forEach(System.out::print); + } + + public void removeInCollectionForEach() { + list.forEach(removeElement); + } + + public void removeInStreamForEach() { + list.stream().forEach(removeElement); + } + + public static void main(String[] argv) { + + ReverseList collectionForEach = new ReverseList(); + collectionForEach.iterateParallel(); + collectionForEach.iterateReverse(); + collectionForEach.removeInCollectionForEach(); + collectionForEach.removeInStreamForEach(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/stream/SkipLimitComparison.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/stream/SkipLimitComparison.java new file mode 100644 index 0000000000..65f12ada45 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/stream/SkipLimitComparison.java @@ -0,0 +1,46 @@ +package com.baeldung.stream; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class SkipLimitComparison { + + public static void main(String[] args) { + skipExample(); + limitExample(); + limitInfiniteStreamExample(); + getEvenNumbers(10, 10).stream() + .forEach(System.out::println); + } + + public static void skipExample() { + Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + .filter(i -> i % 2 == 0) + .skip(2) + .forEach(i -> System.out.print(i + " ")); + } + + public static void limitExample() { + Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + .filter(i -> i % 2 == 0) + .limit(2) + .forEach(i -> System.out.print(i + " ")); + } + + public static void limitInfiniteStreamExample() { + Stream.iterate(0, i -> i + 1) + .filter(i -> i % 2 == 0) + .limit(10) + .forEach(System.out::println); + } + + private static List getEvenNumbers(int offset, int limit) { + return Stream.iterate(0, i -> i + 1) + .filter(i -> i % 2 == 0) + .skip(offset) + .limit(limit) + .collect(Collectors.toList()); + } + +} diff --git a/core-java-modules/core-java-8-2/src/test/java/com/baeldung/bifunction/BiFunctionalInterfacesUnitTest.java b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/bifunction/BiFunctionalInterfacesUnitTest.java new file mode 100644 index 0000000000..ea63409c88 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/bifunction/BiFunctionalInterfacesUnitTest.java @@ -0,0 +1,164 @@ +package com.baeldung.bifunction; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.function.BiFunction; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BiFunctionalInterfacesUnitTest { + @Test + public void givenStreamValues_whenMappedToNewValues() { + List mapped = Stream.of("hello", "world") + .map(word -> word + "!") + .collect(Collectors.toList()); + + assertThat(mapped).containsExactly("hello!", "world!"); + } + + @Test + public void givenStreamValues_whenReducedWithPrefixingOperation() { + String result = Stream.of("hello", "world") + .reduce("", (a, b) -> b + "-" + a); + + assertThat(result).isEqualTo("world-hello-"); + } + + @Test + public void givenStreamValues_whenReducedWithPrefixingLambda_thenHasNoTrailingDash() { + String result = Stream.of("hello", "world") + .reduce("", (a, b) -> combineWithoutTrailingDash(a, b)); + + assertThat(result).isEqualTo("world-hello"); + } + + private String combineWithoutTrailingDash(String a, String b) { + if (a.isEmpty()) { + return b; + } + return b + "-" + a; + } + + @Test + public void givenStreamValues_whenReducedWithPrefixingMethodReference_thenHasNoTrailingDash() { + String result = Stream.of("hello", "world") + .reduce("", this::combineWithoutTrailingDash); + + assertThat(result).isEqualTo("world-hello"); + } + + @Test + public void givenTwoLists_whenCombined() { + List list1 = Arrays.asList("a", "b", "c"); + List list2 = Arrays.asList(1, 2, 3); + + List result = new ArrayList<>(); + for (int i=0; i < list1.size(); i++) { + result.add(list1.get(i) + list2.get(i)); + } + + assertThat(result).containsExactly("a1", "b2", "c3"); + } + + @Test + public void givenTwoLists_whenCombinedWithGeneralPurposeCombiner() { + List list1 = Arrays.asList("a", "b", "c"); + List list2 = Arrays.asList(1, 2, 3); + + List result = listCombiner(list1, list2, (a, b) -> a + b); + + assertThat(result).containsExactly("a1", "b2", "c3"); + } + + private static List listCombiner(List list1, + List list2, + BiFunction combiner) { + List result = new ArrayList<>(); + for (int i = 0; i < list1.size(); i++) { + result.add(combiner.apply(list1.get(i), list2.get(i))); + } + return result; + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunction() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + // algorithm to determine if the value in list1 > value in list 2 + List result = listCombiner(list1, list2, (a, b) -> a > b); + + assertThat(result).containsExactly(true, true, false); + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunctionByMethodReference() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + // algorithm to determine if the value in list1 > value in list 2 + List result = listCombiner(list1, list2, this::firstIsGreaterThanSecond); + + assertThat(result).containsExactly(true, true, false); + } + + private boolean firstIsGreaterThanSecond(Double a, Float b) { + return a > b; + } + + @Test + public void givenTwoLists_whenComparedForEqualityByCombiningFunction() { + List list1 = Arrays.asList(0.1f, 0.2f, 4f); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + List result = listCombiner(list1, list2, (a, b) -> a.equals(b)); + + assertThat(result).containsExactly(true, true, true); + } + + @Test + public void givenTwoLists_whenComparedForEqualityByCombiningFunctionWithMethodReference() { + List list1 = Arrays.asList(0.1f, 0.2f, 4f); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + List result = listCombiner(list1, list2, Float::equals); + + assertThat(result).containsExactly(true, true, true); + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunctionWithCompareTo() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1d, 0.2d, 4d); + + List result = listCombiner(list1, list2, Double::compareTo); + + assertThat(result).containsExactly(1, 1, -1); + } + + /** + * Allows you to to pass in a lambda or method reference and then + * get access to the BiFunction it is meant to become + */ + private static BiFunction asBiFunction(BiFunction function) { + return function; + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunctionWithComposedBiFunction() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1d, 0.2d, 4d); + + List result = listCombiner(list1, list2, + asBiFunction(Double::compareTo) + .andThen(i -> i > 0)); + + assertThat(result).containsExactly(true, true, false); + } +} diff --git a/core-java-modules/core-java-8/README.md b/core-java-modules/core-java-8/README.md index d11d2debce..b2ae48ea11 100644 --- a/core-java-modules/core-java-8/README.md +++ b/core-java-modules/core-java-8/README.md @@ -40,3 +40,4 @@ - [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain) - [Method References in Java](https://www.baeldung.com/java-method-references) - [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation) +- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach) diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml index c09c970e07..28182e515b 100644 --- a/core-java-modules/core-java-8/pom.xml +++ b/core-java-modules/core-java-8/pom.xml @@ -175,7 +175,6 @@ - 3.5 3.6.1 4.1 4.01 diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java new file mode 100644 index 0000000000..7a9f62341e --- /dev/null +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java @@ -0,0 +1,34 @@ +package com.baeldung.java_8_features.groupingby; + +public class Tuple { + + private BlogPostType type; + private String author; + + public Tuple(BlogPostType type, String author) { + super(); + this.type = type; + this.author = author; + } + + public BlogPostType getType() { + return type; + } + + public void setType(BlogPostType type) { + this.type = type; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + @Override + public String toString() { + return "Tuple [type=" + type + ", author=" + author + ", getType()=" + getType() + ", getAuthor()=" + getAuthor() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; + } +} diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java index bd7943c77b..bf594610bb 100644 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java +++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java @@ -259,4 +259,15 @@ public class OptionalUnitTest { LOG.debug("Getting default value..."); return "Default Value"; } + +// Uncomment code when code base is compatiable with Java 11 +// @Test +// public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() { +// Optional opt = Optional.of("Baeldung"); +// assertFalse(opt.isEmpty()); +// +// opt = Optional.ofNullable(null); +// assertTrue(opt.isEmpty()); +// } + } \ No newline at end of file diff --git a/core-java-modules/core-java-arrays/README.md b/core-java-modules/core-java-arrays/README.md index ed8221ebe4..b5f71cc253 100644 --- a/core-java-modules/core-java-arrays/README.md +++ b/core-java-modules/core-java-arrays/README.md @@ -15,3 +15,4 @@ - [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) - [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays) - [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array) +- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array) diff --git a/core-java-modules/core-java-arrays/pom.xml b/core-java-modules/core-java-arrays/pom.xml index b713c196b5..23db608abc 100644 --- a/core-java-modules/core-java-arrays/pom.xml +++ b/core-java-modules/core-java-arrays/pom.xml @@ -389,7 +389,7 @@ - 3.8.1 + 3.9 1.19 1.19 diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/JaggedArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/JaggedArray.java deleted file mode 100644 index 36cfc88b95..0000000000 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/JaggedArray.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.array; - -import java.util.Arrays; -import java.util.Scanner; - -public class JaggedArray { - - int[][] shortHandFormInitialization() { - int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; - return jaggedArr; - } - - int[][] declarationAndThenInitialization() { - int[][] jaggedArr = new int[3][]; - jaggedArr[0] = new int[] { 1, 2 }; - jaggedArr[1] = new int[] { 3, 4, 5 }; - jaggedArr[2] = new int[] { 6, 7, 8, 9 }; - return jaggedArr; - } - - int[][] declarationAndThenInitializationUsingUserInputs() { - int[][] jaggedArr = new int[3][]; - jaggedArr[0] = new int[2]; - jaggedArr[1] = new int[3]; - jaggedArr[2] = new int[4]; - initializeElements(jaggedArr); - return jaggedArr; - } - - void initializeElements(int[][] jaggedArr) { - Scanner sc = new Scanner(System.in); - for (int outer = 0; outer < jaggedArr.length; outer++) { - for (int inner = 0; inner < jaggedArr[outer].length; inner++) { - jaggedArr[outer][inner] = sc.nextInt(); - } - } - } - - void printElements(int[][] jaggedArr) { - for (int index = 0; index < jaggedArr.length; index++) { - System.out.println(Arrays.toString(jaggedArr[index])); - } - } - - int[] getElementAtGivenIndex(int[][] jaggedArr, int index) { - return jaggedArr[index]; - } - -} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java new file mode 100644 index 0000000000..4e01b99a14 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java @@ -0,0 +1,83 @@ +package com.baeldung.array; + +import java.util.Arrays; +import java.util.Scanner; + +public class MultiDimensionalArray { + + int[][] shortHandFormInitialization() { + int[][] multiDimensionalArray = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + return multiDimensionalArray; + } + + int[][] declarationAndThenInitialization() { + int[][] multiDimensionalArray = new int[3][]; + multiDimensionalArray[0] = new int[] { 1, 2 }; + multiDimensionalArray[1] = new int[] { 3, 4, 5 }; + multiDimensionalArray[2] = new int[] { 6, 7, 8, 9 }; + return multiDimensionalArray; + } + + int[][] declarationAndThenInitializationUsingUserInputs() { + int[][] multiDimensionalArray = new int[3][]; + multiDimensionalArray[0] = new int[2]; + multiDimensionalArray[1] = new int[3]; + multiDimensionalArray[2] = new int[4]; + initializeElements(multiDimensionalArray); + return multiDimensionalArray; + } + + void initializeElements(int[][] multiDimensionalArray) { + Scanner sc = new Scanner(System.in); + for (int outer = 0; outer < multiDimensionalArray.length; outer++) { + for (int inner = 0; inner < multiDimensionalArray[outer].length; inner++) { + multiDimensionalArray[outer][inner] = sc.nextInt(); + } + } + } + + void initialize2DArray(int[][] multiDimensionalArray) { + for (int[] array : multiDimensionalArray) { + Arrays.fill(array, 7); + } + } + + void printElements(int[][] multiDimensionalArray) { + for (int index = 0; index < multiDimensionalArray.length; index++) { + System.out.println(Arrays.toString(multiDimensionalArray[index])); + } + } + + int[] getElementAtGivenIndex(int[][] multiDimensionalArray, int index) { + return multiDimensionalArray[index]; + } + + int[] findLengthOfElements(int[][] multiDimensionalArray) { + int[] arrayOfLengths = new int[multiDimensionalArray.length]; + for (int i = 0; i < multiDimensionalArray.length; i++) { + arrayOfLengths[i] = multiDimensionalArray[i].length; + } + return arrayOfLengths; + } + + Integer[] findLengthOfElements(Integer[][] multiDimensionalArray) { + return Arrays.stream(multiDimensionalArray) + .map(array -> array.length) + .toArray(Integer[]::new); + } + + int[][] copy2DArray(int[][] arrayOfArrays) { + int[][] copied2DArray = new int[arrayOfArrays.length][]; + for (int i = 0; i < arrayOfArrays.length; i++) { + int[] array = arrayOfArrays[i]; + copied2DArray[i] = Arrays.copyOf(array, array.length); + } + return copied2DArray; + } + + Integer[][] copy2DArray(Integer[][] arrayOfArrays) { + return Arrays.stream(arrayOfArrays) + .map(array -> Arrays.copyOf(array, array.length)) + .toArray(Integer[][]::new); + } +} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java new file mode 100644 index 0000000000..62a1a0ee58 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java @@ -0,0 +1,27 @@ +package com.baeldung.array; + +import org.apache.commons.lang3.ArrayUtils; + +public class RemoveElementFromAnArray { + + public int[] removeAnElementWithAGivenIndex(int[] array, int index) { + return ArrayUtils.remove(array, index); + } + + public int[] removeAllElementsWithGivenIndices(int[] array, int... indicies) { + return ArrayUtils.removeAll(array, indicies); + } + + public int[] removeFirstOccurrenceOfGivenElement(int[] array, int element) { + return ArrayUtils.removeElement(array, element); + } + + public int[] removeAllGivenElements(int[] array, int... elements) { + return ArrayUtils.removeElements(array, elements); + } + + public int[] removeAllOccurrencesOfAGivenElement(int[] array, int element) { + return ArrayUtils.removeAllOccurences(array, element); + } + +} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java new file mode 100644 index 0000000000..ec612fd53b --- /dev/null +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java @@ -0,0 +1,71 @@ +package com.baeldung.array; + +import com.baeldung.arraycopy.model.Employee; + +public class SortedArrayChecker { + boolean isSorted(int[] array, int length) { + if (array == null || length < 2) + return true; + + if (array[length - 2] > array[length - 1]) + return false; + + return isSorted(array, length - 1); + } + + boolean isSorted(int[] array) { + for (int i = 0; i < array.length - 1; i++) { + if (array[i] > array[i + 1]) + return false; + } + + return true; + } + + boolean isSorted(String[] array, int length) { + if (array == null || length < 2) + return true; + + if (array[length - 2].compareTo(array[length - 1]) > 0) + return false; + + return isSorted(array, length - 1); + } + +boolean isSorted(String[] array) { + for (int i = 0; i < array.length - 1; ++i) { + if (array[i].compareTo(array[i + 1]) > 0) + return false; + } + + return true; +} + + boolean isSortedByName(Employee[] array) { + for (int i = 0; i < array.length - 1; ++i) { + if (array[i].getName().compareTo(array[i + 1].getName()) > 0) + return false; + } + + return true; + } + +boolean isSortedByAge(Employee[] array) { + for (int i = 0; i < array.length - 1; ++i) { + if (array[i].getAge() > (array[i + 1].getAge())) + return false; + } + + return true; +} + + boolean isSortedByAge(Employee[] array, int length) { + if (array == null || length < 2) + return true; + + if (array[length - 2].getAge() > array[length - 1].getAge()) + return false; + + return isSortedByAge(array, length - 1); + } +} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java index a7592574d9..eba39d5716 100644 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java @@ -6,6 +6,7 @@ public class Employee implements Serializable { private static final long serialVersionUID = -2454619097207585825L; private int id; private String name; + private int age; public Employee() { } @@ -15,10 +16,24 @@ public class Employee implements Serializable { this.name = name; } + public Employee(int id, String name, int age) { + this.id = id; + this.name = name; + this.age = age; + } + + public int getAge() { + return age; + } + public int getId() { return id; } + public void setAge(int age) { + this.age = age; + } + public void setId(int id) { this.id = id; } diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java deleted file mode 100644 index a4dd7e25c3..0000000000 --- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.array; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.PrintStream; - -import org.junit.Test; - -public class JaggedArrayUnitTest { - - private JaggedArray obj = new JaggedArray(); - - @Test - public void whenInitializedUsingShortHandForm_thenCorrect() { - assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization()); - } - - @Test - public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() { - assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization()); - } - - @Test - public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() { - InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes()); - System.setIn(is); - assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs()); - System.setIn(System.in); - } - - @Test - public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() { - int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; - assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0)); - assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1)); - assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2)); - } - - @Test - public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() { - int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; - ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - obj.printElements(jaggedArr); - assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", "")); - System.setOut(System.out); - } - -} diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java new file mode 100644 index 0000000000..8980eaa9dc --- /dev/null +++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.array; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.PrintStream; + +import org.junit.Test; + +public class MultiDimensionalArrayUnitTest { + + private MultiDimensionalArray obj = new MultiDimensionalArray(); + + @Test + public void whenInitializedUsingShortHandForm_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() { + InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes()); + System.setIn(is); + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs()); + System.setIn(System.in); + } + + @Test + public void givenMultiDimensionalArrayAndAnIndex_thenReturnArrayAtGivenIndex() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(multiDimensionalArr, 0)); + assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(multiDimensionalArr, 1)); + assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(multiDimensionalArr, 2)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysAPI_thenVerifyPrintedElements() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + obj.printElements(multiDimensionalArr); + assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", "")); + System.setOut(System.out); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysFill_thenVerifyInitialize2DArray() { + int[][] multiDimensionalArr = new int[3][]; + multiDimensionalArr[0] = new int[2]; + multiDimensionalArr[1] = new int[3]; + multiDimensionalArr[2] = new int[4]; + obj.initialize2DArray(multiDimensionalArr); + assertArrayEquals(new int[][] {{7,7}, {7,7,7}, {7,7,7,7}}, multiDimensionalArr); + } + + @Test + public void givenMultiDimensionalArray_whenUsingIteration_thenVerifyFindLengthOfElements() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new int[]{2,3,4}, obj.findLengthOfElements(multiDimensionalArr)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysStream_thenVerifyFindLengthOfElements() { + Integer[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new Integer[]{2,3,4}, obj.findLengthOfElements(multiDimensionalArr)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysCopyOf_thenVerifyCopy2DArray() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(multiDimensionalArr, obj.copy2DArray(multiDimensionalArr)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysStream_thenVerifyCopy2DArray() { + Integer[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(multiDimensionalArr, obj.copy2DArray(multiDimensionalArr)); + } +} diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java new file mode 100644 index 0000000000..ea52cd17d9 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java @@ -0,0 +1,85 @@ +package com.baeldung.array; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.commons.lang3.ArrayUtils; +import org.junit.jupiter.api.Test; + +class RemoveElementFromAnArrayUnitTest { + + private final RemoveElementFromAnArray sut = new RemoveElementFromAnArray(); + private final int[] inputArray = new int[] { 40, 10, 20, 30, 40, 50 }; + + @Test + void testRemoveAnElementWithAGivenIndex() { + int index = 2; + int[] modifiedArray = sut.removeAnElementWithAGivenIndex(inputArray, index); + + assertFalse(ArrayUtils.contains(modifiedArray, inputArray[index])); + } + + @Test + void testRemoveAllElementsWithGivenIndices() { + int first = 0; + int last = inputArray.length - 1; + int[] modifiedArray = sut.removeAllElementsWithGivenIndices(inputArray, first, last); + + assertFalse(ArrayUtils.contains(modifiedArray, inputArray[first]) && ArrayUtils.contains(modifiedArray, inputArray[last])); + } + + @Test + void testRemoveElement_WhenArrayIsNull_ThrowsIndexOutOfBoundEx() { + int index = 2; + + assertThrows(IndexOutOfBoundsException.class, () -> { + sut.removeAnElementWithAGivenIndex(null, index); + }); + + assertThrows(IndexOutOfBoundsException.class, () -> { + sut.removeAllElementsWithGivenIndices(null, index); + }); + } + + @Test + void testRemoveFirstOccurrenceOfGivenElement() { + int element = 40; + int[] modifiedArray = sut.removeFirstOccurrenceOfGivenElement(inputArray, element); + + int indexInInputArray = ArrayUtils.indexOf(inputArray, element); + int indexInModifiedArray = ArrayUtils.indexOf(modifiedArray, element); + assertFalse(indexInInputArray == indexInModifiedArray); + } + + @Test + void testRemoveAllGivenElements() { + int duplicateElement = 40; + int[] elements = new int[] { duplicateElement, 10, 50 }; + int[] modifiedArray = sut.removeAllGivenElements(inputArray, elements); + + assertTrue(ArrayUtils.contains(modifiedArray, duplicateElement)); + assertFalse(ArrayUtils.contains(modifiedArray, elements[1])); + assertFalse(ArrayUtils.contains(modifiedArray, elements[2])); + } + + @Test + void testRemoveAllOccurrencesOfAGivenElement() { + int element = 40; + int[] modifiedArray = sut.removeAllOccurrencesOfAGivenElement(inputArray, element); + + assertFalse(ArrayUtils.contains(modifiedArray, element)); + } + + @Test + void testRemoveElement_WhenArrayIsNull_ReturnsNull() { + int element = 20; + + assertEquals(null, sut.removeFirstOccurrenceOfGivenElement(null, element)); + assertEquals(null, sut.removeAllGivenElements(null, element)); + assertEquals(null, sut.removeAllOccurrencesOfAGivenElement(null, element)); + + } + +} diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java new file mode 100644 index 0000000000..29866a3c22 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.array; + +import com.baeldung.arraycopy.model.Employee; +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SortedArrayCheckerUnitTest { + + private static final int[] INTEGER_SORTED = {1, 3, 5, 7, 9}; + private static final int[] INTEGER_NOT_SORTED = {1, 3, 11, 7}; + + private static final String[] STRING_SORTED = {"abc", "cde", "fgh"}; + private static final String[] STRING_NOT_SORTED = {"abc", "fgh", "cde", "ijk"}; + + private final Employee[] EMPLOYEES_SORTED_BY_NAME = { + new Employee(1, "Carlos", 26), + new Employee(2, "Daniel", 31), + new Employee(3, "Marta", 27)}; + + private final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = { + new Employee(1, "Daniel", 31), + new Employee(2, "Carlos", 26), + new Employee(3, "Marta", 27)}; + + private final Employee[] EMPLOYEES_SORTED_BY_AGE = { + new Employee(1, "Carlos", 26), + new Employee(2, "Marta", 27), + new Employee(3, "Daniel", 31)}; + + private final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = { + new Employee(1, "Marta", 27), + new Employee(2, "Carlos", 26), + new Employee(3, "Daniel", 31)}; + + private SortedArrayChecker sortedArrayChecker; + + @Before + public void setup() { + sortedArrayChecker = new SortedArrayChecker(); + } + + @Test + public void givenIntegerArray_thenReturnIfItIsSortedOrNot() { + assertThat(sortedArrayChecker.isSorted(INTEGER_SORTED)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(INTEGER_NOT_SORTED)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSorted(INTEGER_SORTED, INTEGER_SORTED.length)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(INTEGER_NOT_SORTED, INTEGER_NOT_SORTED.length)).isEqualTo(false); + } + + @Test + public void givenStringArray_thenReturnIfItIsSortedOrNot() { + assertThat(sortedArrayChecker.isSorted(STRING_SORTED)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(STRING_NOT_SORTED)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSorted(STRING_SORTED, STRING_SORTED.length)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(STRING_NOT_SORTED, STRING_NOT_SORTED.length)).isEqualTo(false); + } + + @Test + public void givenEmployeeArray_thenReturnIfItIsSortedOrNot() { + assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_SORTED_BY_NAME)).isEqualTo(true); + assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_NOT_SORTED_BY_NAME)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE)).isEqualTo(true); + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE, EMPLOYEES_SORTED_BY_AGE.length)).isEqualTo(true); + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE, EMPLOYEES_NOT_SORTED_BY_AGE.length)).isEqualTo(false); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java index ecf68e0b2c..5f7fe356c5 100644 --- a/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java +++ b/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java @@ -42,7 +42,7 @@ public class CoreJavaCollectionsUnitTest { @Test(expected = UnsupportedOperationException.class) public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() { final List list = new ArrayList(Arrays.asList("one", "two", "three")); - final ImmutableList unmodifiableList = ImmutableList.builder().addAll(list).build(); + final ImmutableList unmodifiableList = ImmutableList.builder().addAll(list).build(); unmodifiableList.add("four"); } diff --git a/core-java-modules/core-java-collections-set/README.md b/core-java-modules/core-java-collections-set/README.md index 2e09e920dc..618b4e932c 100644 --- a/core-java-modules/core-java-collections-set/README.md +++ b/core-java-modules/core-java-collections-set/README.md @@ -10,3 +10,4 @@ - [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset) - [Guide to EnumSet](https://www.baeldung.com/java-enumset) - [Set Operations in Java](https://www.baeldung.com/java-set-operations) +- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 2a930efde8..101ed79de0 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -14,20 +14,31 @@ - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + com.google.code.gson + gson + ${gson.version} + + + commons-lang + commons-lang + ${commons-lang.version} + 4.3 27.1-jre + 2.8.5 - + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java new file mode 100644 index 0000000000..53933e4439 --- /dev/null +++ b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java @@ -0,0 +1,59 @@ +package com.baeldung.set; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.lang.SerializationUtils; + +import com.google.gson.Gson; + +public class CopySets { + + // Copy Constructor + public static Set copyByConstructor(Set original) { + Set copy = new HashSet<>(original); + return copy; + } + + // Set.addAll + public static Set copyBySetAddAll(Set original) { + Set copy = new HashSet<>(); + copy.addAll(original); + return copy; + } + + // Set.clone + public static Set copyBySetClone(HashSet original) { + Set copy = (Set) original.clone(); + return copy; + } + + // JSON + public static Set copyByJson(Set original) { + Gson gson = new Gson(); + String jsonStr = gson.toJson(original); + Set copy = gson.fromJson(jsonStr, Set.class); + + return copy; + } + + // Apache Commons Lang + public static Set copyByApacheCommonsLang(Set original) { + Set copy = new HashSet<>(); + for (T item : original) { + copy.add((T) SerializationUtils.clone(item)); + } + return copy; + } + + // Collectors.toSet + public static Set copyByCollectorsToSet(Set original) { + Set copy = original.stream() + .collect(Collectors.toSet()); + + return copy; + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced/pom.xml b/core-java-modules/core-java-concurrency-advanced/pom.xml index a3ac7aa88a..5d41909ed3 100644 --- a/core-java-modules/core-java-concurrency-advanced/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced/pom.xml @@ -72,7 +72,6 @@ 21.0 - 3.5 3.6.1 4.1 4.01 diff --git a/core-java-modules/core-java-concurrency-basic/README.md b/core-java-modules/core-java-concurrency-basic/README.md index 6fa702fbe7..c498bed315 100644 --- a/core-java-modules/core-java-concurrency-basic/README.md +++ b/core-java-modules/core-java-concurrency-basic/README.md @@ -17,3 +17,4 @@ - [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) - [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety) - [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread) +- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) diff --git a/core-java-modules/core-java-concurrency-basic/pom.xml b/core-java-modules/core-java-concurrency-basic/pom.xml index aea4bef6a7..96b3ef76f7 100644 --- a/core-java-modules/core-java-concurrency-basic/pom.xml +++ b/core-java-modules/core-java-concurrency-basic/pom.xml @@ -45,8 +45,6 @@ - - 3.5 3.6.1 1.7.0 diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/delay/Delay.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/delay/Delay.java similarity index 95% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/delay/Delay.java rename to core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/delay/Delay.java index 0cc0c9487f..1689c09f51 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/delay/Delay.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/delay/Delay.java @@ -1,4 +1,4 @@ -package com.baeldung.delay; +package com.baeldung.concurrent.delay; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -61,6 +61,7 @@ public class Delay { executorService.schedule(Delay::someTask1, delayInSeconds, TimeUnit.SECONDS); + executorService.shutdown(); } private static void fixedRateServiceTask(Integer delayInSeconds) { @@ -78,6 +79,7 @@ public class Delay { sf.cancel(true); + executorService.shutdown(); } private static void someTask1() { diff --git a/core-java-modules/core-java-concurrency-collections/pom.xml b/core-java-modules/core-java-concurrency-collections/pom.xml index 27aae4ea6c..ea3bbe44f3 100644 --- a/core-java-modules/core-java-concurrency-collections/pom.xml +++ b/core-java-modules/core-java-concurrency-collections/pom.xml @@ -62,7 +62,6 @@ 21.0 - 3.5 3.6.1 4.1 4.01 diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md new file mode 100644 index 0000000000..5338789a2f --- /dev/null +++ b/core-java-modules/core-java-exceptions/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) diff --git a/core-java-modules/core-java-exceptions/pom.xml b/core-java-modules/core-java-exceptions/pom.xml index 51c4e51341..2e5200944a 100644 --- a/core-java-modules/core-java-exceptions/pom.xml +++ b/core-java-modules/core-java-exceptions/pom.xml @@ -1,26 +1,35 @@ - 4.0.0 - com.baeldung.exception.numberformat - core-java-exceptions - 0.0.1-SNAPSHOT - core-java-exceptions + 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.exception.numberformat + core-java-exceptions + 0.0.1-SNAPSHOT + core-java-exceptions - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - - junit - junit - 4.12 - test - - + + + junit + junit + ${junit.version} + test + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + 3.9 + diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/RootCauseFinder.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java rename to core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/RootCauseFinder.java diff --git a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java index de56fb7113..6dcd0d72e0 100644 --- a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java +++ b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java @@ -1,7 +1,6 @@ -package com.baeldung.error; +package com.baeldung.exception.error; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; public class ErrorGeneratorUnitTest { diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderUnitTest.java b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/RootCauseFinderUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderUnitTest.java rename to core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/RootCauseFinderUnitTest.java diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index 44c703ee68..1a133d2cbe 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -248,7 +248,6 @@ - 3.5 1.55 1.10 3.6.1 diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml index 6a41ec0d1a..059075318a 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml @@ -11,6 +11,14 @@ 1.0 + + + com.baeldung.servicemodule + servicemodule + 1.0 + + + @@ -19,12 +27,4 @@ - - - - com.baeldung.servicemodule - servicemodule - 1.0 - - diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml index 828fe7de6a..757d9229df 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml @@ -2,17 +2,18 @@ - - com.baeldung.decoupling-pattern2 - decoupling-pattern2 - 1.0-SNAPSHOT - 4.0.0 com.baeldung.consumermodule consumermodule 1.0 + + com.baeldung.decoupling-pattern2 + decoupling-pattern2 + 1.0-SNAPSHOT + + com.baeldung.servicemodule diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index 6c700cd005..b1860322a6 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/pom.xml @@ -35,7 +35,6 @@ - 3.5 3.6.1 diff --git a/core-java-modules/core-java-lambdas/README.MD b/core-java-modules/core-java-lambdas/README.MD deleted file mode 100644 index 31790ffbb1..0000000000 --- a/core-java-modules/core-java-lambdas/README.MD +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables) diff --git a/core-java-modules/core-java-lang-oop-2/README.md b/core-java-modules/core-java-lang-oop-2/README.md index 2e36d251ca..72c3c6742b 100644 --- a/core-java-modules/core-java-lang-oop-2/README.md +++ b/core-java-modules/core-java-lang-oop-2/README.md @@ -6,3 +6,4 @@ - [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors) - [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error) - [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes) +- [Raw Types in Java](https://www.baeldung.com/raw-types-java) diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/rawtype/RawTypeDemo.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/rawtype/RawTypeDemo.java new file mode 100644 index 0000000000..e358219d24 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/rawtype/RawTypeDemo.java @@ -0,0 +1,25 @@ +package com.baeldung.rawtype; + +import java.util.ArrayList; +import java.util.List; + +public class RawTypeDemo { + + public static void main(String[] args) { + RawTypeDemo rawTypeDemo = new RawTypeDemo(); + rawTypeDemo.methodA(); + } + + public void methodA() { + // parameterized type + List listStr = new ArrayList<>(); + listStr.add("Hello Folks!"); + methodB(listStr); + String s = listStr.get(1); // ClassCastException at run time + } + + public void methodB(List rawList) { // Inexpressive raw type + rawList.add(1); // Unsafe operation + } + +} diff --git a/core-java-modules/core-java-lang-oop/pom.xml b/core-java-modules/core-java-lang-oop/pom.xml index c9bb3b3e5a..46003b132b 100644 --- a/core-java-modules/core-java-lang-oop/pom.xml +++ b/core-java-modules/core-java-lang-oop/pom.xml @@ -75,13 +75,7 @@ - - - 2.8.5 2.8.2 - - - 3.5 3.10.0 3.0.3 diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java index 3d50e85245..b78b5937e1 100644 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java +++ b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java @@ -54,3 +54,15 @@ class BankAccountCopyConstructor extends BankAccount { this.balance = 0.0f; } } + +class BankAccountChainedConstructors extends BankAccount { + public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) { + this.name = name; + this.opened = opened; + this.balance = balance; + } + + public BankAccountChainedConstructors(String name) { + this(name, LocalDateTime.now(), 0.0f); + } +} diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java index 2cd8832fbf..66c8520e34 100644 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java +++ b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java @@ -1,15 +1,14 @@ package com.baeldung.constructors; -import com.baeldung.constructors.*; +import com.google.common.collect.Comparators; +import org.junit.Test; -import java.util.logging.Logger; import java.time.LocalDateTime; import java.time.Month; +import java.util.ArrayList; +import java.util.logging.Logger; -import org.junit.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.*; public class ConstructorUnitTest { final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName()); @@ -17,26 +16,28 @@ public class ConstructorUnitTest { @Test public void givenNoExplicitContructor_whenUsed_thenFails() { BankAccount account = new BankAccount(); - assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class); + assertThatThrownBy(() -> { + account.toString(); + }).isInstanceOf(Exception.class); } @Test public void givenNoArgumentConstructor_whenUsed_thenSucceeds() { BankAccountEmptyConstructor account = new BankAccountEmptyConstructor(); assertThatCode(() -> { - account.toString(); - }).doesNotThrowAnyException(); + account.toString(); + }).doesNotThrowAnyException(); } @Test public void givenParameterisedConstructor_whenUsed_thenSucceeds() { LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00); BankAccountParameterizedConstructor account = - new BankAccountParameterizedConstructor("Tom", opened, 1000.0f); - + new BankAccountParameterizedConstructor("Tom", opened, 1000.0f); + assertThatCode(() -> { - account.toString(); - }).doesNotThrowAnyException(); + account.toString(); + }).doesNotThrowAnyException(); } @Test @@ -47,7 +48,16 @@ public class ConstructorUnitTest { assertThat(account.getName()).isEqualTo(newAccount.getName()); assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened()); - + assertThat(newAccount.getBalance()).isEqualTo(0.0f); } + + @Test + public void givenChainedConstructor_whenUsed_thenMaintainsLogic() { + BankAccountChainedConstructors account = new BankAccountChainedConstructors("Tim"); + BankAccountChainedConstructors newAccount = new BankAccountChainedConstructors("Tim", LocalDateTime.now(), 0.0f); + + assertThat(account.getName()).isEqualTo(newAccount.getName()); + assertThat(account.getBalance()).isEqualTo(newAccount.getBalance()); + } } diff --git a/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/breakloop/LoopBreaking.java b/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/breakloop/LoopBreaking.java new file mode 100644 index 0000000000..90b99f57cb --- /dev/null +++ b/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/breakloop/LoopBreaking.java @@ -0,0 +1,47 @@ +package com.baeldung.breakloop; + +public class LoopBreaking { + + public String simpleBreak() { + String result = ""; + for (int outerCounter = 0; outerCounter < 2; outerCounter++) { + result += "outer" + outerCounter; + for (int innerCounter = 0; innerCounter < 2; innerCounter++) { + result += "inner" + innerCounter; + if (innerCounter == 0) { + break; + } + } + } + return result; + } + + public String labelBreak() { + String result = ""; + myBreakLabel: + for (int outerCounter = 0; outerCounter < 2; outerCounter++) { + result += "outer" + outerCounter; + for (int innerCounter = 0; innerCounter < 2; innerCounter++) { + result += "inner" + innerCounter; + if (innerCounter == 0) { + break myBreakLabel; + } + } + } + return result; + } + + public String usingReturn() { + String result = ""; + for (int outerCounter = 0; outerCounter < 2; outerCounter++) { + result += "outer" + outerCounter; + for (int innerCounter = 0; innerCounter < 2; innerCounter++) { + result += "inner" + innerCounter; + if (innerCounter == 0) { + return result; + } + } + } + return "failed"; + } +} diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/breakloop/LoopBreakingUnitTest.java b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/breakloop/LoopBreakingUnitTest.java new file mode 100644 index 0000000000..c4b6573c86 --- /dev/null +++ b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/breakloop/LoopBreakingUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.breakloop; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LoopBreakingUnitTest { + + private LoopBreaking loopBreaking = new LoopBreaking(); + + @Test + void whenUsingBreak_shouldBreakInnerLoop() { + assertEquals("outer0inner0outer1inner0", loopBreaking.simpleBreak()); + } + + @Test + void whenUsingLabeledBreak_shouldBreakInnerLoopAndOuterLoop() { + assertEquals("outer0inner0", loopBreaking.labelBreak()); + } + + @Test + void whenUsingReturn_shouldBreakInnerLoopAndOuterLoop() { + assertEquals("outer0inner0", loopBreaking.usingReturn()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang/README.md b/core-java-modules/core-java-lang/README.md index e9169a5820..74936eac21 100644 --- a/core-java-modules/core-java-lang/README.md +++ b/core-java-modules/core-java-lang/README.md @@ -18,7 +18,6 @@ - [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces) - [Recursion In Java](http://www.baeldung.com/java-recursion) - [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize) -- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) - [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) - [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system) - [Using Java Assertions](http://www.baeldung.com/java-assert) diff --git a/core-java-modules/core-java-lang/pom.xml b/core-java-modules/core-java-lang/pom.xml index 45ccc8d0f5..8311636873 100644 --- a/core-java-modules/core-java-lang/pom.xml +++ b/core-java-modules/core-java-lang/pom.xml @@ -75,9 +75,6 @@ 2.8.2 - - - 3.5 1.5.0-b01 diff --git a/core-java-modules/core-java-networking/pom.xml b/core-java-modules/core-java-networking/pom.xml index 550ebdb4ff..e2ee7b2fcc 100644 --- a/core-java-modules/core-java-networking/pom.xml +++ b/core-java-modules/core-java-networking/pom.xml @@ -42,8 +42,6 @@ 1.5.0-b01 - 2.5 - 3.5 4.3.4.RELEASE diff --git a/core-java-modules/core-java-nio/README.md b/core-java-modules/core-java-nio/README.md new file mode 100644 index 0000000000..9034c3b3b1 --- /dev/null +++ b/core-java-modules/core-java-nio/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Determine File Creating Date in Java](https://www.baeldung.com/java-file-creation-date) diff --git a/core-java-modules/core-java-nio/pom.xml b/core-java-modules/core-java-nio/pom.xml index 36d6848998..31433e632f 100644 --- a/core-java-modules/core-java-nio/pom.xml +++ b/core-java-modules/core-java-nio/pom.xml @@ -8,9 +8,9 @@ jar - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java \ No newline at end of file diff --git a/core-java-modules/core-java-nio/src/main/java/com/baeldung/creationdate/CreationDateResolver.java b/core-java-modules/core-java-nio/src/main/java/com/baeldung/creationdate/CreationDateResolver.java new file mode 100644 index 0000000000..6347a6e681 --- /dev/null +++ b/core-java-modules/core-java-nio/src/main/java/com/baeldung/creationdate/CreationDateResolver.java @@ -0,0 +1,35 @@ +package com.baeldung.creationdate; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileTime; +import java.time.Instant; +import java.util.Optional; + +public class CreationDateResolver { + + public Instant resolveCreationTimeWithBasicAttributes(Path path) { + try { + final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class); + final FileTime fileTime = attr.creationTime(); + + return fileTime.toInstant(); + } catch (IOException ex) { + throw new RuntimeException("An issue occured went wrong when resolving creation time", ex); + } + } + + public Optional resolveCreationTimeWithAttribute(Path path) { + try { + final FileTime creationTime = (FileTime) Files.getAttribute(path, "creationTime"); + + return Optional + .ofNullable(creationTime) + .map((FileTime::toInstant)); + } catch (IOException ex) { + throw new RuntimeException("An issue occured went wrong when resolving creation time", ex); + } + } +} diff --git a/core-java-modules/core-java-nio/src/test/java/com/baeldung/creationdate/CreationDateResolverUnitTest.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/creationdate/CreationDateResolverUnitTest.java new file mode 100644 index 0000000000..5402852c74 --- /dev/null +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/creationdate/CreationDateResolverUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.creationdate; + +import org.junit.Test; + +import java.io.File; +import java.nio.file.Path; +import java.time.Instant; +import java.util.Optional; + +import static org.junit.Assert.assertTrue; + +public class CreationDateResolverUnitTest { + + private final CreationDateResolver creationDateResolver = new CreationDateResolver(); + + @Test + public void givenFile_whenGettingCreationDateTimeFromBasicAttributes_thenReturnDate() throws Exception { + + final File file = File.createTempFile("createdFile", ".txt"); + final Path path = file.toPath(); + + final Instant response = creationDateResolver.resolveCreationTimeWithBasicAttributes(path); + + assertTrue(Instant + .now() + .isAfter(response)); + + } + + @Test + public void givenFile_whenGettingCreationDateTimeFromAttribute_thenReturnDate() throws Exception { + + final File file = File.createTempFile("createdFile", ".txt"); + final Path path = file.toPath(); + + final Optional response = creationDateResolver.resolveCreationTimeWithAttribute(path); + + response.ifPresent((value) -> { + assertTrue(Instant + .now() + .isAfter(value)); + }); + + } +} diff --git a/core-java-modules/core-java-optional/README.md b/core-java-modules/core-java-optional/README.md new file mode 100644 index 0000000000..b6848b5d33 --- /dev/null +++ b/core-java-modules/core-java-optional/README.md @@ -0,0 +1,6 @@ +========= + +## Core Java Optional + +### Relevant Articles: +- [Java Optional as Return Type](https://www.baeldung.com/java-optional-return) diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml new file mode 100644 index 0000000000..eb981c0907 --- /dev/null +++ b/core-java-modules/core-java-optional/pom.xml @@ -0,0 +1,52 @@ + + 4.0.0 + core-java-optional + 0.1.0-SNAPSHOT + jar + + + com.baeldung.core-java-modules + core-java-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.core.version} + + + com.h2database + h2 + ${h2.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + UTF-8 + 1.8 + 1.8 + 5.4.0.Final + + \ No newline at end of file diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/User.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/User.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/UserOptional.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/UserOptional.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml index 85194b176e..f6c5ef04a5 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/pom.xml @@ -68,7 +68,6 @@ - 3.5 4.1 4.01 diff --git a/core-java-modules/core-java-os/src/main/java/com/baeldung/core/pwd/CurrentDirectoryFetcher.java b/core-java-modules/core-java-os/src/main/java/com/baeldung/core/pwd/CurrentDirectoryFetcher.java new file mode 100644 index 0000000000..8f022d2cc7 --- /dev/null +++ b/core-java-modules/core-java-os/src/main/java/com/baeldung/core/pwd/CurrentDirectoryFetcher.java @@ -0,0 +1,40 @@ +package com.baeldung.core.pwd; + +import java.io.File; +import java.nio.file.FileSystems; +import java.nio.file.Paths; + +public final class CurrentDirectoryFetcher { + + public static void main(String[] args) { + System.out.printf("Current Directory Using Java System API: %s%n", currentDirectoryUsingSystemProperties()); + + System.out.printf("Current Directory Using Java IO File API: %s%n", currentDirectoryUsingFile()); + + System.out.printf("Current Directory Using Java NIO FileSystems API: %s%n", currentDirectoryUsingFileSystems()); + + System.out.printf("Current Directory Using Java NIO Paths API: %s%n", currentDirectoryUsingPaths()); + } + + public static String currentDirectoryUsingSystemProperties() { + return System.getProperty("user.dir"); + } + + public static String currentDirectoryUsingPaths() { + return Paths.get("") + .toAbsolutePath() + .toString(); + } + + public static String currentDirectoryUsingFileSystems() { + return FileSystems.getDefault() + .getPath("") + .toAbsolutePath() + .toString(); + } + + public static String currentDirectoryUsingFile() { + return new File("").getAbsolutePath(); + } + +} diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/core/pwd/CurrentDirectoryFetcherTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/core/pwd/CurrentDirectoryFetcherTest.java new file mode 100644 index 0000000000..dbaad211d9 --- /dev/null +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/core/pwd/CurrentDirectoryFetcherTest.java @@ -0,0 +1,34 @@ +package com.baeldung.core.pwd; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class CurrentDirectoryFetcherTest { + + private static final String CURRENT_DIR = "core-java-os"; + + @Test + public void whenUsingSystemProperties_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingSystemProperties() + .endsWith(CURRENT_DIR)); + } + + @Test + public void whenUsingJavaNioPaths_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingPaths() + .endsWith(CURRENT_DIR)); + } + + @Test + public void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFileSystems() + .endsWith(CURRENT_DIR)); + } + + @Test + public void whenUsingJavaIoFile_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFile() + .endsWith(CURRENT_DIR)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-perf/pom.xml b/core-java-modules/core-java-perf/pom.xml index f225a9554b..b9c9d30ac0 100644 --- a/core-java-modules/core-java-perf/pom.xml +++ b/core-java-modules/core-java-perf/pom.xml @@ -23,11 +23,4 @@ - - - - 3.8.1 - - - diff --git a/core-java-modules/core-java-security/pom.xml b/core-java-modules/core-java-security/pom.xml index ed82a5209a..d3efb26fe8 100644 --- a/core-java-modules/core-java-security/pom.xml +++ b/core-java-modules/core-java-security/pom.xml @@ -43,7 +43,6 @@ - 3.8.1 1.60 1.11 diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/random/SecureRandomDemo.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/random/SecureRandomDemo.java new file mode 100644 index 0000000000..02f815f5a7 --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/random/SecureRandomDemo.java @@ -0,0 +1,36 @@ +package com.baeldung.random; + +import java.security.SecureRandom; +import java.security.NoSuchAlgorithmException; +import java.util.stream.IntStream; +import java.util.stream.LongStream; +import java.util.stream.DoubleStream; + +public interface SecureRandomDemo { + + public static void generateSecureRandomValues() { + SecureRandom sr = new SecureRandom(); + + int randomInt = sr.nextInt(); + long randomLong = sr.nextLong(); + float randomFloat = sr.nextFloat(); + double randomDouble = sr.nextDouble(); + boolean randomBoolean = sr.nextBoolean(); + + IntStream randomIntStream = sr.ints(); + LongStream randomLongStream = sr.longs(); + DoubleStream randomDoubleStream = sr.doubles(); + + byte[] values = new byte[124]; + sr.nextBytes(values); + } + + public static SecureRandom getSecureRandomForAlgorithm(String algorithm) throws NoSuchAlgorithmException { + if (algorithm == null || algorithm.isEmpty()) { + return new SecureRandom(); + } + + return SecureRandom.getInstance(algorithm); + } + +} diff --git a/core-java-modules/core-java-sun/pom.xml b/core-java-modules/core-java-sun/pom.xml index da27564d96..ab5f945114 100644 --- a/core-java-modules/core-java-sun/pom.xml +++ b/core-java-modules/core-java-sun/pom.xml @@ -264,7 +264,6 @@ 23.0 - 3.5 1.55 1.10 3.6.1 diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index 65fb5ddb9d..436a481803 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -37,7 +37,6 @@ - [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) -- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) - [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources) - [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class) - [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) @@ -51,4 +50,5 @@ - [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) - [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post) +- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) - [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index 7942f3e7e2..2a2cb3a6af 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -13,7 +13,6 @@ ../../parent-java - commons-io @@ -114,7 +113,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} @@ -454,8 +453,6 @@ 2.8.2 - 3.9 - 2.5 3.6.1 1.0.3 0.4 @@ -472,7 +469,6 @@ 2.21.0 1.1 - 1.4.197 2.1.0.1 1.19 diff --git a/core-java-modules/multimodulemavenproject/daomodule/pom.xml b/core-java-modules/multimodulemavenproject/daomodule/pom.xml index a260e15e6d..e98c48aa76 100644 --- a/core-java-modules/multimodulemavenproject/daomodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/daomodule/pom.xml @@ -1,15 +1,16 @@ 4.0.0 + com.baeldung.daomodule + daomodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.daomodule - daomodule - 1.0 - jar diff --git a/core-java-modules/multimodulemavenproject/entitymodule/pom.xml b/core-java-modules/multimodulemavenproject/entitymodule/pom.xml index 1fd672d03e..b90a7ed068 100644 --- a/core-java-modules/multimodulemavenproject/entitymodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/entitymodule/pom.xml @@ -1,15 +1,16 @@ 4.0.0 + com.baeldung.entitymodule + entitymodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.entitymodule - entitymodule - 1.0 - jar diff --git a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml index 26e6a15b1e..1f44a1690c 100644 --- a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml @@ -1,15 +1,16 @@ 4.0.0 + com.baeldung.mainappmodule + mainappmodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.mainappmodule - mainappmodule - 1.0 - jar diff --git a/core-java-modules/multimodulemavenproject/pom.xml b/core-java-modules/multimodulemavenproject/pom.xml index 3d56f1356b..ad347a4179 100644 --- a/core-java-modules/multimodulemavenproject/pom.xml +++ b/core-java-modules/multimodulemavenproject/pom.xml @@ -14,18 +14,25 @@ ../../ + + entitymodule + daomodule + userdaomodule + mainappmodule + + junit junit - 4.12 + ${junit.version} test org.assertj assertj-core - 3.12.2 + ${assertj-core.version} test @@ -49,14 +56,8 @@ - - entitymodule - daomodule - userdaomodule - mainappmodule - - UTF-8 + 3.12.2 diff --git a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml index 63968452db..d3543d5864 100644 --- a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml @@ -1,24 +1,16 @@ 4.0.0 + com.baeldung.userdaomodule + userdaomodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.userdaomodule - userdaomodule - 1.0 - jar - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - @@ -33,6 +25,15 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + 9 9 diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 2b563a7be4..11a1003460 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -16,6 +16,7 @@ pre-jpms core-java-exceptions + core-java-optional diff --git a/core-java-modules/pre-jpms/pom.xml b/core-java-modules/pre-jpms/pom.xml index 169cd21f3e..380d94fbf1 100644 --- a/core-java-modules/pre-jpms/pom.xml +++ b/core-java-modules/pre-jpms/pom.xml @@ -18,9 +18,10 @@ org.slf4j slf4j-api - 1.7.25 + ${org.slf4j.version} + pre-jpms @@ -65,9 +66,9 @@ - + UTF-8 diff --git a/core-kotlin-io/pom.xml b/core-kotlin-io/pom.xml index a0b688a223..78b36626d6 100644 --- a/core-kotlin-io/pom.xml +++ b/core-kotlin-io/pom.xml @@ -22,7 +22,7 @@ org.junit.jupiter junit-jupiter - ${junit.jupiter.version} + ${junit-jupiter.version} test @@ -88,7 +88,7 @@ 1.3.30 - 5.4.2 + 5.4.2 2.27.0 1.9.12 3.10.0 diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index 5de986b49e..e4d243360a 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -39,7 +39,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} com.github.kittinunf.fuel @@ -76,11 +76,9 @@ 3.6.1 - 3.8.1 1.1.1 5.2.0 3.10.0 - 1.4.197 1.15.0 3.3.0 1.16.1 diff --git a/couchbase/pom.xml b/couchbase/pom.xml index 31e6a53388..fc40749c61 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -69,7 +69,6 @@ 2.5.0 4.3.5.RELEASE - 3.5 diff --git a/custom-pmd-0.0.1.jar b/custom-pmd-0.0.1.jar index e19bce6e52..3ae5e8e41a 100644 Binary files a/custom-pmd-0.0.1.jar and b/custom-pmd-0.0.1.jar differ diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index 74e6d9593b..9964bf2bb4 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -7,6 +7,12 @@ custom-pmd jar http://maven.apache.org + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + diff --git a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java index 3b73f9c21c..2cbab782ee 100644 --- a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java +++ b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java @@ -22,6 +22,10 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule { String className = node.getImage(); Objects.requireNonNull(className); + if (className.endsWith("SpringContextTest")) { + return data; + } + if (className.endsWith("Tests") || (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) { addViolation(data, node); diff --git a/ddd/README.md b/ddd/README.md index 4275bc26b3..6b68fe2205 100644 --- a/ddd/README.md +++ b/ddd/README.md @@ -1,4 +1,5 @@ ### Relevant articles - [Persisting DDD Aggregates](https://www.baeldung.com/spring-persisting-ddd-aggregates) +- [Double Dispatch in DDD](https://www.baeldung.com/ddd-double-dispatch) - [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) diff --git a/disruptor/pom.xml b/disruptor/pom.xml index 296704f546..e1d78e7ed6 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -115,7 +115,6 @@ - 3.5 3.3.6 6.10 diff --git a/dozer/pom.xml b/dozer/pom.xml index 5720001acf..8234eb4c79 100644 --- a/dozer/pom.xml +++ b/dozer/pom.xml @@ -26,7 +26,6 @@ - 3.5 5.5.1 diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index f49a51ea4b..e8b327e35f 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -8,6 +8,13 @@ 1.0-SNAPSHOT flyway-cdi-extension + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + javax.enterprise @@ -51,6 +58,5 @@ 5.1.4 8.5.33 1.3.2 - 1.4.197 diff --git a/gson/pom.xml b/gson/pom.xml index a21d783c39..9d2cf630d0 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -64,7 +64,6 @@ 2.8.0 - 3.5 4.1 2.9.6 diff --git a/guava-collections/pom.xml b/guava-collections/pom.xml index a717023156..ecda3c9595 100644 --- a/guava-collections/pom.xml +++ b/guava-collections/pom.xml @@ -55,7 +55,6 @@ 24.0-jre - 3.5 4.1 diff --git a/guava/pom.xml b/guava/pom.xml index 1d37a79ab6..34eb7eafa6 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -49,7 +49,6 @@ 24.0-jre - 3.5 3.6.1 diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index efcf0452e2..7dd54c8fc4 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -297,7 +297,6 @@ 19.0 - 3.5 1.10 4.1.4 @@ -305,7 +304,6 @@ 4.4.11 4.5.8 - 2.6 1.6.1 diff --git a/httpclient/pom.xml b/httpclient/pom.xml index def3a05816..8cd483cfc6 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -120,7 +120,6 @@ 19.0 - 3.5 1.10 4.1.4 diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 7bb3e98246..e08af2c40f 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -65,7 +65,6 @@ 1.5.8 0.20.7 - 2.6 2.7 1.5.8 1.5.8 diff --git a/jackson-2/README.md b/jackson-2/README.md index ee9f8458a0..d8c233a00e 100644 --- a/jackson-2/README.md +++ b/jackson-2/README.md @@ -9,4 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) - [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml) - [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model) - +- [Converting JSON to CSV in Java](https://www.baeldung.com/java-converting-json-to-csv) diff --git a/jackson-2/pom.xml b/jackson-2/pom.xml index 6b973dd6f5..2fff1f8706 100644 --- a/jackson-2/pom.xml +++ b/jackson-2/pom.xml @@ -26,14 +26,21 @@ com.fasterxml.jackson.dataformat jackson-dataformat-yaml - 2.9.8 + ${jackson.version} + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-csv + ${jackson.version} + com.fasterxml.jackson.datatype jackson-datatype-jsr310 - 2.9.8 + ${jackson.version} diff --git a/jackson-2/src/main/java/com/baeldung/jackson/csv/JsonCsvConverter.java b/jackson-2/src/main/java/com/baeldung/jackson/csv/JsonCsvConverter.java new file mode 100644 index 0000000000..71c6de4d7e --- /dev/null +++ b/jackson-2/src/main/java/com/baeldung/jackson/csv/JsonCsvConverter.java @@ -0,0 +1,59 @@ +package com.baeldung.jackson.csv; + +import java.io.File; +import java.io.IOException; + +import com.baeldung.jackson.entities.OrderLine; +import com.baeldung.jackson.mixin.OrderLineForCsv; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MappingIterator; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.dataformat.csv.CsvMapper; +import com.fasterxml.jackson.dataformat.csv.CsvSchema; +import com.fasterxml.jackson.dataformat.csv.CsvSchema.Builder; + +public class JsonCsvConverter { + + public static void JsonToCsv(File jsonFile, File csvFile) throws IOException { + JsonNode jsonTree = new ObjectMapper().readTree(jsonFile); + + Builder csvSchemaBuilder = CsvSchema.builder(); + JsonNode firstObject = jsonTree.elements().next(); + firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} ); + CsvSchema csvSchema = csvSchemaBuilder + .build() + .withHeader(); + + CsvMapper csvMapper = new CsvMapper(); + csvMapper.writerFor(JsonNode.class) + .with(csvSchema) + .writeValue(csvFile, jsonTree); + } + + public static void csvToJson(File csvFile, File jsonFile) throws IOException { + CsvSchema orderLineSchema = CsvSchema.emptySchema().withHeader(); + CsvMapper csvMapper = new CsvMapper(); + MappingIterator orderLines = csvMapper.readerFor(OrderLine.class) + .with(orderLineSchema) + .readValues(csvFile); + + new ObjectMapper() + .configure(SerializationFeature.INDENT_OUTPUT, true) + .writeValue(jsonFile, orderLines.readAll()); + } + + public static void JsonToFormattedCsv(File jsonFile, File csvFile) throws IOException { + CsvMapper csvMapper = new CsvMapper(); + CsvSchema csvSchema = csvMapper + .schemaFor(OrderLineForCsv.class) + .withHeader(); + csvMapper.addMixIn(OrderLine.class, OrderLineForCsv.class); + + OrderLine[] orderLines = new ObjectMapper() + .readValue(jsonFile, OrderLine[].class); + csvMapper.writerFor(OrderLine[].class) + .with(csvSchema) + .writeValue(csvFile, orderLines); + } +} diff --git a/jackson-2/src/main/java/com/baeldung/jackson/mixin/OrderLineForCsv.java b/jackson-2/src/main/java/com/baeldung/jackson/mixin/OrderLineForCsv.java new file mode 100644 index 0000000000..05d70a8053 --- /dev/null +++ b/jackson-2/src/main/java/com/baeldung/jackson/mixin/OrderLineForCsv.java @@ -0,0 +1,25 @@ +package com.baeldung.jackson.mixin; + +import java.math.BigDecimal; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonPropertyOrder({ + "count", + "name" +}) +public abstract class OrderLineForCsv { + + @JsonProperty("name") + private String item; + + @JsonProperty("count") + private int quantity; + + @JsonIgnore + private BigDecimal unitPrice; + + +} diff --git a/jackson-2/src/main/resources/orderLines.csv b/jackson-2/src/main/resources/orderLines.csv new file mode 100644 index 0000000000..e15e12f2bf --- /dev/null +++ b/jackson-2/src/main/resources/orderLines.csv @@ -0,0 +1,3 @@ +item,quantity,unitPrice +"No. 9 Sprockets",12,1.23 +"Widget (10mm)",4,3.45 diff --git a/jackson-2/src/main/resources/orderLines.json b/jackson-2/src/main/resources/orderLines.json new file mode 100644 index 0000000000..64f18e1673 --- /dev/null +++ b/jackson-2/src/main/resources/orderLines.json @@ -0,0 +1,9 @@ +[ { + "item" : "No. 9 Sprockets", + "quantity" : 12, + "unitPrice" : 1.23 +}, { + "item" : "Widget (10mm)", + "quantity" : 4, + "unitPrice" : 3.45 +} ] \ No newline at end of file diff --git a/jackson-2/src/test/java/com/baeldung/jackson/csv/CsvUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/csv/CsvUnitTest.java new file mode 100644 index 0000000000..60c8ce79f3 --- /dev/null +++ b/jackson-2/src/test/java/com/baeldung/jackson/csv/CsvUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.jackson.csv; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.List; + +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.google.common.io.Files; + + +public class CsvUnitTest { + + @Test + public void givenJsonInput_thenWriteCsv() throws JsonParseException, JsonMappingException, IOException { + JsonCsvConverter.JsonToCsv(new File("src/main/resources/orderLines.json"), + new File("src/main/resources/csvFromJson.csv")); + + assertEquals(readFile("src/main/resources/csvFromJson.csv"), + readFile("src/test/resources/expectedCsvFromJson.csv")); + } + + @Test + public void givenCsvInput_thenWritesJson() throws JsonParseException, JsonMappingException, IOException { + JsonCsvConverter.csvToJson(new File("src/main/resources/orderLines.csv"), + new File("src/main/resources/jsonFromCsv.json")); + + assertEquals(readFile("src/main/resources/jsonFromCsv.json"), + readFile("src/test/resources/expectedJsonFromCsv.json")); + + } + + @Test + public void givenJsonInput_thenWriteFormattedCsvOutput() throws JsonParseException, JsonMappingException, IOException { + JsonCsvConverter.JsonToFormattedCsv(new File("src/main/resources/orderLines.json"), + new File("src/main/resources/formattedCsvFromJson.csv")); + + assertEquals(readFile("src/main/resources/formattedCsvFromJson.csv"), + readFile("src/test/resources/expectedFormattedCsvFromJson.csv")); + + } + + private List readFile(String filename) throws IOException { + return Files.readLines(new File(filename), Charset.forName("utf-8")); + } + + +} +; \ No newline at end of file diff --git a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java new file mode 100644 index 0000000000..03d7c63e36 --- /dev/null +++ b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java @@ -0,0 +1,126 @@ +package com.baeldung.jackson.json.compare; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Comparator; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.NumericNode; +import com.fasterxml.jackson.databind.node.TextNode; + +public class JsonCompareUnitTest { + + @Test + public void givenTwoSameJsonDataObjects_whenCompared_thenAreEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\", \"age\": 34 }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"age\": 34, \"fullName\": \"John Miles\" }}"; + + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + assertEquals(actualObj1, actualObj2); + + } + + @Test + public void givenTwoSameNestedJsonDataObjects_whenCompared_thenEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; + + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + assertEquals(actualObj1, actualObj2); + + } + + @Test + public void givenTwoSameListJsonDataObjects_whenCompared_thenEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}"; + + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + assertEquals(actualObj1, actualObj2); + + } + + @Test + public void givenTwoJsonDataObjects_whenComparedUsingCustomNumericNodeComparator_thenEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"name\": \"John\",\"score\":5.0}"; + String s2 = "{\"name\": \"John\",\"score\":5}"; + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + NumericNodeComparator cmp = new NumericNodeComparator(); + + assertNotEquals(actualObj1, actualObj2); + assertTrue(actualObj1.equals(cmp, actualObj2)); + + } + + public class NumericNodeComparator implements Comparator { + @Override + public int compare(JsonNode o1, JsonNode o2) { + if (o1.equals(o2)) { + return 0; + } + if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) { + Double d1 = ((NumericNode) o1).asDouble(); + Double d2 = ((NumericNode) o2).asDouble(); + if (d1.compareTo(d2) == 0) { + return 0; + } + } + return 1; + } + } + + @Test + public void givenTwoJsonDataObjects_whenComparedUsingCustomTextNodeComparator_thenEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"name\": \"JOHN\",\"score\":5}"; + String s2 = "{\"name\": \"John\",\"score\":5}"; + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + TextNodeComparator cmp = new TextNodeComparator(); + + assertNotEquals(actualObj1, actualObj2); + assertTrue(actualObj1.equals(cmp, actualObj2)); + + } + + public class TextNodeComparator implements Comparator { + @Override + public int compare(JsonNode o1, JsonNode o2) { + if (o1.equals(o2)) { + return 0; + } + if ((o1 instanceof TextNode) && (o2 instanceof TextNode)) { + String s1 = ((TextNode) o1).asText(); + String s2 = ((TextNode) o2).asText(); + if (s1.equalsIgnoreCase(s2)) { + return 0; + } + } + return 1; + } + } +} diff --git a/jackson-2/src/test/resources/expectedCsvFromJson.csv b/jackson-2/src/test/resources/expectedCsvFromJson.csv new file mode 100644 index 0000000000..e15e12f2bf --- /dev/null +++ b/jackson-2/src/test/resources/expectedCsvFromJson.csv @@ -0,0 +1,3 @@ +item,quantity,unitPrice +"No. 9 Sprockets",12,1.23 +"Widget (10mm)",4,3.45 diff --git a/jackson-2/src/test/resources/expectedFormattedCsvFromJson.csv b/jackson-2/src/test/resources/expectedFormattedCsvFromJson.csv new file mode 100644 index 0000000000..5a60ba602a --- /dev/null +++ b/jackson-2/src/test/resources/expectedFormattedCsvFromJson.csv @@ -0,0 +1,3 @@ +count,name +12,"No. 9 Sprockets" +4,"Widget (10mm)" diff --git a/jackson-2/src/test/resources/expectedJsonFromCsv.json b/jackson-2/src/test/resources/expectedJsonFromCsv.json new file mode 100644 index 0000000000..64f18e1673 --- /dev/null +++ b/jackson-2/src/test/resources/expectedJsonFromCsv.json @@ -0,0 +1,9 @@ +[ { + "item" : "No. 9 Sprockets", + "quantity" : 12, + "unitPrice" : 1.23 +}, { + "item" : "Widget (10mm)", + "quantity" : 4, + "unitPrice" : 3.45 +} ] \ No newline at end of file diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index 5023ad87b6..05c1ef4595 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -118,7 +118,6 @@ - 3.8 2.10 2.8.5 4.2 diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java b/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java index 4230420132..146f274380 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java @@ -165,7 +165,7 @@ public class JacksonSerializationIgnoreUnitTest { } @Test - public final void givenIgnoringNullFieldsOnClass_whenWritingObjectWithNullField_thenFieldIsIgnored() throws JsonProcessingException { + public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull(); @@ -178,7 +178,7 @@ public class JacksonSerializationIgnoreUnitTest { } @Test - public final void givenIgnoringNullFieldsGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { + public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); final MyDto dtoObject = new MyDto(); diff --git a/jackson/pom.xml b/jackson/pom.xml index 948248d255..8a083525a2 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -118,7 +118,6 @@ - 3.8 2.10 2.8.5 4.2 diff --git a/java-collections-conversions/README.md b/java-collections-conversions/README.md index 31fead3c42..614f20f186 100644 --- a/java-collections-conversions/README.md +++ b/java-collections-conversions/README.md @@ -10,4 +10,7 @@ - [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string) - [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map) - [Array to String Conversions](https://www.baeldung.com/java-array-to-string) -- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) \ No newline at end of file +- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) +- [Java 8 Collectors toMap](https://www.baeldung.com/java-collectors-tomap) +- [Converting Iterable to Collection in Java](https://www.baeldung.com/java-iterable-to-collection) +- [Converting Iterator to List](https://www.baeldung.com/java-convert-iterator-to-list) diff --git a/java-collections-conversions/pom.xml b/java-collections-conversions/pom.xml index ee7221b25e..24d918d105 100644 --- a/java-collections-conversions/pom.xml +++ b/java-collections-conversions/pom.xml @@ -33,7 +33,6 @@ - 3.5 4.1 3.6.1 diff --git a/java-collections-conversions/src/test/java/com/baeldung/convert/iteratortolist/ConvertIteratorToListServiceUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convert/iteratortolist/ConvertIteratorToListServiceUnitTest.java new file mode 100644 index 0000000000..ced2ddcfc0 --- /dev/null +++ b/java-collections-conversions/src/test/java/com/baeldung/convert/iteratortolist/ConvertIteratorToListServiceUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.convert.iteratortolist; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import org.apache.commons.collections4.IteratorUtils; +import org.junit.Before; +import org.junit.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +public class ConvertIteratorToListServiceUnitTest { + + Iterator iterator; + + @Before + public void setUp() throws Exception { + iterator = Arrays.asList(1, 2, 3) + .iterator(); + } + + @Test + public void givenAnIterator_whenConvertIteratorToListUsingWhileLoop_thenReturnAList() { + + List actualList = new ArrayList(); + + // Convert Iterator to List using while loop dsf + while (iterator.hasNext()) { + actualList.add(iterator.next()); + } + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } + + @Test + public void givenAnIterator_whenConvertIteratorToListAfterJava8_thenReturnAList() { + List actualList = new ArrayList(); + + // Convert Iterator to List using Java 8 + iterator.forEachRemaining(actualList::add); + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } + + @Test + public void givenAnIterator_whenConvertIteratorToListJava8Stream_thenReturnAList() { + + // Convert iterator to iterable + Iterable iterable = () -> iterator; + + // Extract List from stream + List actualList = StreamSupport + .stream(iterable.spliterator(), false) + .collect(Collectors.toList()); + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } + + @Test + public void givenAnIterator_whenConvertIteratorToImmutableListWithGuava_thenReturnAList() { + + // Convert Iterator to an Immutable list using Guava library in Java + List actualList = ImmutableList.copyOf(iterator); + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } + + @Test + public void givenAnIterator_whenConvertIteratorToMutableListWithGuava_thenReturnAList() { + + // Convert Iterator to a mutable list using Guava library in Java + List actualList = Lists.newArrayList(iterator); + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } + + @Test + public void givenAnIterator_whenConvertIteratorToMutableListWithApacheCommons_thenReturnAList() { + + // Convert Iterator to a mutable list using Apache Commons library in Java + List actualList = IteratorUtils.toList(iterator); + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } +} diff --git a/java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java new file mode 100644 index 0000000000..0283191b74 --- /dev/null +++ b/java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java @@ -0,0 +1,122 @@ +package com.baeldung.java.collections; + +import static org.hamcrest.Matchers.contains; +import static org.junit.Assert.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import org.apache.commons.collections4.IterableUtils; +import org.apache.commons.collections4.IteratorUtils; +import org.junit.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +public class IterableToCollectionUnitTest { + + Iterable iterable = Arrays.asList("john", "tom", "jane"); + Iterator iterator = iterable.iterator(); + + @Test + public void whenConvertIterableToListUsingJava_thenSuccess() { + List result = new ArrayList(); + for (String str : iterable) { + result.add(str); + } + + assertThat(result, contains("john", "tom", "jane")); + } + + @Test + public void whenConvertIterableToListUsingJava8_thenSuccess() { + List result = new ArrayList(); + iterable.forEach(result::add); + + assertThat(result, contains("john", "tom", "jane")); + } + + @Test + public void whenConvertIterableToListUsingJava8WithSpliterator_thenSuccess() { + List result = StreamSupport.stream(iterable.spliterator(), false) + .collect(Collectors.toList()); + + assertThat(result, contains("john", "tom", "jane")); + } + + @Test + public void whenConvertIterableToListUsingGuava_thenSuccess() { + List result = Lists.newArrayList(iterable); + + assertThat(result, contains("john", "tom", "jane")); + } + + @Test + public void whenConvertIterableToImmutableListUsingGuava_thenSuccess() { + List result = ImmutableList.copyOf(iterable); + + assertThat(result, contains("john", "tom", "jane")); + } + + @Test + public void whenConvertIterableToListUsingApacheCommons_thenSuccess() { + List result = IterableUtils.toList(iterable); + + assertThat(result, contains("john", "tom", "jane")); + } + + // ======================== Iterator + + @Test + public void whenConvertIteratorToListUsingJava_thenSuccess() { + List result = new ArrayList(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + + assertThat(result, contains("john", "tom", "jane")); + } + + @Test + public void whenConvertIteratorToListUsingJava8_thenSuccess() { + List result = new ArrayList(); + iterator.forEachRemaining(result::add); + + assertThat(result, contains("john", "tom", "jane")); + } + + @Test + public void whenConvertIteratorToListUsingJava8WithSpliterator_thenSuccess() { + List result = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false) + .collect(Collectors.toList()); + + assertThat(result, contains("john", "tom", "jane")); + } + + @Test + public void whenConvertIteratorToListUsingGuava_thenSuccess() { + List result = Lists.newArrayList(iterator); + + assertThat(result, contains("john", "tom", "jane")); + } + + @Test + public void whenConvertIteratorToImmutableListUsingGuava_thenSuccess() { + List result = ImmutableList.copyOf(iterator); + + assertThat(result, contains("john", "tom", "jane")); + } + + @Test + public void whenConvertIteratorToListUsingApacheCommons_thenSuccess() { + List result = IteratorUtils.toList(iterator); + + assertThat(result, contains("john", "tom", "jane")); + } +} diff --git a/java-collections-maps-2/pom.xml b/java-collections-maps-2/pom.xml index 5f27eaa2d8..e242a8655e 100644 --- a/java-collections-maps-2/pom.xml +++ b/java-collections-maps-2/pom.xml @@ -54,7 +54,6 @@ 3.0.2 8.1.0 1.2.0 - 3.8.1 3.11.1 diff --git a/java-collections-maps/pom.xml b/java-collections-maps/pom.xml index b5eba31437..83cc97a21e 100644 --- a/java-collections-maps/pom.xml +++ b/java-collections-maps/pom.xml @@ -44,7 +44,6 @@ - 3.5 4.1 4.01 1.7.0 diff --git a/java-dates-2/pom.xml b/java-dates-2/pom.xml index 9307a794b9..c1419514ef 100644 --- a/java-dates-2/pom.xml +++ b/java-dates-2/pom.xml @@ -20,6 +20,13 @@ joda-time ${joda-time.version} + + + + commons-validator + commons-validator + ${commons-validator.version} + @@ -56,6 +63,7 @@ 3.6.1 2.10 + 1.6 1.9 1.9 diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java new file mode 100644 index 0000000000..b774edab43 --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java @@ -0,0 +1,5 @@ +package com.baeldung.date.validation; + +public interface DateValidator { + boolean isValid(String dateStr); +} diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java new file mode 100644 index 0000000000..f7b2f48d2d --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java @@ -0,0 +1,11 @@ +package com.baeldung.date.validation; + +import org.apache.commons.validator.GenericValidator; + +public class DateValidatorUsingApacheValidator implements DateValidator { + + @Override + public boolean isValid(String dateStr) { + return GenericValidator.isDate(dateStr, "yyyy-MM-dd", true); + } +} diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java new file mode 100644 index 0000000000..eb0fbdb086 --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java @@ -0,0 +1,25 @@ +package com.baeldung.date.validation; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class DateValidatorUsingDateFormat implements DateValidator { + private String dateFormat; + + public DateValidatorUsingDateFormat(String dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public boolean isValid(String dateStr) { + DateFormat sdf = new SimpleDateFormat(this.dateFormat); + sdf.setLenient(false); + try { + sdf.parse(dateStr); + } catch (ParseException e) { + return false; + } + return true; + } +} diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java new file mode 100644 index 0000000000..0f68baf06e --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java @@ -0,0 +1,22 @@ +package com.baeldung.date.validation; + +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +public class DateValidatorUsingDateTimeFormatter implements DateValidator { + private DateTimeFormatter dateFormatter; + + public DateValidatorUsingDateTimeFormatter(DateTimeFormatter dateFormatter) { + this.dateFormatter = dateFormatter; + } + + @Override + public boolean isValid(String dateStr) { + try { + this.dateFormatter.parse(dateStr); + } catch (DateTimeParseException e) { + return false; + } + return true; + } +} diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java new file mode 100644 index 0000000000..f04c2e4185 --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java @@ -0,0 +1,23 @@ +package com.baeldung.date.validation; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +public class DateValidatorUsingLocalDate implements DateValidator { + private DateTimeFormatter dateFormatter; + + public DateValidatorUsingLocalDate(DateTimeFormatter dateFormatter) { + this.dateFormatter = dateFormatter; + } + + @Override + public boolean isValid(String dateStr) { + try { + LocalDate.parse(dateStr, this.dateFormatter); + } catch (DateTimeParseException e) { + return false; + } + return true; + } +} diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java new file mode 100644 index 0000000000..daa464722a --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.date.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.validator.GenericValidator; +import org.junit.Test; + +public class DateValidatorUsingApacheValidatorUnitTest { + + @Test + public void whenValidDatePassed_ThenTrue() { + assertTrue(GenericValidator.isDate("2019-02-28", "yyyy-MM-dd", true)); + } + + @Test + public void whenInvalidDatePassed_ThenFalse() { + assertFalse(GenericValidator.isDate("2019-02-29", "yyyy-MM-dd", true)); + } +} diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java new file mode 100644 index 0000000000..9b86b3381c --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.date.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class DateValidatorUsingDateFormatUnitTest { + + @Test + public void givenValidator_whenValidDatePassed_ThenTrue() { + DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); + + assertTrue(validator.isValid("02/28/2019")); + } + + @Test + public void givenValidator_whenInvalidDatePassed_ThenFalse() { + DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); + + assertFalse(validator.isValid("02/30/2019")); + } +} diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java new file mode 100644 index 0000000000..368b04f8e3 --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.date.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.time.format.DateTimeFormatter; +import java.time.format.ResolverStyle; +import java.util.Locale; + +import org.junit.Test; + +public class DateValidatorUsingDateTimeFormatterUnitTest { + + @Test + public void givenValidator_whenValidDatePassed_ThenTrue() { + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.US) + .withResolverStyle(ResolverStyle.STRICT); + DateValidator validator = new DateValidatorUsingDateTimeFormatter(dateFormatter); + + assertTrue(validator.isValid("2019-02-28")); + } + + @Test + public void givenValidator_whenInValidDatePassed_ThenFalse() { + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.US) + .withResolverStyle(ResolverStyle.STRICT); + DateValidator validator = new DateValidatorUsingDateTimeFormatter(dateFormatter); + + assertFalse(validator.isValid("2019-02-30")); + } + +} diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java new file mode 100644 index 0000000000..63296359db --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.date.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.time.format.DateTimeFormatter; + +import org.junit.Test; + +public class DateValidatorUsingLocalDateUnitTest { + + @Test + public void givenValidator_whenValidDatePassed_ThenTrue() { + DateTimeFormatter dateFormatter = DateTimeFormatter.BASIC_ISO_DATE; + DateValidator validator = new DateValidatorUsingLocalDate(dateFormatter); + + assertTrue(validator.isValid("20190228")); + } + + @Test + public void givenValidator_whenInValidDatePassed_ThenFalse() { + DateTimeFormatter dateFormatter = DateTimeFormatter.BASIC_ISO_DATE; + DateValidator validator = new DateValidatorUsingLocalDate(dateFormatter); + + assertFalse(validator.isValid("20190230")); + } +} diff --git a/java-dates/pom.xml b/java-dates/pom.xml index d4f690d894..3fddf3f0f8 100644 --- a/java-dates/pom.xml +++ b/java-dates/pom.xml @@ -74,8 +74,6 @@ - - 3.5 2.10 3.6.1 diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml index 9b8356714f..4d4e2ba3b3 100644 --- a/java-ee-8-security-api/pom.xml +++ b/java-ee-8-security-api/pom.xml @@ -72,8 +72,6 @@ 8.0 2.3 18.0.0.1 - - 3.2.2 diff --git a/java-math/pom.xml b/java-math/pom.xml index 159d053df3..f71577b707 100644 --- a/java-math/pom.xml +++ b/java-math/pom.xml @@ -42,7 +42,7 @@ com.github.dpaukov combinatoricslib3 - 3.3.0 + ${combinatoricslib3.version} @@ -63,6 +63,7 @@ 3.9.0 1.11 27.0.1-jre + 3.3.0 \ No newline at end of file diff --git a/java-numbers-2/.gitignore b/java-numbers-2/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/java-numbers-2/.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-numbers-2/pom.xml b/java-numbers-2/pom.xml new file mode 100644 index 0000000000..57f1154f53 --- /dev/null +++ b/java-numbers-2/pom.xml @@ -0,0 +1,135 @@ + + 4.0.0 + java-numbers-2 + 0.1.0-SNAPSHOT + java-numbers-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + log4j + log4j + ${log4j.version} + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.decimal4j + decimal4j + ${decimal4j.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-numbers-2 + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + 1.8 + 1.8 + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + 3.6.1 + 1.0.3 + 3.5 + + 3.6.1 + + 1.7.21 + 1.1.7 + + 2.21.0 + 3.0.0-M1 + 3.0.2 + + diff --git a/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java new file mode 100644 index 0000000000..2001f39359 --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.lossyconversion; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Test; + +public class ConversionTechniquesUnitTest { + + @Test + public void testPrimitiveConversion() { + + long longNum = 24; + short shortNum = (short) longNum; + assertEquals(24, shortNum); + + double doubleNum = 15.6; + int integerNum = (int) doubleNum; + assertEquals(15, integerNum); + + long largeLongNum = 32768; + short minShortNum = (short) largeLongNum; + assertEquals(-32768, minShortNum); + + long smallLongNum = -32769; + short maxShortNum = (short) smallLongNum; + assertEquals(32767, maxShortNum); + + long maxLong = Long.MAX_VALUE; + int minInt = (int) maxLong; + assertEquals(-1, minInt); + + long minLong = Long.MIN_VALUE; + int maxInt = (int) minLong; + assertEquals(0, maxInt); + } + + @Test + public void testWrapperToPrimitiveConversion() { + + Float floatNum = 17.564f; + long longNum = floatNum.longValue(); + assertEquals(17, longNum); + + Double doubleNum = 15.9999; + longNum = doubleNum.longValue(); + assertEquals(15, longNum); + } + + @Test + public void testWrapperToPrimitiveConversionUsingMathRound() { + + Double doubleNum = 15.9999; + long longNum = Math.round(doubleNum); + assertEquals(16, longNum); + } + + @Test + public void testWrapperConversion() { + + Double doubleNum = 10.3; + double dbl = doubleNum.doubleValue(); //unboxing + int intgr = (int) dbl; //downcasting + Integer intNum = Integer.valueOf(intgr); + assertEquals(Integer.valueOf(10), intNum); + } + +} diff --git a/java-numbers/pom.xml b/java-numbers/pom.xml index daed356f66..ac3ca2680f 100644 --- a/java-numbers/pom.xml +++ b/java-numbers/pom.xml @@ -121,7 +121,6 @@ 3.6.1 1.0.3 - 3.5 3.6.1 diff --git a/java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java b/java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java new file mode 100644 index 0000000000..02f815f5a7 --- /dev/null +++ b/java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java @@ -0,0 +1,36 @@ +package com.baeldung.random; + +import java.security.SecureRandom; +import java.security.NoSuchAlgorithmException; +import java.util.stream.IntStream; +import java.util.stream.LongStream; +import java.util.stream.DoubleStream; + +public interface SecureRandomDemo { + + public static void generateSecureRandomValues() { + SecureRandom sr = new SecureRandom(); + + int randomInt = sr.nextInt(); + long randomLong = sr.nextLong(); + float randomFloat = sr.nextFloat(); + double randomDouble = sr.nextDouble(); + boolean randomBoolean = sr.nextBoolean(); + + IntStream randomIntStream = sr.ints(); + LongStream randomLongStream = sr.longs(); + DoubleStream randomDoubleStream = sr.doubles(); + + byte[] values = new byte[124]; + sr.nextBytes(values); + } + + public static SecureRandom getSecureRandomForAlgorithm(String algorithm) throws NoSuchAlgorithmException { + if (algorithm == null || algorithm.isEmpty()) { + return new SecureRandom(); + } + + return SecureRandom.getInstance(algorithm); + } + +} diff --git a/java-streams-2/README.md b/java-streams-2/README.md index 83ef97686f..851d3d71e2 100644 --- a/java-streams-2/README.md +++ b/java-streams-2/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) - +- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach) +- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert) diff --git a/java-streams-2/pom.xml b/java-streams-2/pom.xml index 3e08e2f432..f7a0379ac5 100644 --- a/java-streams-2/pom.xml +++ b/java-streams-2/pom.xml @@ -4,7 +4,7 @@ com.baeldung.javastreams2 javastreams2 1.0 - Stream Reduce + javastreams2 jar @@ -42,8 +42,8 @@ UTF-8 - 1.8 - 1.8 + 1.9 + 1.9 3.11.1 \ No newline at end of file diff --git a/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomForEach.java b/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomForEach.java new file mode 100644 index 0000000000..1f8866b16c --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomForEach.java @@ -0,0 +1,32 @@ +package com.baeldung.breakforeach; + +import java.util.Spliterator; +import java.util.function.BiConsumer; +import java.util.stream.Stream; + +public class CustomForEach { + + public static class Breaker { + private boolean shouldBreak = false; + + public void stop() { + shouldBreak = true; + } + + boolean get() { + return shouldBreak; + } + } + + public static void forEach(Stream stream, BiConsumer consumer) { + Spliterator spliterator = stream.spliterator(); + boolean hadNext = true; + Breaker breaker = new Breaker(); + + while (hadNext && !breaker.get()) { + hadNext = spliterator.tryAdvance(elem -> { + consumer.accept(elem, breaker); + }); + } + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomSpliterator.java b/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomSpliterator.java new file mode 100644 index 0000000000..cfe4bedac3 --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomSpliterator.java @@ -0,0 +1,31 @@ +package com.baeldung.breakforeach; + +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Consumer; +import java.util.function.Predicate; + +public class CustomSpliterator extends Spliterators.AbstractSpliterator { + + private Spliterator splitr; + private Predicate predicate; + private boolean isMatched = true; + + public CustomSpliterator(Spliterator splitr, Predicate predicate) { + super(splitr.estimateSize(), 0); + this.splitr = splitr; + this.predicate = predicate; + } + + @Override + public boolean tryAdvance(Consumer consumer) { + boolean hadNext = splitr.tryAdvance(elem -> { + if (predicate.test(elem) && isMatched) { + consumer.accept(elem); + } else { + isMatched = false; + } + }); + return hadNext && isMatched; + } +} \ No newline at end of file diff --git a/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomTakeWhile.java b/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomTakeWhile.java new file mode 100644 index 0000000000..05574f9ae6 --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomTakeWhile.java @@ -0,0 +1,14 @@ +package com.baeldung.breakforeach; + +import java.util.function.Predicate; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +public class CustomTakeWhile { + + public static Stream takeWhile(Stream stream, Predicate predicate) { + CustomSpliterator customSpliterator = new CustomSpliterator<>(stream.spliterator(), predicate); + return StreamSupport.stream(customSpliterator, false); + } + +} diff --git a/java-streams-2/src/main/java/com/baeldung/breakforeach/TakeWhileExample.java b/java-streams-2/src/main/java/com/baeldung/breakforeach/TakeWhileExample.java new file mode 100644 index 0000000000..1838ae5fb7 --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/breakforeach/TakeWhileExample.java @@ -0,0 +1,26 @@ +package com.baeldung.breakforeach; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class TakeWhileExample { + + public static void takeWhileJava9() { + Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck") + .takeWhile(n -> n.length() % 2 != 0) + .forEach(System.out::println); // cat, dog + } + + public static void plainForLoopWithBreak() { + List list = asList("cat", "dog", "elephant", "fox", "rabbit", "duck"); + for (int i = 0; i < list.size(); i++) { + String item = list.get(i); + if (item.length() % 2 == 0) { + break; + } + System.out.println(item); + } + } +} \ No newline at end of file diff --git a/java-streams-2/src/test/java/com/baeldung/breakforeach/BreakFromStreamForEachUnitTest.java b/java-streams-2/src/test/java/com/baeldung/breakforeach/BreakFromStreamForEachUnitTest.java new file mode 100644 index 0000000000..23653c0a39 --- /dev/null +++ b/java-streams-2/src/test/java/com/baeldung/breakforeach/BreakFromStreamForEachUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.breakforeach; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static org.junit.Assert.assertEquals; + +public class BreakFromStreamForEachUnitTest { + + @Test + public void whenCustomTakeWhileIsCalled_ThenCorrectItemsAreReturned() { + Stream initialStream = Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck"); + + List result = CustomTakeWhile.takeWhile(initialStream, x -> x.length() % 2 != 0) + .collect(Collectors.toList()); + + assertEquals(asList("cat", "dog"), result); + } + + @Test + public void whenCustomForEachIsCalled_ThenCorrectItemsAreReturned() { + Stream initialStream = Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck"); + List result = new ArrayList<>(); + + CustomForEach.forEach(initialStream, (elem, breaker) -> { + if (elem.length() % 2 == 0) { + breaker.stop(); + } else { + result.add(elem); + } + }); + + assertEquals(asList("cat", "dog"), result); + } + +} diff --git a/java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java b/java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java new file mode 100644 index 0000000000..3f2fd1641e --- /dev/null +++ b/java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.convert.intstreams; + +import org.junit.Test; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import static org.assertj.core.api.Assertions.assertThat; + +public class IntStreamsConversionsUnitTest { + + @Test + public void intStreamToArray() { + int[] first50EvenNumbers = IntStream.iterate(0, i -> i + 2) + .limit(50) + .toArray(); + + assertThat(first50EvenNumbers).hasSize(50); + assertThat(first50EvenNumbers[2]).isEqualTo(4); + } + + @Test + public void intStreamToList() { + List first50IntegerNumbers = IntStream.range(0, 50) + .boxed() + .collect(Collectors.toList()); + + assertThat(first50IntegerNumbers).hasSize(50); + assertThat(first50IntegerNumbers.get(2)).isEqualTo(2); + } + + @Test + public void intStreamToString() { + String first3numbers = IntStream.of(0, 1, 2) + .mapToObj(String::valueOf) + .collect(Collectors.joining(", ", "[", "]")); + + assertThat(first3numbers).isEqualTo("[0, 1, 2]"); + } +} diff --git a/java-streams/pom.xml b/java-streams/pom.xml index b0c56ecdf9..bd0123e01d 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -106,7 +106,6 @@ - 3.5 0.9.0 1.15 0.6.5 diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD index 85832fde37..c6d4f0222a 100644 --- a/java-strings-2/README.MD +++ b/java-strings-2/README.MD @@ -3,3 +3,5 @@ - [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) +- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) +- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) diff --git a/java-strings-2/pom.xml b/java-strings-2/pom.xml index 9c27429139..7342953d15 100755 --- a/java-strings-2/pom.xml +++ b/java-strings-2/pom.xml @@ -57,6 +57,26 @@ commons-text ${commons-text.version} + + javax.validation + validation-api + 2.0.0.Final + + + org.hibernate.validator + hibernate-validator + 6.0.2.Final + + + javax.el + javax.el-api + 3.0.0 + + + org.glassfish.web + javax.el + 2.2.6 + @@ -86,7 +106,7 @@ 3.8.1 61.1 - 27.0.1-jre + 28.0-jre 1.4 diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java new file mode 100644 index 0000000000..6d3234a4ec --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java @@ -0,0 +1,8 @@ +package com.baeldung.string.emptystrings; + +class EmptyStringCheck { + + boolean isEmptyString(String string) { + return string == null || string.isEmpty(); + } +} diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java new file mode 100644 index 0000000000..096b83acea --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java @@ -0,0 +1,8 @@ +package com.baeldung.string.emptystrings; + +class Java5EmptyStringCheck { + + boolean isEmptyString(String string) { + return string == null || string.length() == 0; + } +} diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java new file mode 100644 index 0000000000..26e281c9b7 --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java @@ -0,0 +1,8 @@ +package com.baeldung.string.emptystrings; + +class PlainJavaBlankStringCheck { + + boolean isBlankString(String string) { + return string == null || string.trim().isEmpty(); + } +} diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java new file mode 100644 index 0000000000..8c484efb43 --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java @@ -0,0 +1,14 @@ +package com.baeldung.string.emptystrings; + +import javax.validation.constraints.Pattern; + +class SomeClassWithValidations { + + @Pattern(regexp = "\\A(?!\\s*\\Z).+") + private String someString; + + SomeClassWithValidations setSomeString(String someString) { + this.someString = someString; + return this; + } +} diff --git a/java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java b/java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java new file mode 100644 index 0000000000..1bde2dcb63 --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java @@ -0,0 +1,67 @@ +package com.baeldung.string.multiline; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Paths; + +import com.google.common.base.Joiner; +import com.google.common.collect.ImmutableList; + +public class MultiLineString { + + String newLine = System.getProperty("line.separator"); + + public String stringConcatenation() { + return "Get busy living" + .concat(newLine) + .concat("or") + .concat(newLine) + .concat("get busy dying.") + .concat(newLine) + .concat("--Stephen King"); + } + + public String stringJoin() { + return String.join(newLine, + "Get busy living", + "or", + "get busy dying.", + "--Stephen King"); + } + + public String stringBuilder() { + return new StringBuilder() + .append("Get busy living") + .append(newLine) + .append("or") + .append(newLine) + .append("get busy dying.") + .append(newLine) + .append("--Stephen King") + .toString(); + } + + public String stringWriter() { + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + printWriter.println("Get busy living"); + printWriter.println("or"); + printWriter.println("get busy dying."); + printWriter.println("--Stephen King"); + return stringWriter.toString(); + } + + public String guavaJoiner() { + return Joiner.on(newLine).join(ImmutableList.of("Get busy living", + "or", + "get busy dying.", + "--Stephen King")); + } + + public String loadFromFile() throws IOException { + return new String(Files.readAllBytes(Paths.get("src/main/resources/stephenking.txt"))); + } + +} diff --git a/java-strings-2/src/main/java/com/baeldung/string/repetition/SubstringRepetition.java b/java-strings-2/src/main/java/com/baeldung/string/repetition/SubstringRepetition.java new file mode 100644 index 0000000000..466ce9146b --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/repetition/SubstringRepetition.java @@ -0,0 +1,29 @@ +package com.baeldung.string.repetition; + +public class SubstringRepetition { + + public static boolean containsOnlySubstrings(String string) { + + if (string.length() < 2) { + return false; + } + + StringBuilder substr = new StringBuilder(); + for (int i = 0; i < string.length() / 2; i++) { + substr.append(string.charAt(i)); + + String clearedFromSubstrings = string.replaceAll(substr.toString(), ""); + + if (clearedFromSubstrings.length() == 0) { + return true; + } + } + + return false; + } + + public static boolean containsOnlySubstringsEfficient(String string) { + + return ((string + string).indexOf(string, 1) != string.length()); + } +} diff --git a/java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java b/java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java new file mode 100644 index 0000000000..1a58d09598 --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java @@ -0,0 +1,56 @@ +package com.baeldung.string.reverse; + +import org.apache.commons.lang3.StringUtils; + +public class ReverseStringExamples { + + public static String reverse(String input) { + if (input == null) { + return null; + } + + String output = ""; + + for (int i = input.length() - 1; i >= 0; i--) { + output = output + input.charAt(i); + } + + return output; + } + + public static String reverseUsingStringBuilder(String input) { + if (input == null) { + return null; + } + + StringBuilder output = new StringBuilder(input).reverse(); + + return output.toString(); + } + + public static String reverseUsingApacheCommons(String input) { + return StringUtils.reverse(input); + } + + public static String reverseTheOrderOfWords(String sentence) { + if (sentence == null) { + return null; + } + + StringBuilder output = new StringBuilder(); + String[] words = sentence.split(" "); + + for (int i = words.length - 1; i >= 0; i--) { + output.append(words[i]); + output.append(" "); + } + + return output.toString() + .trim(); + } + + public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) { + return StringUtils.reverseDelimited(sentence, ' '); + } + +} diff --git a/java-strings-2/src/main/resources/stephenking.txt b/java-strings-2/src/main/resources/stephenking.txt new file mode 100644 index 0000000000..f31b4a28bd --- /dev/null +++ b/java-strings-2/src/main/resources/stephenking.txt @@ -0,0 +1,4 @@ +Get busy living +or +get busy dying. +--Stephen King \ No newline at end of file diff --git a/java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java new file mode 100644 index 0000000000..96b1d681dd --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java @@ -0,0 +1,142 @@ +package com.baeldung.string.emptystrings; + +import static org.hamcrest.Matchers.iterableWithSize; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import com.google.common.base.Strings; + +public class EmptyStringsUnitTest { + + private String emptyString = ""; + private String blankString = " \n\t "; + private String nonEmptyString = " someString "; + + /* + * EmptyStringCheck + */ + @Test + public void givenSomeEmptyString_thenEmptyStringCheckIsEmptyStringReturnsTrue() { + assertTrue(new EmptyStringCheck().isEmptyString(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenEmptyStringCheckIsEmptyStringReturnsFalse() { + assertFalse(new EmptyStringCheck().isEmptyString(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenEmptyStringCheckIsEmptyStringReturnsFalse() { + assertFalse(new EmptyStringCheck().isEmptyString(blankString)); + } + + /* + * Java5EmptyStringCheck + */ + @Test + public void givenSomeEmptyString_thenJava5EmptyStringCheckIsEmptyStringReturnsTrue() { + assertTrue(new Java5EmptyStringCheck().isEmptyString(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenJava5EmptyStringCheckIsEmptyStringReturnsFalse() { + assertFalse(new Java5EmptyStringCheck().isEmptyString(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenJava5EmptyStringCheckIsEmptyStringReturnsFalse() { + assertFalse(new Java5EmptyStringCheck().isEmptyString(blankString)); + } + + /* + * PlainJavaBlankStringCheck + */ + @Test + public void givenSomeEmptyString_thenPlainJavaBlankStringCheckIsBlankStringReturnsTrue() { + assertTrue(new PlainJavaBlankStringCheck().isBlankString(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenPlainJavaBlankStringCheckIsBlankStringReturnsFalse() { + assertFalse(new PlainJavaBlankStringCheck().isBlankString(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenPlainJavaBlankStringCheckIsBlankStringReturnsTrue() { + assertTrue(new PlainJavaBlankStringCheck().isBlankString(blankString)); + } + + /* + * Apache Commons Lang StringUtils + */ + @Test + public void givenSomeEmptyString_thenStringUtilsIsBlankReturnsTrue() { + assertTrue(StringUtils.isBlank(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenStringUtilsIsBlankReturnsFalse() { + assertFalse(StringUtils.isBlank(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenStringUtilsIsBlankReturnsTrue() { + assertTrue(StringUtils.isBlank(blankString)); + } + + /* + * Google Guava Strings + */ + @Test + public void givenSomeEmptyString_thenStringsIsNullOrEmptyStringReturnsTrue() { + assertTrue(Strings.isNullOrEmpty(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenStringsIsNullOrEmptyStringReturnsFalse() { + assertFalse(Strings.isNullOrEmpty(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenStringsIsNullOrEmptyStringReturnsFalse() { + assertFalse(Strings.isNullOrEmpty(blankString)); + } + + /* + * Bean Validation + */ + private ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + private Validator validator = factory.getValidator(); + + @Test + public void givenSomeEmptyString_thenBeanValidationReturnsViolations() { + SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(emptyString); + Set> violations = validator.validate(someClassWithValidations); + assertThat(violations, iterableWithSize(1)); + } + + @Test + public void givenSomeNonEmptyString_thenBeanValidationValidatesWithoutViolations() { + SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(nonEmptyString); + Set> violations = validator.validate(someClassWithValidations); + assertThat(violations, iterableWithSize(0)); + } + + @Test + public void givenSomeBlankString_thenBeanValidationReturnsViolations() { + SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(blankString); + Set> violations = validator.validate(someClassWithValidations); + assertThat(violations, iterableWithSize(1)); + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java new file mode 100644 index 0000000000..3ebee9b5d1 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.string.multiline; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import com.baeldung.string.multiline.MultiLineString; + +public class MultiLineStringUnitTest { + + + @Test + public void whenCompareMultiLineStrings_thenTheyAreAllTheSame() throws IOException { + MultiLineString ms = new MultiLineString(); + assertEquals(ms.stringConcatenation(), ms.stringJoin()); + assertEquals(ms.stringJoin(), ms.stringBuilder()); + assertEquals(ms.stringBuilder(), ms.guavaJoiner()); + assertEquals(ms.guavaJoiner(), ms.loadFromFile()); + } + +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/repetition/SubstringRepetitionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/repetition/SubstringRepetitionUnitTest.java new file mode 100644 index 0000000000..f382a24a7f --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/repetition/SubstringRepetitionUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.string.repetition; + +import static com.baeldung.string.repetition.SubstringRepetition.*; +import static org.junit.Assert.*; + +import org.junit.Test; + +public class SubstringRepetitionUnitTest { + + private String validString = "aa"; + private String validStringTwo = "ababab"; + private String validStringThree = "baeldungbaeldung"; + + private String invalidString = "aca"; + private String invalidStringTwo = "ababa"; + private String invalidStringThree = "baeldungnonrepeatedbaeldung"; + + @Test + public void givenValidStrings_whenCheckIfContainsOnlySubstrings_thenReturnsTrue() { + assertTrue(containsOnlySubstrings(validString)); + assertTrue(containsOnlySubstrings(validStringTwo)); + assertTrue(containsOnlySubstrings(validStringThree)); + } + + @Test + public void givenInvalidStrings_whenCheckIfContainsOnlySubstrings_thenReturnsFalse() { + assertFalse(containsOnlySubstrings(invalidString)); + assertFalse(containsOnlySubstrings(invalidStringTwo)); + assertFalse(containsOnlySubstrings(invalidStringThree)); + } + + @Test + public void givenValidStrings_whenCheckEfficientlyIfContainsOnlySubstrings_thenReturnsTrue() { + assertTrue(containsOnlySubstringsEfficient(validString)); + assertTrue(containsOnlySubstringsEfficient(validStringTwo)); + assertTrue(containsOnlySubstringsEfficient(validStringThree)); + } + + @Test + public void givenInvalidStrings_whenCheckEfficientlyIfContainsOnlySubstrings_thenReturnsFalse() { + assertFalse(containsOnlySubstringsEfficient(invalidString)); + assertFalse(containsOnlySubstringsEfficient(invalidStringTwo)); + assertFalse(containsOnlySubstringsEfficient(invalidStringThree)); + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/reverse/ReverseStringExamplesUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/reverse/ReverseStringExamplesUnitTest.java new file mode 100644 index 0000000000..020ead02db --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/reverse/ReverseStringExamplesUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.string.reverse; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ReverseStringExamplesUnitTest { + + private static final String STRING_INPUT = "cat"; + private static final String STRING_INPUT_REVERSED = "tac"; + private static final String SENTENCE = "The quick brown fox jumps over the lazy dog"; + private static final String REVERSED_WORDS_SENTENCE = "dog lazy the over jumps fox brown quick The"; + + @Test + public void whenReverseIsCalled_ThenCorrectStringIsReturned() { + String reversed = ReverseStringExamples.reverse(STRING_INPUT); + String reversedNull = ReverseStringExamples.reverse(null); + String reversedEmpty = ReverseStringExamples.reverse(StringUtils.EMPTY); + + assertEquals(STRING_INPUT_REVERSED, reversed); + assertEquals(null, reversedNull); + assertEquals(StringUtils.EMPTY, reversedEmpty); + } + + @Test + public void whenReverseUsingStringBuilderIsCalled_ThenCorrectStringIsReturned() throws Exception { + String reversed = ReverseStringExamples.reverseUsingStringBuilder(STRING_INPUT); + String reversedNull = ReverseStringExamples.reverseUsingStringBuilder(null); + String reversedEmpty = ReverseStringExamples.reverseUsingStringBuilder(StringUtils.EMPTY); + + assertEquals(STRING_INPUT_REVERSED, reversed); + assertEquals(null, reversedNull); + assertEquals(StringUtils.EMPTY, reversedEmpty); + } + + @Test + public void whenReverseUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned() throws Exception { + String reversed = ReverseStringExamples.reverseUsingApacheCommons(STRING_INPUT); + String reversedNull = ReverseStringExamples.reverseUsingApacheCommons(null); + String reversedEmpty = ReverseStringExamples.reverseUsingApacheCommons(StringUtils.EMPTY); + + assertEquals(STRING_INPUT_REVERSED, reversed); + assertEquals(null, reversedNull); + assertEquals(StringUtils.EMPTY, reversedEmpty); + } + + @Test + public void whenReverseTheOrderOfWordsIsCalled_ThenCorrectStringIsReturned() { + String reversed = ReverseStringExamples.reverseTheOrderOfWords(SENTENCE); + String reversedNull = ReverseStringExamples.reverseTheOrderOfWords(null); + String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWords(StringUtils.EMPTY); + + assertEquals(REVERSED_WORDS_SENTENCE, reversed); + assertEquals(null, reversedNull); + assertEquals(StringUtils.EMPTY, reversedEmpty); + } + + @Test + public void whenReverseTheOrderOfWordsUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned() { + String reversed = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(SENTENCE); + String reversedNull = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(null); + String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(StringUtils.EMPTY); + + assertEquals(REVERSED_WORDS_SENTENCE, reversed); + assertEquals(null, reversedNull); + assertEquals(StringUtils.EMPTY, reversedEmpty); + } + +} diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml index e3d8a430d9..096b1bb229 100644 --- a/javax-servlets/pom.xml +++ b/javax-servlets/pom.xml @@ -88,7 +88,6 @@ 3.9.1 2.21.0 1.3.3 - 2.6 4.0.1 diff --git a/jaxb/pom.xml b/jaxb/pom.xml index 3ed6d9b21a..d575f12c7b 100644 --- a/jaxb/pom.xml +++ b/jaxb/pom.xml @@ -130,8 +130,6 @@ 2.3 3.0.2 - 2.5 - 3.5 1.0.0 1.1 diff --git a/jee-7/README.md b/jee-7/README.md index a783e7860e..c57863651d 100644 --- a/jee-7/README.md +++ b/jee-7/README.md @@ -6,3 +6,4 @@ - [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) - [Java EE 7 Batch Processing](https://www.baeldung.com/java-ee-7-batch-processing) +- [The Difference Between CDI and EJB Singleton](https://www.baeldung.com/jee-cdi-vs-ejb-singleton) diff --git a/jee-7/pom.xml b/jee-7/pom.xml index d389b57cd5..9432801fd9 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -519,11 +519,9 @@ 1.13 2.25 1.0.0.Final - 2.6 4.2.3.RELEASE 2.21.0 1.1.2 - 2.4 2.2.14 4.5 2.0.1.Final diff --git a/jee-kotlin/README.md b/jee-kotlin/README.md new file mode 100644 index 0000000000..7d843af9ea --- /dev/null +++ b/jee-kotlin/README.md @@ -0,0 +1 @@ +### Relevant Articles: diff --git a/jee-kotlin/pom.xml b/jee-kotlin/pom.xml new file mode 100644 index 0000000000..17163ba23c --- /dev/null +++ b/jee-kotlin/pom.xml @@ -0,0 +1,286 @@ + + + + 4.0.0 + jee-kotlin + jee-kotlin + war + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-test-junit + ${kotlin.version} + test + + + junit + junit + ${junit.version} + test + + + javax + javaee-api + ${javaee-api.version} + jar + provided + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + test + + + org.jboss.arquillian.junit + arquillian-junit-container + ${arquillian_core.version} + test + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-depchain + ${shrinkwrap.version} + pom + test + + + org.jboss.arquillian.extension + arquillian-rest-client-impl-jersey + ${arquillian-rest-client.version} + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + + + src/main/kotlin + src/test/kotlin + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + webapp + kotlin + + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + none + + + default-testCompile + none + + + compile + compile + + compile + + + + testCompile + test-compile + + testCompile + + + + + + + + + + + org.jboss.arquillian + arquillian-bom + ${arquillian_core.version} + import + pom + + + org.jboss.arquillian.extension + arquillian-drone-bom + ${arquillian-drone-bom.version} + pom + import + + + + + + + wildfly-managed-arquillian + + true + + + + org.wildfly + wildfly-arquillian-container-embedded + ${wildfly.version} + + + org.wildfly + wildfly-embedded + ${wildfly.version} + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + ${maven-dependency-plugin.version} + + + unpack + process-test-classes + + unpack + + + + + org.wildfly + wildfly-dist + ${wildfly.version} + zip + false + target + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + always + + org.jboss.logmanager.LogManager + ${project.basedir}/target/wildfly-${wildfly.version} + ${project.basedir}/target/wildfly-${wildfly.version}/modules + + false + + + + + + + wildfly-remote-arquillian + + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + test + + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + test + + + org.jboss.resteasy + resteasy-json-p-provider + ${resteasy.version} + test + + + org.wildfly.arquillian + wildfly-arquillian-container-remote + 2.2.0.Final + test + + + + + + + UTF-8 + false + 8.0 + + + 1.3.41 + official + true + + + 8.2.1.Final + 2.21.0 + 3.1.1 + + 1.4.1.Final + 2.0.1.Final + 1.0.0.Alpha4 + + 3.8.0.Final + 3.1.3 + + + diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt new file mode 100644 index 0000000000..07f54a39d1 --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt @@ -0,0 +1,22 @@ +package com.baeldung.jeekotlin.entity + +import com.fasterxml.jackson.annotation.JsonProperty +import javax.persistence.* + +@Entity +data class Student constructor ( + + @SequenceGenerator(name = "student_id_seq", sequenceName = "student_id_seq", allocationSize = 1) + @GeneratedValue(generator = "student_id_seq", strategy = GenerationType.SEQUENCE) + @Id + var id: Long?, + + var firstName: String, + + var lastName: String + +) { + constructor() : this(null, "", "") + + constructor(firstName: String, lastName: String) : this(null, firstName, lastName) +} diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt new file mode 100644 index 0000000000..12511ed320 --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt @@ -0,0 +1,9 @@ +package com.baeldung.jeekotlin.rest + +import javax.ws.rs.ApplicationPath +import javax.ws.rs.core.Application + +@ApplicationPath("/") +class ApplicationConfig : Application() { + override fun getClasses() = setOf(StudentResource::class.java) +} diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt new file mode 100644 index 0000000000..91fa3ff62b --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt @@ -0,0 +1,42 @@ +package com.baeldung.jeekotlin.rest + +import com.baeldung.jeekotlin.entity.Student +import com.baeldung.jeekotlin.service.StudentService +import javax.inject.Inject +import javax.ws.rs.* +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response + +@Path("/student") +open class StudentResource { + + @Inject + private lateinit var service: StudentService + + @POST + open fun create(student: Student): Response { + service.create(student) + return Response.ok().build() + } + + @GET + @Path("/{id}") + open fun read(@PathParam("id") id: Long): Response { + val student = service.read(id) + return Response.ok(student, MediaType.APPLICATION_JSON_TYPE).build() + } + + @PUT + open fun update(student: Student): Response { + service.update(student) + return Response.ok(student, MediaType.APPLICATION_JSON_TYPE).build() + } + + @DELETE + @Path("/{id}") + open fun delete(@PathParam("id") id: Long): Response { + service.delete(id) + return Response.noContent().build() + } + +} \ No newline at end of file diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt new file mode 100644 index 0000000000..3977a45e96 --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt @@ -0,0 +1,21 @@ +package com.baeldung.jeekotlin.service + +import com.baeldung.jeekotlin.entity.Student +import javax.ejb.Stateless +import javax.persistence.EntityManager +import javax.persistence.PersistenceContext + +@Stateless +open class StudentService { + + @PersistenceContext + private lateinit var entityManager: EntityManager + + open fun create(student: Student) = entityManager.persist(student) + + open fun read(id: Long): Student? = entityManager.find(Student::class.java, id) + + open fun update(student: Student) = entityManager.merge(student) + + open fun delete(id: Long) = entityManager.remove(read(id)) +} \ No newline at end of file diff --git a/jee-kotlin/src/main/resources/META-INF/persistence.xml b/jee-kotlin/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..daac86868b --- /dev/null +++ b/jee-kotlin/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + + java:jboss/datasources/ExampleDS + + com.enpy.entity.Student + + + + + + + + diff --git a/jee-kotlin/src/main/webapp/WEB-INF/beans.xml b/jee-kotlin/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..ae0f4bf2ee --- /dev/null +++ b/jee-kotlin/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,8 @@ + + + \ No newline at end of file diff --git a/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java new file mode 100644 index 0000000000..b91b47cb1f --- /dev/null +++ b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java @@ -0,0 +1,108 @@ +package com.baeldung.jeekotlin; + +import com.baeldung.jeekotlin.entity.Student; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.container.test.api.RunAsClient; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Filters; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.junit.Test; +import org.junit.runner.RunWith; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.URISyntaxException; +import java.net.URL; + +import static org.junit.Assert.assertEquals; + +@RunWith(Arquillian.class) +public class StudentResourceIntegrationTest { + + @Deployment + public static WebArchive createDeployment() { + JavaArchive[] kotlinRuntime = Maven.configureResolver() + .workOffline() + .withMavenCentralRepo(true) + .withClassPathResolution(true) + .loadPomFromFile("pom.xml") + .resolve("org.jetbrains.kotlin:kotlin-stdlib") + .withTransitivity() + .as(JavaArchive.class); + + return ShrinkWrap.create(WebArchive.class, "kotlin.war") + .addPackages(true, Filters.exclude(".*Test*"), + "com.baeldung.jeekotlin" + ) + .addAsLibraries(kotlinRuntime) + .addAsResource("META-INF/persistence.xml") + .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); + } + + @Test + @RunAsClient + public void when_post__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + String student = new ObjectMapper().writeValueAsString(new Student("firstName", "lastName")); + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student") + .request(MediaType.APPLICATION_JSON) + .post(Entity.json(student)); + + assertEquals(200, response.getStatus()); + } + + @Test + @RunAsClient + public void when_get__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student/1") + .request(MediaType.APPLICATION_JSON) + .get(); + + assertEquals(200, response.getStatus()); + } + + @Test + @RunAsClient + public void when_put__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + Student student = new Student("firstName", "lastName"); + student.setId(1L); + String studentJson = new ObjectMapper().writeValueAsString(student); + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student") + .request(MediaType.APPLICATION_JSON) + .put(Entity.json(studentJson)); + + assertEquals(200, response.getStatus()); + } + + @Test + @RunAsClient + public void when_delete__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student/1") + .request() + .delete(); + + assertEquals(204, response.getStatus()); + } + +} \ No newline at end of file diff --git a/jee-kotlin/src/test/resources/arquillian.xml b/jee-kotlin/src/test/resources/arquillian.xml new file mode 100644 index 0000000000..5e6d7c54e8 --- /dev/null +++ b/jee-kotlin/src/test/resources/arquillian.xml @@ -0,0 +1,22 @@ + + + + + target/wildfly-8.2.1.Final + standalone.xml + true + 9990 + + + + + + 127.0.0.1 + 9990 + admin + pass + true + + + + \ No newline at end of file diff --git a/jersey/README.md b/jersey/README.md index 1dd871b3e8..126dc542ba 100644 --- a/jersey/README.md +++ b/jersey/README.md @@ -3,3 +3,4 @@ - [Bean Validation in Jersey](https://www.baeldung.com/jersey-bean-validation) - [Set a Response Body in JAX-RS](https://www.baeldung.com/jax-rs-response) - [Exploring the Jersey Test Framework](https://www.baeldung.com/jersey-test) +- [Explore Jersey Request Parameters](https://www.baeldung.com/jersey-request-parameters) diff --git a/jersey/pom.xml b/jersey/pom.xml index a3adb4cf5a..708b36ce41 100644 --- a/jersey/pom.xml +++ b/jersey/pom.xml @@ -80,7 +80,6 @@ 2.26 - 3.2.0 diff --git a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java index 376c8c1e75..f7bb0df1ed 100644 --- a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java +++ b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java @@ -26,6 +26,7 @@ public class FruitResourceIntegrationTest extends JerseyTest { protected Application configure() { enable(TestProperties.LOG_TRAFFIC); enable(TestProperties.DUMP_ENTITY); + forceSet(TestProperties.CONTAINER_PORT, "0"); ViewApplicationConfig config = new ViewApplicationConfig(); config.register(FruitExceptionMapper.class); diff --git a/jhipster/README.md b/jhipster/README.md deleted file mode 100644 index 289bfac754..0000000000 --- a/jhipster/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Relevant articles: - -- [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices) -- [Intro to JHipster](http://www.baeldung.com/jhipster) -- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service) -- [Creating New Roles and Authorities in JHipster](https://www.baeldung.com/jhipster-new-roles) diff --git a/jsf/pom.xml b/jsf/pom.xml index 19f1265250..31362a8809 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -99,9 +99,6 @@ 2.2.14 3.0.0 - - 2.6 - 6.2 diff --git a/jws/pom.xml b/jws/pom.xml index 2c89b687f8..5c19c887d3 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -34,6 +34,7 @@ + ${project.artifactId} org.apache.maven.plugins @@ -78,12 +79,10 @@ - ${project.artifactId} 3.0.2 - 3.0.0 1.6.0 1.6.0 diff --git a/kotlin-libraries-2/README.md b/kotlin-libraries-2/README.md index fdb7c2830d..0b9f238d51 100644 --- a/kotlin-libraries-2/README.md +++ b/kotlin-libraries-2/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Jackson Support for Kotlin](https://www.baeldung.com/jackson-kotlin) +- [Introduction to RxKotlin](https://www.baeldung.com/rxkotlin) diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index b75c77f358..e252329426 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -94,7 +94,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} @@ -184,7 +184,6 @@ 1.1.1 5.2.0 3.10.0 - 1.4.197 0.10.4 1.9.3 diff --git a/kotlin-quasar/README.md b/kotlin-quasar/README.md new file mode 100644 index 0000000000..b3b84e0446 --- /dev/null +++ b/kotlin-quasar/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Introduction to Quasar in Kotlin](https://www.baeldung.com/kotlin-quasar) diff --git a/kotlin-quasar/pom.xml b/kotlin-quasar/pom.xml index 44feabd183..231b02b0c7 100644 --- a/kotlin-quasar/pom.xml +++ b/kotlin-quasar/pom.xml @@ -8,6 +8,12 @@ kotlin-quasar jar + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + org.jetbrains.kotlin @@ -45,6 +51,27 @@ junit 4.12 + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + @@ -116,5 +143,7 @@ 0.8.0 1.3.31 + 1.7.21 + 1.1.7 diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt new file mode 100644 index 0000000000..b4d0288a64 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt @@ -0,0 +1,157 @@ +package com.baeldung.quasar + +import co.paralleluniverse.actors.Actor +import co.paralleluniverse.actors.ActorRef +import co.paralleluniverse.actors.behaviors.* +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.strands.SuspendableCallable +import org.junit.Test +import org.slf4j.LoggerFactory +import java.lang.Exception + +class ActorsBehaviorTest { + companion object { + private val LOG = LoggerFactory.getLogger(ActorsBehaviorTest::class.java) + } + + @Test + fun requestReplyHelper() { + data class TestMessage(val input: Int) : RequestMessage() + + val actor = object : Actor("requestReplyActor", null) { + @Suspendable + override fun doRun(): Void? { + while (true) { + val msg = receive() + LOG.info("Processing message: {}", msg) + + RequestReplyHelper.reply(msg, msg.input * 100) + } + } + } + + val actorRef = actor.spawn() + + val result = RequestReplyHelper.call(actorRef, TestMessage(50)) + LOG.info("Received reply: {}", result) + } + + @Test + fun server() { + val actor = ServerActor(object : AbstractServerHandler() { + @Suspendable + override fun handleCall(from: ActorRef<*>?, id: Any?, m: Int?): String { + LOG.info("Called with message: {} from {} with ID {}", m, from, id) + return m.toString() ?: "None" + } + + @Suspendable + override fun handleCast(from: ActorRef<*>?, id: Any?, m: Float?) { + LOG.info("Cast message: {} from {} with ID {}", m, from, id) + } + }) + + val server = actor.spawn() + + LOG.info("Call result: {}", server.call(5)) + server.cast(2.5f) + + server.shutdown() + } + + interface Summer { + fun sum(a: Int, b: Int) : Int + } + + @Test + fun proxyServer() { + val actor = ProxyServerActor(false, object : Summer { + @Synchronized + override fun sum(a: Int, b: Int): Int { + Exception().printStackTrace() + LOG.info("Adding together {} and {}", a, b) + return a + b + } + }) + + val summerActor = actor.spawn() + + val result = (summerActor as Summer).sum(1, 2) + LOG.info("Result: {}", result) + + summerActor.shutdown() + } + + @Test + fun eventSource() { + val actor = EventSourceActor() + val eventSource = actor.spawn() + + eventSource.addHandler { msg -> + LOG.info("Sent message: {}", msg) + } + + val name = "Outside Value" + eventSource.addHandler { msg -> + LOG.info("Also Sent message: {} {}", msg, name) + } + + eventSource.send("Hello") + + eventSource.shutdown() + } + + @Test + fun finiteStateMachine() { + val actor = object : FiniteStateMachineActor() { + @Suspendable + override fun initialState(): SuspendableCallable> { + LOG.info("Starting") + return SuspendableCallable { lockedState() } + } + + @Suspendable + fun lockedState() : SuspendableCallable> { + return receive {msg -> + when (msg) { + "PUSH" -> { + LOG.info("Still locked") + lockedState() + } + "COIN" -> { + LOG.info("Unlocking...") + unlockedState() + } + else -> TERMINATE + } + } + } + + @Suspendable + fun unlockedState() : SuspendableCallable> { + return receive {msg -> + when (msg) { + "PUSH" -> { + LOG.info("Locking") + lockedState() + } + "COIN" -> { + LOG.info("Unlocked") + unlockedState() + } + else -> TERMINATE + } + } + } + } + + val actorRef = actor.spawn() + + listOf("PUSH", "COIN", "COIN", "PUSH", "PUSH").forEach { + LOG.info(it) + actorRef.sendSync(it) + } + + actorRef.shutdown() + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt new file mode 100644 index 0000000000..819a149af3 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt @@ -0,0 +1,298 @@ +package com.baeldung.quasar + +import co.paralleluniverse.actors.* +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.strands.channels.Channels +import org.junit.Assert +import org.junit.Test +import org.slf4j.LoggerFactory +import java.util.concurrent.TimeUnit + +class ActorsTest { + companion object { + private val LOG = LoggerFactory.getLogger(ActorsTest::class.java) + } + + @Test + fun createNoopActor() { + val actor = object : Actor("noopActor", MailboxConfig(5, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + return "Hello" + } + } + + actor.spawn() + + println("Noop Actor: ${actor.get()}") + } + + @Test + fun registerActor() { + val actor = object : Actor("registerActor", null) { + @Suspendable + override fun doRun(): String { + return "Hello" + } + } + + val actorRef = actor.spawn() + actor.register() + + val retrievedRef = ActorRegistry.getActor>("registerActor") + + Assert.assertEquals(actorRef, retrievedRef) + actor.join() + } + + @Test + fun registerActorNewName() { + val actor = object : Actor(null, null) { + @Suspendable + override fun doRun(): String { + return "Hello" + } + } + + val actorRef = actor.spawn() + actor.register("renamedActor") + + val retrievedRef = ActorRegistry.getActor>("renamedActor") + + Assert.assertEquals(actorRef, retrievedRef) + actor.join() + } + + @Test + fun retrieveUnknownActor() { + val retrievedRef = ActorRegistry.getActor>("unknownActor", 1, TimeUnit.SECONDS) + + Assert.assertNull(retrievedRef) + } + + @Test + fun createSimpleActor() { + val actor = object : Actor("simpleActor", null) { + @Suspendable + override fun doRun(): Void? { + val msg = receive() + LOG.info("SimpleActor Received Message: {}", msg) + + return null + } + } + + val actorRef = actor.spawn() + + actorRef.send(1) + + actor.join() + } + + @Test + fun createLoopingActor() { + val actor = object : Actor("loopingActor", null) { + @Suspendable + override fun doRun(): Void? { + while (true) { + val msg = receive() + + if (msg > 0) { + LOG.info("LoopingActor Received Message: {}", msg) + } else { + break + } + } + + return null + } + } + + val actorRef = actor.spawn() + + actorRef.send(3) + actorRef.send(2) + actorRef.send(1) + actorRef.send(0) + + actor.join() + } + + @Test + fun actorBacklog() { + val actor = object : Actor("backlogActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + TimeUnit.MILLISECONDS.sleep(500); + LOG.info("Backlog Actor Received: {}", receive()) + + try { + receive() + } catch (e: Throwable) { + LOG.info("==== Exception throws by receive() ====") + e.printStackTrace() + } + + return "No Exception" + } + } + + val actorRef = actor.spawn() + + actorRef.send(1) + actorRef.send(2) + + try { + LOG.info("Backlog Actor: {}", actor.get()) + } catch (e: Exception) { + // Expected + LOG.info("==== Exception throws by get() ====") + e.printStackTrace() + } + } + + @Test + fun actorBacklogTrySend() { + val actor = object : Actor("backlogTrySendActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + TimeUnit.MILLISECONDS.sleep(500); + LOG.info("Backlog TrySend Actor Received: {}", receive()) + + return "No Exception" + } + } + + val actorRef = actor.spawn() + + LOG.info("Backlog TrySend 1: {}", actorRef.trySend(1)) + LOG.info("Backlog TrySend 1: {}", actorRef.trySend(2)) + + actor.join() + } + + @Test + fun actorTimeoutReceive() { + val actor = object : Actor("TimeoutReceiveActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + LOG.info("Timeout Actor Received: {}", receive(500, TimeUnit.MILLISECONDS)) + + return "Finished" + } + } + + val actorRef = actor.spawn() + + TimeUnit.MILLISECONDS.sleep(300) + actorRef.trySend(1) + + actor.join() + } + + + @Test + fun actorNonBlockingReceive() { + val actor = object : Actor("NonBlockingReceiveActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + LOG.info("NonBlocking Actor Received #1: {}", tryReceive()) + TimeUnit.MILLISECONDS.sleep(500) + LOG.info("NonBlocking Actor Received #2: {}", tryReceive()) + + return "Finished" + } + } + + val actorRef = actor.spawn() + + TimeUnit.MILLISECONDS.sleep(300) + actorRef.trySend(1) + + actor.join() + } + + @Test + fun evenActor() { + val actor = object : Actor("EvenActor", null) { + @Suspendable + override fun filterMessage(m: Any?): Int? { + return when (m) { + is Int -> { + if (m % 2 == 0) { + m * 10 + } else { + null + } + } + else -> super.filterMessage(m) + } + } + + @Suspendable + override fun doRun(): Void? { + while (true) { + val msg = receive() + + if (msg > 0) { + LOG.info("EvenActor Received Message: {}", msg) + } else { + break + } + } + + return null + } + } + + val actorRef = actor.spawn() + + actorRef.send(3) + actorRef.send(2) + actorRef.send(1) + actorRef.send(0) + + actor.join() + } + + @Test + fun watchingActors() { + val watched = object : Actor("WatchedActor", null) { + @Suspendable + override fun doRun(): Void? { + LOG.info("WatchedActor Starting") + receive(500, TimeUnit.MILLISECONDS) + LOG.info("WatchedActor Finishing") + return null + } + } + + val watcher = object : Actor("WatcherActor", null) { + @Suspendable + override fun doRun(): Void? { + LOG.info("WatcherActor Listening") + try { + LOG.info("WatcherActor received Message: {}", receive(2, TimeUnit.SECONDS)) + } catch (e: Exception) { + LOG.info("WatcherActor Received Exception", e) + } + return null + } + + @Suspendable + override fun handleLifecycleMessage(m: LifecycleMessage?): Int? { + LOG.info("WatcherActor Received Lifecycle Message: {}", m) + return super.handleLifecycleMessage(m) + } + } + + val watcherRef = watcher.spawn() + TimeUnit.MILLISECONDS.sleep(200) + + val watchedRef = watched.spawn() + watcher.link(watchedRef) + + watched.join() + watcher.join() + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt new file mode 100644 index 0000000000..83e06bf7d6 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt @@ -0,0 +1,135 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.channels.Channels +import co.paralleluniverse.strands.channels.Topic +import co.paralleluniverse.strands.channels.reactivestreams.ReactiveStreams +import org.junit.Test +import org.reactivestreams.Subscriber +import org.reactivestreams.Subscription +import org.slf4j.LoggerFactory +import java.util.concurrent.TimeUnit + +class ReactiveStreamsTest { + companion object { + private val LOG = LoggerFactory.getLogger(ReactiveStreamsTest::class.java) + } + + @Test + fun publisher() { + val inputChannel = Channels.newChannel(1); + + val publisher = ReactiveStreams.toPublisher(inputChannel) + publisher.subscribe(object : Subscriber { + @Suspendable + override fun onComplete() { + LOG.info("onComplete") + } + + @Suspendable + override fun onSubscribe(s: Subscription) { + LOG.info("onSubscribe: {}", s) + s.request(2) + } + + @Suspendable + override fun onNext(t: String?) { + LOG.info("onNext: {}", t) + } + + @Suspendable + override fun onError(t: Throwable?) { + LOG.info("onError: {}", t) + } + }) + + inputChannel.send("Hello") + inputChannel.send("World") + + TimeUnit.SECONDS.sleep(1) + + inputChannel.close() + } + + @Test + fun publisherTopic() { + val inputTopic = Topic() + + val publisher = ReactiveStreams.toPublisher(inputTopic) + publisher.subscribe(object : Subscriber { + @Suspendable + override fun onComplete() { + LOG.info("onComplete 1") + } + + @Suspendable + override fun onSubscribe(s: Subscription) { + LOG.info("onSubscribe 1: {}", s) + s.request(2) + } + + @Suspendable + override fun onNext(t: String?) { + LOG.info("onNext 1: {}", t) + } + + @Suspendable + override fun onError(t: Throwable?) { + LOG.info("onError 1: {}", t) + } + }) + publisher.subscribe(object : Subscriber { + @Suspendable + override fun onComplete() { + LOG.info("onComplete 2") + } + + @Suspendable + override fun onSubscribe(s: Subscription) { + LOG.info("onSubscribe 2: {}", s) + s.request(2) + } + + @Suspendable + override fun onNext(t: String?) { + LOG.info("onNext 2: {}", t) + } + + @Suspendable + override fun onError(t: Throwable?) { + LOG.info("onError 2: {}", t) + } + }) + + inputTopic.send("Hello") + inputTopic.send("World") + + TimeUnit.SECONDS.sleep(1) + + inputTopic.close() + } + + @Test + fun subscribe() { + val inputChannel = Channels.newChannel(10); + val publisher = ReactiveStreams.toPublisher(inputChannel) + + val channel = ReactiveStreams.subscribe(10, Channels.OverflowPolicy.THROW, publisher) + + fiber @Suspendable { + while (!channel.isClosed) { + val message = channel.receive() + LOG.info("Received: {}", message) + } + LOG.info("Stopped receiving messages") + } + + inputChannel.send("Hello") + inputChannel.send("World") + + TimeUnit.SECONDS.sleep(1) + + inputChannel.close() + } +} diff --git a/libraries-2/README.md b/libraries-2/README.md index 8243b9f82c..1b042ac3c5 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -4,4 +4,7 @@ - [A Guide to jBPM with Java](https://www.baeldung.com/jbpm-java) - [Guide to Classgraph Library](https://www.baeldung.com/classgraph) - [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program) - +- [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors) +- [Templating with Handlebars](https://www.baeldung.com/handlebars) +- [A Guide to Crawler4j](https://www.baeldung.com/crawler4j) +- [Decode an OkHttp JSON Response](https://www.baeldung.com/okhttp-json-response) diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 6303c0cab5..ff73888b69 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -1,67 +1,169 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + libraries2 + libraries2 - 4.0.0 - libraries2 - libraries2 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + + jboss-public-repository-group + JBoss Public Repository Group + http://repository.jboss.org/nexus/content/groups/public/ + + true + never + + + true + daily + + + - - - jboss-public-repository-group - JBoss Public Repository Group - http://repository.jboss.org/nexus/content/groups/public/ - - true - never - - - true - daily - - - + + + org.mapdb + mapdb + ${mapdb.version} + + + com.pivovarit + parallel-collectors + ${parallel-collectors.version} + + + org.assertj + assertj-core + ${assertj.version} + + + io.github.classgraph + classgraph + ${classgraph.version} + + + org.jbpm + jbpm-test + ${jbpm.version} + + + info.picocli + picocli + ${picocli.version} + + + org.ejml + ejml-all + ${ejml.version} + + + org.nd4j + nd4j-native + ${nd4j.version} + + + org.la4j + la4j + ${la4j.version} + + + colt + colt + ${colt.version} + + + org.springframework.boot + spring-boot-starter + ${spring-boot-starter.version} + + + net.openhft + chronicle-map + ${chronicle.map.version} + + + com.sun.java + tools + + + + + + com.squareup.okhttp3 + okhttp + ${okhttp.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.google.code.gson + gson + ${gson.version} + + + com.squareup.okhttp3 + mockwebserver + ${mockwebserver.version} + test + + + edu.uci.ics + crawler4j + ${crawler4j.version} + + + com.github.jknack + handlebars + ${handlebars.version} + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + org.apache.mesos + mesos + ${mesos.library.version} + + - - - org.assertj - assertj-core - ${assertj.version} - - - io.github.classgraph - classgraph - ${classgraph.version} - - - org.jbpm - jbpm-test - ${jbpm.version} - - - info.picocli - picocli - ${picocli.version} - - - org.springframework.boot - spring-boot-starter - ${spring-boot-starter.version} - - - - - 3.6.2 - 4.8.28 - 6.0.0.Final - 3.9.6 - 2.1.4.RELEASE - + + 3.0.7 + 3.6.2 + 4.8.28 + 6.0.0.Final + 3.9.6 + 3.17.2 + 4.4.0 + 2.1.4.RELEASE + 0.38 + 1.0.0-beta4 + 1.2.0 + 0.6.0 + 1.19 + 0.28.3 + 1.1.0 + 3.14.2 + 2.8.5 + 3.14.2 + 4.1.2 + diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/CrawlerStatistics.java b/libraries-2/src/main/java/com/baeldung/crawler4j/CrawlerStatistics.java new file mode 100644 index 0000000000..e3237a2755 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/CrawlerStatistics.java @@ -0,0 +1,22 @@ +package com.baeldung.crawler4j; + +public class CrawlerStatistics { + private int processedPageCount = 0; + private int totalLinksCount = 0; + + public void incrementProcessedPageCount() { + processedPageCount++; + } + + public void incrementTotalLinksCount(int linksCount) { + totalLinksCount += linksCount; + } + + public int getProcessedPageCount() { + return processedPageCount; + } + + public int getTotalLinksCount() { + return totalLinksCount; + } +} diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawler.java b/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawler.java new file mode 100644 index 0000000000..b77e1e075f --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawler.java @@ -0,0 +1,48 @@ +package com.baeldung.crawler4j; + +import java.util.Set; +import java.util.regex.Pattern; + +import edu.uci.ics.crawler4j.crawler.Page; +import edu.uci.ics.crawler4j.crawler.WebCrawler; +import edu.uci.ics.crawler4j.parser.HtmlParseData; +import edu.uci.ics.crawler4j.url.WebURL; + +public class HtmlCrawler extends WebCrawler { + + private final static Pattern EXCLUSIONS = Pattern.compile(".*(\\.(css|js|xml|gif|jpg|png|mp3|mp4|zip|gz|pdf))$"); + + private CrawlerStatistics stats; + + public HtmlCrawler(CrawlerStatistics stats) { + this.stats = stats; + } + + @Override + public boolean shouldVisit(Page referringPage, WebURL url) { + String urlString = url.getURL().toLowerCase(); + return !EXCLUSIONS.matcher(urlString).matches() + && urlString.startsWith("https://www.baeldung.com/"); + } + + @Override + public void visit(Page page) { + String url = page.getWebURL().getURL(); + stats.incrementProcessedPageCount(); + + if (page.getParseData() instanceof HtmlParseData) { + HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); + String title = htmlParseData.getTitle(); + String text = htmlParseData.getText(); + String html = htmlParseData.getHtml(); + Set links = htmlParseData.getOutgoingUrls(); + stats.incrementTotalLinksCount(links.size()); + + System.out.printf("Page with title '%s' %n", title); + System.out.printf(" Text length: %d %n", text.length()); + System.out.printf(" HTML length: %d %n", html.length()); + System.out.printf(" %d outbound links %n", links.size()); + } + } + +} diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawlerController.java b/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawlerController.java new file mode 100644 index 0000000000..82c1c6bdd7 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawlerController.java @@ -0,0 +1,36 @@ +package com.baeldung.crawler4j; + +import java.io.File; + +import edu.uci.ics.crawler4j.crawler.CrawlConfig; +import edu.uci.ics.crawler4j.crawler.CrawlController; +import edu.uci.ics.crawler4j.fetcher.PageFetcher; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; + +public class HtmlCrawlerController { + + public static void main(String[] args) throws Exception { + File crawlStorage = new File("src/test/resources/crawler4j"); + CrawlConfig config = new CrawlConfig(); + config.setCrawlStorageFolder(crawlStorage.getAbsolutePath()); + config.setMaxDepthOfCrawling(2); + + int numCrawlers = 12; + + PageFetcher pageFetcher = new PageFetcher(config); + RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); + RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); + CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); + + controller.addSeed("https://www.baeldung.com/"); + + CrawlerStatistics stats = new CrawlerStatistics(); + CrawlController.WebCrawlerFactory factory = () -> new HtmlCrawler(stats); + + controller.start(factory, numCrawlers); + System.out.printf("Crawled %d pages %n", stats.getProcessedPageCount()); + System.out.printf("Total Number of outbound links = %d %n", stats.getTotalLinksCount()); + } + +} diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawler.java b/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawler.java new file mode 100644 index 0000000000..ebb5d96f36 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawler.java @@ -0,0 +1,49 @@ +package com.baeldung.crawler4j; + +import java.io.File; +import java.util.regex.Pattern; + +import edu.uci.ics.crawler4j.crawler.Page; +import edu.uci.ics.crawler4j.crawler.WebCrawler; +import edu.uci.ics.crawler4j.parser.BinaryParseData; +import edu.uci.ics.crawler4j.url.WebURL; + +public class ImageCrawler extends WebCrawler { + private final static Pattern EXCLUSIONS = Pattern.compile(".*(\\.(css|js|xml|gif|png|mp3|mp4|zip|gz|pdf))$"); + + private static final Pattern IMG_PATTERNS = Pattern.compile(".*(\\.(jpg|jpeg))$"); + + private File saveDir; + + public ImageCrawler(File saveDir) { + this.saveDir = saveDir; + } + + @Override + public boolean shouldVisit(Page referringPage, WebURL url) { + String urlString = url.getURL().toLowerCase(); + if (EXCLUSIONS.matcher(urlString).matches()) { + return false; + } + + if (IMG_PATTERNS.matcher(urlString).matches() + || urlString.startsWith("https://www.baeldung.com/")) { + return true; + } + + return false; + } + + @Override + public void visit(Page page) { + String url = page.getWebURL().getURL(); + if (IMG_PATTERNS.matcher(url).matches() + && page.getParseData() instanceof BinaryParseData) { + String extension = url.substring(url.lastIndexOf(".")); + int contentLength = page.getContentData().length; + + System.out.printf("Extension is '%s' with content length %d %n", extension, contentLength); + } + } + +} diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawlerController.java b/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawlerController.java new file mode 100644 index 0000000000..9db32f1bfb --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawlerController.java @@ -0,0 +1,36 @@ +package com.baeldung.crawler4j; + +import java.io.File; + +import edu.uci.ics.crawler4j.crawler.CrawlConfig; +import edu.uci.ics.crawler4j.crawler.CrawlController; +import edu.uci.ics.crawler4j.fetcher.PageFetcher; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; + +public class ImageCrawlerController { + + public static void main(String[] args) throws Exception { + File crawlStorage = new File("src/test/resources/crawler4j"); + CrawlConfig config = new CrawlConfig(); + config.setCrawlStorageFolder(crawlStorage.getAbsolutePath()); + config.setIncludeBinaryContentInCrawling(true); + config.setMaxPagesToFetch(500); + + File saveDir = new File("src/test/resources/crawler4j"); + + int numCrawlers = 12; + + PageFetcher pageFetcher = new PageFetcher(config); + RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); + RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); + CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); + + controller.addSeed("https://www.baeldung.com/"); + + CrawlController.WebCrawlerFactory factory = () -> new ImageCrawler(saveDir); + + controller.start(factory, numCrawlers); + } + +} diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/MultipleCrawlerController.java b/libraries-2/src/main/java/com/baeldung/crawler4j/MultipleCrawlerController.java new file mode 100644 index 0000000000..7662607f80 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/MultipleCrawlerController.java @@ -0,0 +1,54 @@ +package com.baeldung.crawler4j; + +import java.io.File; + +import edu.uci.ics.crawler4j.crawler.CrawlConfig; +import edu.uci.ics.crawler4j.crawler.CrawlController; +import edu.uci.ics.crawler4j.fetcher.PageFetcher; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; + +public class MultipleCrawlerController { + public static void main(String[] args) throws Exception { + File crawlStorageBase = new File("src/test/resources/crawler4j"); + CrawlConfig htmlConfig = new CrawlConfig(); + CrawlConfig imageConfig = new CrawlConfig(); + + htmlConfig.setCrawlStorageFolder(new File(crawlStorageBase, "html").getAbsolutePath()); + imageConfig.setCrawlStorageFolder(new File(crawlStorageBase, "image").getAbsolutePath()); + imageConfig.setIncludeBinaryContentInCrawling(true); + + htmlConfig.setMaxPagesToFetch(500); + imageConfig.setMaxPagesToFetch(1000); + + PageFetcher pageFetcherHtml = new PageFetcher(htmlConfig); + PageFetcher pageFetcherImage = new PageFetcher(imageConfig); + + RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); + RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcherHtml); + + CrawlController htmlController = new CrawlController(htmlConfig, pageFetcherHtml, robotstxtServer); + CrawlController imageController = new CrawlController(imageConfig, pageFetcherImage, robotstxtServer); + + htmlController.addSeed("https://www.baeldung.com/"); + imageController.addSeed("https://www.baeldung.com/"); + + CrawlerStatistics stats = new CrawlerStatistics(); + CrawlController.WebCrawlerFactory htmlFactory = () -> new HtmlCrawler(stats); + + File saveDir = new File("src/test/resources/crawler4j"); + CrawlController.WebCrawlerFactory imageFactory = () -> new ImageCrawler(saveDir); + + imageController.startNonBlocking(imageFactory, 7); + htmlController.startNonBlocking(htmlFactory, 10); + + + htmlController.waitUntilFinish(); + System.out.printf("Crawled %d pages %n", stats.getProcessedPageCount()); + System.out.printf("Total Number of outbound links = %d %n", stats.getTotalLinksCount()); + + imageController.waitUntilFinish(); + System.out.printf("Image Crawler is finished."); + + } +} diff --git a/libraries-2/src/main/java/com/baeldung/mesos/HelloWorldMain.java b/libraries-2/src/main/java/com/baeldung/mesos/HelloWorldMain.java new file mode 100644 index 0000000000..e4bf593e7e --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/mesos/HelloWorldMain.java @@ -0,0 +1,42 @@ +package com.baeldung.mesos; + +import com.baeldung.mesos.schedulers.HelloWorldScheduler; +import org.apache.mesos.MesosSchedulerDriver; +import org.apache.mesos.Protos; +import org.apache.mesos.Protos.CommandInfo; +import org.apache.mesos.Protos.ExecutorInfo; +import org.apache.mesos.Protos.FrameworkInfo; + +public class HelloWorldMain { + + public static void main(String[] args) { + + String path = System.getProperty("user.dir") + + "/target/libraries2-1.0.0-SNAPSHOT.jar"; + + CommandInfo.URI uri = CommandInfo.URI.newBuilder().setValue(path).setExtract(false).build(); + + String helloWorldCommand = "java -cp libraries2-1.0.0-SNAPSHOT.jar com.baeldung.mesos.executors.HelloWorldExecutor"; + CommandInfo commandInfoHelloWorld = CommandInfo.newBuilder().setValue(helloWorldCommand).addUris(uri) + .build(); + + ExecutorInfo executorHelloWorld = ExecutorInfo.newBuilder() + .setExecutorId(Protos.ExecutorID.newBuilder().setValue("HelloWorldExecutor")) + .setCommand(commandInfoHelloWorld).setName("Hello World (Java)").setSource("java").build(); + + FrameworkInfo.Builder frameworkBuilder = FrameworkInfo.newBuilder().setFailoverTimeout(120000) + .setUser("") + .setName("Hello World Framework (Java)"); + + frameworkBuilder.setPrincipal("test-framework-java"); + + MesosSchedulerDriver driver = new MesosSchedulerDriver(new HelloWorldScheduler(executorHelloWorld), frameworkBuilder.build(), args[0]); + + int status = driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1; + + // Ensure that the driver process terminates. + driver.stop(); + + System.exit(status); + } +} diff --git a/libraries-2/src/main/java/com/baeldung/mesos/executors/HelloWorldExecutor.java b/libraries-2/src/main/java/com/baeldung/mesos/executors/HelloWorldExecutor.java new file mode 100644 index 0000000000..a8620bbce3 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/mesos/executors/HelloWorldExecutor.java @@ -0,0 +1,59 @@ +package com.baeldung.mesos.executors; + +import org.apache.mesos.Executor; +import org.apache.mesos.ExecutorDriver; +import org.apache.mesos.MesosExecutorDriver; +import org.apache.mesos.Protos; +import org.apache.mesos.Protos.TaskInfo; + +public class HelloWorldExecutor implements Executor { + @Override + public void registered(ExecutorDriver driver, Protos.ExecutorInfo executorInfo, Protos.FrameworkInfo frameworkInfo, Protos.SlaveInfo slaveInfo) { + } + + @Override + public void reregistered(ExecutorDriver driver, Protos.SlaveInfo slaveInfo) { + } + + @Override + public void disconnected(ExecutorDriver driver) { + } + + @Override + public void launchTask(ExecutorDriver driver, TaskInfo task) { + + Protos.TaskStatus status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId()) + .setState(Protos.TaskState.TASK_RUNNING).build(); + driver.sendStatusUpdate(status); + + String myStatus = "Hello Framework"; + driver.sendFrameworkMessage(myStatus.getBytes()); + + System.out.println("Hello World!!!"); + + status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId()) + .setState(Protos.TaskState.TASK_FINISHED).build(); + driver.sendStatusUpdate(status); + } + + @Override + public void killTask(ExecutorDriver driver, Protos.TaskID taskId) { + } + + @Override + public void frameworkMessage(ExecutorDriver driver, byte[] data) { + } + + @Override + public void shutdown(ExecutorDriver driver) { + } + + @Override + public void error(ExecutorDriver driver, String message) { + } + + public static void main(String[] args) { + MesosExecutorDriver driver = new MesosExecutorDriver(new HelloWorldExecutor()); + System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1); + } +} diff --git a/libraries-2/src/main/java/com/baeldung/mesos/schedulers/HelloWorldScheduler.java b/libraries-2/src/main/java/com/baeldung/mesos/schedulers/HelloWorldScheduler.java new file mode 100644 index 0000000000..68808b4dd0 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/mesos/schedulers/HelloWorldScheduler.java @@ -0,0 +1,100 @@ +package com.baeldung.mesos.schedulers; + +import com.google.protobuf.ByteString; +import org.apache.mesos.Protos; +import org.apache.mesos.Protos.ExecutorInfo; +import org.apache.mesos.Protos.Offer; +import org.apache.mesos.Protos.OfferID; +import org.apache.mesos.Protos.TaskInfo; +import org.apache.mesos.Scheduler; +import org.apache.mesos.SchedulerDriver; + +import java.util.ArrayList; +import java.util.List; + +public class HelloWorldScheduler implements Scheduler { + + private int launchedTasks = 0; + private final ExecutorInfo helloWorldExecutor; + + public HelloWorldScheduler(ExecutorInfo helloWorldExecutor) { + this.helloWorldExecutor = helloWorldExecutor; + } + + @Override + public void registered(SchedulerDriver schedulerDriver, Protos.FrameworkID frameworkID, Protos.MasterInfo masterInfo) { + + } + + @Override + public void reregistered(SchedulerDriver schedulerDriver, Protos.MasterInfo masterInfo) { + + } + + @Override + public void resourceOffers(SchedulerDriver schedulerDriver, List list) { + + for (Offer offer : list) { + List tasks = new ArrayList(); + Protos.TaskID taskId = Protos.TaskID.newBuilder().setValue(Integer.toString(launchedTasks++)).build(); + + System.out.println("Launching printHelloWorld " + taskId.getValue() + " Hello World Java"); + TaskInfo printHelloWorld = TaskInfo + .newBuilder() + .setName("printHelloWorld " + taskId.getValue()) + .setTaskId(taskId) + .setSlaveId(offer.getSlaveId()) + .addResources( + Protos.Resource.newBuilder().setName("cpus").setType(Protos.Value.Type.SCALAR) + .setScalar(Protos.Value.Scalar.newBuilder().setValue(1))) + .addResources( + Protos.Resource.newBuilder().setName("mem").setType(Protos.Value.Type.SCALAR) + .setScalar(Protos.Value.Scalar.newBuilder().setValue(128))) + .setExecutor(ExecutorInfo.newBuilder(helloWorldExecutor)).build(); + + List offerIDS = new ArrayList<>(); + offerIDS.add(offer.getId()); + + tasks.add(printHelloWorld); + + schedulerDriver.declineOffer(offer.getId()); + schedulerDriver.launchTasks(offerIDS, tasks); + } + + } + + @Override + public void offerRescinded(SchedulerDriver schedulerDriver, OfferID offerID) { + + } + + @Override + public void statusUpdate(SchedulerDriver schedulerDriver, Protos.TaskStatus taskStatus) { + + } + + @Override + public void frameworkMessage(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, byte[] bytes) { + + } + + @Override + public void disconnected(SchedulerDriver schedulerDriver) { + + } + + @Override + public void slaveLost(SchedulerDriver schedulerDriver, Protos.SlaveID slaveID) { + + } + + @Override + public void executorLost(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, int i) { + + } + + @Override + public void error(SchedulerDriver schedulerDriver, String s) { + + } +} diff --git a/libraries-2/src/test/java/com/baeldung/chroniclemap/ChronicleMapUnitTest.java b/libraries-2/src/test/java/com/baeldung/chroniclemap/ChronicleMapUnitTest.java new file mode 100644 index 0000000000..7f36a9abdb --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/chroniclemap/ChronicleMapUnitTest.java @@ -0,0 +1,132 @@ +package com.baeldung.chroniclemap; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import net.openhft.chronicle.core.values.LongValue; +import net.openhft.chronicle.map.ChronicleMap; +import net.openhft.chronicle.map.ExternalMapQueryContext; +import net.openhft.chronicle.map.MapEntry; +import net.openhft.chronicle.values.Values; + +public class ChronicleMapUnitTest { + + static ChronicleMap persistedCountryMap = null; + + static ChronicleMap inMemoryCountryMap = null; + + static ChronicleMap> multiMap = null; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @BeforeClass + public static void init() { + try { + inMemoryCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class) + .name("country-map") + .entries(50) + .averageValue("America") + .create(); + + persistedCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class) + .name("country-map") + .entries(50) + .averageValue("America") + .createPersistedTo(new File(System.getProperty("user.home") + "/country-details.dat")); + + Set averageValue = IntStream.of(1, 2) + .boxed() + .collect(Collectors.toSet()); + multiMap = ChronicleMap.of(Integer.class, (Class>) (Class) Set.class) + .name("multi-map") + .entries(50) + .averageValue(averageValue) + .create(); + + LongValue qatarKey = Values.newHeapInstance(LongValue.class); + qatarKey.setValue(1); + inMemoryCountryMap.put(qatarKey, "Qatar"); + + LongValue key = Values.newHeapInstance(LongValue.class); + key.setValue(1); + persistedCountryMap.put(key, "Romania"); + key.setValue(2); + persistedCountryMap.put(key, "India"); + + Set set1 = new HashSet<>(); + set1.add(1); + set1.add(2); + multiMap.put(1, set1); + + Set set2 = new HashSet<>(); + set2.add(3); + multiMap.put(2, set2); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void givenGetQuery_whenCalled_shouldReturnResult() { + LongValue key = Values.newHeapInstance(LongValue.class); + key.setValue(1); + CharSequence country = inMemoryCountryMap.get(key); + assertThat(country.toString(), is(equalTo("Qatar"))); + } + + @Test + public void givenGetUsingQuery_whenCalled_shouldReturnResult() { + LongValue key = Values.newHeapInstance(LongValue.class); + StringBuilder country = new StringBuilder(); + key.setValue(1); + persistedCountryMap.getUsing(key, country); + assertThat(country.toString(), is(equalTo("Romania"))); + key.setValue(2); + persistedCountryMap.getUsing(key, country); + assertThat(country.toString(), is(equalTo("India"))); + } + + @Test + public void givenMultipleKeyQuery_whenProcessed_shouldChangeTheValue() { + try (ExternalMapQueryContext, ?> fistContext = multiMap.queryContext(1)) { + try (ExternalMapQueryContext, ?> secondContext = multiMap.queryContext(2)) { + fistContext.updateLock() + .lock(); + secondContext.updateLock() + .lock(); + MapEntry> firstEntry = fistContext.entry(); + Set firstSet = firstEntry.value() + .get(); + firstSet.remove(2); + MapEntry> secondEntry = secondContext.entry(); + Set secondSet = secondEntry.value() + .get(); + secondSet.add(4); + firstEntry.doReplaceValue(fistContext.wrapValueAsData(firstSet)); + secondEntry.doReplaceValue(secondContext.wrapValueAsData(secondSet)); + } + } finally { + assertThat(multiMap.get(1) + .size(), is(equalTo(1))); + assertThat(multiMap.get(2) + .size(), is(equalTo(2))); + } + } + + @AfterClass + public static void finish() { + persistedCountryMap.close(); + inMemoryCountryMap.close(); + multiMap.close(); + } +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java new file mode 100644 index 0000000000..3eb325dbb6 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java @@ -0,0 +1,109 @@ +package com.baeldung.handlebars; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Template; +import com.github.jknack.handlebars.io.ClassPathTemplateLoader; +import com.github.jknack.handlebars.io.TemplateLoader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; + +/** + * Showcases the tag usage and different template loading mechanisms. + * + * @author isaolmez + */ +public class BasicUsageUnitTest { + + @Test + public void whenThereIsNoTemplateFile_ThenCompilesInline() throws IOException { + Handlebars handlebars = new Handlebars(); + Template template = handlebars.compileInline("Hi {{this}}!"); + + String templateString = template.apply("Baeldung"); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + @Test + public void whenParameterMapIsSupplied_thenDisplays() throws IOException { + Handlebars handlebars = new Handlebars(); + Template template = handlebars.compileInline("Hi {{name}}!"); + Map parameterMap = new HashMap<>(); + parameterMap.put("name", "Baeldung"); + + String templateString = template.apply(parameterMap); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + @Test + public void whenParameterObjectIsSupplied_ThenDisplays() throws IOException { + Handlebars handlebars = new Handlebars(); + Template template = handlebars.compileInline("Hi {{name}}!"); + Person person = new Person(); + person.setName("Baeldung"); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + @Test + public void whenMultipleParametersAreSupplied_ThenDisplays() throws IOException { + Handlebars handlebars = new Handlebars(); + Template template = handlebars.compileInline("Hi {{name}}! This is {{topic}}."); + Map parameterMap = new HashMap<>(); + parameterMap.put("name", "Baeldung"); + parameterMap.put("topic", "Handlebars"); + + String templateString = template.apply(parameterMap); + + assertThat(templateString).isEqualTo("Hi Baeldung! This is Handlebars."); + } + + @Test + public void whenNoLoaderIsGiven_ThenSearchesClasspath() throws IOException { + Handlebars handlebars = new Handlebars(); + Template template = handlebars.compile("greeting"); + Person person = getPerson("Baeldung"); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + @Test + public void whenClasspathTemplateLoaderIsGiven_ThenSearchesClasspathWithPrefixSuffix() throws IOException { + TemplateLoader loader = new ClassPathTemplateLoader("/handlebars", ".html"); + Handlebars handlebars = new Handlebars(loader); + Template template = handlebars.compile("greeting"); + Person person = getPerson("Baeldung"); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + @Test + public void whenMultipleLoadersAreGiven_ThenSearchesSequentially() throws IOException { + TemplateLoader firstLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + TemplateLoader secondLoader = new ClassPathTemplateLoader("/templates", ".html"); + Handlebars handlebars = new Handlebars().with(firstLoader, secondLoader); + Template template = handlebars.compile("greeting"); + Person person = getPerson("Baeldung"); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + private Person getPerson(String name) { + Person person = new Person(); + person.setName(name); + return person; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java new file mode 100644 index 0000000000..6749f7fe0a --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java @@ -0,0 +1,106 @@ +package com.baeldung.handlebars; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Template; +import com.github.jknack.handlebars.io.ClassPathTemplateLoader; +import com.github.jknack.handlebars.io.TemplateLoader; +import java.io.IOException; +import org.junit.Test; + +/** + * Showcases the built-in template helpers. + * + * @author isaolmez + */ +public class BuiltinHelperUnitTest { + + private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + + @Test + public void whenUsedWith_ThenContextChanges() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("with"); + Person person = getPerson("Baeldung"); + person.getAddress().setStreet("World"); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\n

I live in World

\n"); + } + + @Test + public void whenUsedWithMustacheStyle_ThenContextChanges() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("with_mustache"); + Person person = getPerson("Baeldung"); + person.getAddress().setStreet("World"); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\n

I live in World

\n"); + } + + @Test + public void whenUsedEach_ThenIterates() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("each"); + Person person = getPerson("Baeldung"); + Person friend1 = getPerson("Java"); + Person friend2 = getPerson("Spring"); + person.getFriends().add(friend1); + person.getFriends().add(friend2); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\nJava is my friend.\n" + + "\nSpring is my friend.\n"); + } + + @Test + public void whenUsedEachMustacheStyle_ThenIterates() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("each_mustache"); + Person person = getPerson("Baeldung"); + Person friend1 = getPerson("Java"); + Person friend2 = getPerson("Spring"); + person.getFriends().add(friend1); + person.getFriends().add(friend2); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\nJava is my friend.\n" + + "\nSpring is my friend.\n"); + } + + @Test + public void whenUsedIf_ThenPutsCondition() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("if"); + Person person = getPerson("Baeldung"); + person.setBusy(true); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\n

Baeldung is busy.

\n"); + } + + @Test + public void whenUsedIfMustacheStyle_ThenPutsCondition() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("if_mustache"); + Person person = getPerson("Baeldung"); + person.setBusy(true); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\n

Baeldung is busy.

\n"); + } + + private Person getPerson(String name) { + Person person = new Person(); + person.setName(name); + return person; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java new file mode 100644 index 0000000000..a3c6667654 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.handlebars; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Helper; +import com.github.jknack.handlebars.Options; +import com.github.jknack.handlebars.Template; +import com.github.jknack.handlebars.io.ClassPathTemplateLoader; +import com.github.jknack.handlebars.io.TemplateLoader; +import java.io.IOException; +import org.junit.Test; + +/** + * Showcases implementing a custom template helper. + * + * @author isaolmez + */ +public class CustomHelperUnitTest { + + private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + + @Test + public void whenHelperIsCreated_ThenCanRegister() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + handlebars.registerHelper("isBusy", new Helper() { + @Override + public Object apply(Person context, Options options) throws IOException { + String busyString = context.isBusy() ? "busy" : "available"; + return context.getName() + " - " + busyString; + } + }); + Template template = handlebars.compile("person"); + Person person = getPerson("Baeldung"); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Baeldung - busy"); + } + + @Test + public void whenHelperSourceIsCreated_ThenCanRegister() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + handlebars.registerHelpers(new HelperSource()); + Template template = handlebars.compile("person"); + Person person = getPerson("Baeldung"); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Baeldung - busy"); + } + + private Person getPerson(String name) { + Person person = new Person(); + person.setName(name); + person.setBusy(true); + return person; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java b/libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java new file mode 100644 index 0000000000..b98786c029 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java @@ -0,0 +1,9 @@ +package com.baeldung.handlebars; + +public class HelperSource { + + public String isBusy(Person context) { + String busyString = context.isBusy() ? "busy" : "available"; + return context.getName() + " - " + busyString; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/Person.java b/libraries-2/src/test/java/com/baeldung/handlebars/Person.java new file mode 100644 index 0000000000..9ddc0fdffb --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/Person.java @@ -0,0 +1,58 @@ +package com.baeldung.handlebars; + +import java.util.ArrayList; +import java.util.List; + +public class Person { + + private String name; + private boolean busy; + private Address address = new Address(); + private List friends = new ArrayList<>(); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isBusy() { + return busy; + } + + public void setBusy(boolean busy) { + this.busy = busy; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public List getFriends() { + return friends; + } + + public void setFriends(List friends) { + this.friends = friends; + } + + public static class Address { + + private String street; + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java new file mode 100644 index 0000000000..36f78f486e --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.handlebars; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Template; +import com.github.jknack.handlebars.io.ClassPathTemplateLoader; +import com.github.jknack.handlebars.io.TemplateLoader; +import java.io.IOException; +import org.junit.Test; + +/** + * Showcases reusing the existing templates. + * + * @author isaolmez + */ +public class ReusingTemplatesUnitTest { + + private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + + @Test + public void whenOtherTemplateIsReferenced_ThenCanReuse() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("page"); + Person person = new Person(); + person.setName("Baeldung"); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("

Hi Baeldung!

\n

This is the page Baeldung

"); + } + + @Test + public void whenBlockIsDefined_ThenCanOverrideWithPartial() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("simplemessage"); + Person person = new Person(); + person.setName("Baeldung"); + + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\n\n" + + "\n" + + "\n This is the intro\n\n" + + "\n Hi there!\n\n" + + "\n" + + ""); + } +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java new file mode 100644 index 0000000000..6f5141b054 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.mapdb; + +import org.junit.Test; +import org.mapdb.DB; +import org.mapdb.DBMaker; +import org.mapdb.Serializer; + +import java.util.NavigableSet; + +import static junit.framework.Assert.assertEquals; + +public class CollectionsUnitTest { + + @Test + public void givenSetCreatedInDB_whenMultipleElementsAdded_checkOnlyOneExists() { + + DB db = DBMaker.memoryDB().make(); + + NavigableSet set = db. + treeSet("mySet") + .serializer(Serializer.STRING) + .createOrOpen(); + + String myString = "Baeldung!"; + + set.add(myString); + set.add(myString); + + assertEquals(1, set.size()); + + db.close(); + } +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java new file mode 100644 index 0000000000..3b7cac04fb --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.mapdb; + +import org.jetbrains.annotations.NotNull; +import org.junit.Test; +import org.mapdb.*; + +import java.io.IOException; + +import static junit.framework.Assert.assertEquals; + +public class HTreeMapUnitTest { + + @Test + public void givenValidDB_whenHTreeMapAddedToAndRetrieved_CheckedRetrievalCorrect() { + + DB db = DBMaker.memoryDB().make(); + + HTreeMap hTreeMap = db + .hashMap("myTreMap") + .keySerializer(Serializer.STRING) + .valueSerializer(Serializer.STRING) + .create(); + + hTreeMap.put("key1", "value1"); + hTreeMap.put("key2", "value2"); + + assertEquals(2, hTreeMap.size()); + + //add another value with the same key + + hTreeMap.put("key1", "value3"); + + assertEquals(2, hTreeMap.size()); + assertEquals("value3", hTreeMap.get("key1")); + + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java new file mode 100644 index 0000000000..952efd0639 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.mapdb; + +import org.junit.Test; +import org.mapdb.DB; +import org.mapdb.DBMaker; +import org.mapdb.HTreeMap; + +import java.util.concurrent.ConcurrentMap; + +import static junit.framework.Assert.assertEquals; + +public class HelloBaeldungUnitTest { + + @Test + public void givenInMemoryDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() { + + DB db = DBMaker.memoryDB().make(); + + String welcomeMessageKey = "Welcome Message"; + String welcomeMessageString = "Hello Baeldung!"; + + HTreeMap myMap = db.hashMap("myMap").createOrOpen(); + myMap.put(welcomeMessageKey, welcomeMessageString); + + String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey); + + db.close(); + + assertEquals(welcomeMessageString, welcomeMessageFromDB); + } + + @Test + public void givenInFileDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() { + + DB db = DBMaker.fileDB("file.db").make(); + + String welcomeMessageKey = "Welcome Message"; + String welcomeMessageString = "Hello Baeldung!"; + + HTreeMap myMap = db.hashMap("myMap").createOrOpen(); + myMap.put(welcomeMessageKey, welcomeMessageString); + + String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey); + + db.close(); + + assertEquals(welcomeMessageString, welcomeMessageFromDB); + } +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java new file mode 100644 index 0000000000..9c53f9c792 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.mapdb; + +import org.junit.Test; +import org.mapdb.DB; +import org.mapdb.DBMaker; +import org.mapdb.HTreeMap; +import org.mapdb.Serializer; + +import static junit.framework.Assert.assertEquals; + +public class InMemoryModesUnitTest { + + @Test + public void givenDBCreatedOnHeap_whenUsed_checkUsageCorrect() { + + DB heapDB = DBMaker.heapDB().make(); + + HTreeMap map = heapDB + .hashMap("myMap") + .keySerializer(Serializer.INTEGER) + .valueSerializer(Serializer.STRING) + .createOrOpen(); + + map.put(1, "ONE"); + + assertEquals("ONE", map.get(1)); + + } + + @Test + public void givenDBCreatedBaseOnByteArray_whenUsed_checkUsageCorrect() { + + DB heapDB = DBMaker.memoryDB().make(); + + HTreeMap map = heapDB + .hashMap("myMap") + .keySerializer(Serializer.INTEGER) + .valueSerializer(Serializer.STRING) + .createOrOpen(); + + map.put(1, "ONE"); + + assertEquals("ONE", map.get(1)); + } + + @Test + public void givenDBCreatedBaseOnDirectByteBuffer_whenUsed_checkUsageCorrect() { + + DB heapDB = DBMaker.memoryDirectDB().make(); + + HTreeMap map = heapDB + .hashMap("myMap") + .keySerializer(Serializer.INTEGER) + .valueSerializer(Serializer.STRING) + .createOrOpen(); + + map.put(1, "ONE"); + + assertEquals("ONE", map.get(1)); + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java new file mode 100644 index 0000000000..83ba917393 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.mapdb; + +import org.junit.Test; +import org.mapdb.Serializer; +import org.mapdb.SortedTableMap; +import org.mapdb.volume.MappedFileVol; +import org.mapdb.volume.Volume; + +import static junit.framework.Assert.assertEquals; + +public class SortedTableMapUnitTest { + + private static final String VOLUME_LOCATION = "sortedTableMapVol.db"; + + @Test + public void givenValidSortedTableMapSetup_whenQueried_checkValuesCorrect() { + + //create memory mapped volume, readonly false + Volume vol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, false); + + //create sink to feed the map with data + SortedTableMap.Sink sink = + SortedTableMap.create( + vol, + Serializer.INTEGER, + Serializer.STRING + ).createFromSink(); + + //add content + for(int i = 0; i < 100; i++){ + sink.put(i, "Value " + Integer.toString(i)); + } + + sink.create(); + + //now open in read-only mode + Volume openVol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, true); + + SortedTableMap sortedTableMap = SortedTableMap.open( + openVol, + Serializer.INTEGER, + Serializer.STRING + ); + + assertEquals(100, sortedTableMap.size()); + } +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java new file mode 100644 index 0000000000..4de9db10e8 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.mapdb; + +import org.junit.Test; +import org.mapdb.DB; +import org.mapdb.DBMaker; +import org.mapdb.Serializer; + +import java.util.NavigableSet; + +import static junit.framework.Assert.assertEquals; + +public class TransactionsUnitTest { + + @Test + public void givenValidDBSetup_whenTransactionCommittedAndRolledBack_checkPreviousStateAchieved() { + + DB db = DBMaker.memoryDB().transactionEnable().make(); + + NavigableSet set = db + .treeSet("mySet") + .serializer(Serializer.STRING) + .createOrOpen(); + + set.add("One"); + set.add("Two"); + + db.commit(); + + assertEquals(2, set.size()); + + set.add("Three"); + + assertEquals(3, set.size()); + + db.rollback(); + + assertEquals(2, set.size()); + + db.close(); + } +} diff --git a/libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java b/libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java new file mode 100644 index 0000000000..1e3b183aa7 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java @@ -0,0 +1,9 @@ +package com.baeldung.matrices; + +public class MatrixMultiplicationBenchmarking { + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java new file mode 100644 index 0000000000..05944e7b3a --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.matrices.apache; + +import org.apache.commons.math3.linear.Array2DRowRealMatrix; +import org.apache.commons.math3.linear.RealMatrix; +import org.junit.jupiter.api.Test; +import org.openjdk.jmh.annotations.*; + +import static org.assertj.core.api.Assertions.assertThat; + +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class RealMatrixUnitTest { + + @Test + @Benchmark + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + RealMatrix firstMatrix = new Array2DRowRealMatrix( + new double[][] { + new double[] {1d, 5d}, + new double[] {2d, 3d}, + new double[] {1d ,7d} + } + ); + + RealMatrix secondMatrix = new Array2DRowRealMatrix( + new double[][] { + new double[] {1d, 2d, 3d, 7d}, + new double[] {5d, 2d, 8d, 1d} + } + ); + + RealMatrix expected = new Array2DRowRealMatrix( + new double[][] { + new double[] {26d, 12d, 43d, 12d}, + new double[] {17d, 10d, 30d, 17d}, + new double[] {36d, 16d, 59d, 14d} + } + ); + + RealMatrix actual = firstMatrix.multiply(secondMatrix); + + assertThat(actual).isEqualTo(expected); + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java new file mode 100644 index 0000000000..fb4a419eb0 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.matrices.colt; + +import cern.colt.matrix.DoubleFactory2D; +import cern.colt.matrix.DoubleMatrix2D; +import cern.colt.matrix.linalg.Algebra; +import org.junit.jupiter.api.Test; +import org.openjdk.jmh.annotations.*; + +import static org.assertj.core.api.Assertions.assertThat; + +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class DoubleMatrix2DUnitTest { + + @Test + @Benchmark + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense; + + DoubleMatrix2D firstMatrix = doubleFactory2D.make( + new double[][] { + new double[] {1d, 5d}, + new double[] {2d, 3d}, + new double[] {1d ,7d} + } + ); + + DoubleMatrix2D secondMatrix = doubleFactory2D.make( + new double[][] { + new double[] {1d, 2d, 3d, 7d}, + new double[] {5d, 2d, 8d, 1d} + } + ); + + DoubleMatrix2D expected = doubleFactory2D.make( + new double[][] { + new double[] {26d, 12d, 43d, 12d}, + new double[] {17d, 10d, 30d, 17d}, + new double[] {36d, 16d, 59d, 14d} + } + ); + + Algebra algebra = new Algebra(); + DoubleMatrix2D actual = algebra.mult(firstMatrix, secondMatrix); + + assertThat(actual).isEqualTo(expected); + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java new file mode 100644 index 0000000000..b025266a1d --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.matrices.ejml; + +import org.ejml.simple.SimpleMatrix; +import org.junit.jupiter.api.Test; +import org.openjdk.jmh.annotations.*; + +import static org.assertj.core.api.Assertions.assertThat; + +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class SimpleMatrixUnitTest { + + @Test + @Benchmark + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + SimpleMatrix firstMatrix = new SimpleMatrix( + new double[][] { + new double[] {1d, 5d}, + new double[] {2d, 3d}, + new double[] {1d ,7d} + } + ); + + SimpleMatrix secondMatrix = new SimpleMatrix( + new double[][] { + new double[] {1d, 2d, 3d, 7d}, + new double[] {5d, 2d, 8d, 1d} + } + ); + + SimpleMatrix expected = new SimpleMatrix( + new double[][] { + new double[] {26d, 12d, 43d, 12d}, + new double[] {17d, 10d, 30d, 17d}, + new double[] {36d, 16d, 59d, 14d} + } + ); + + SimpleMatrix actual = firstMatrix.mult(secondMatrix); + + assertThat(actual).matches(m -> m.isIdentical(expected, 0d)); + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java new file mode 100644 index 0000000000..be9e483d5b --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.matrices.homemade; + +import org.junit.jupiter.api.Test; +import org.openjdk.jmh.annotations.*; + +import static org.assertj.core.api.Assertions.assertThat; + +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class HomemadeMatrixUnitTest { + + @Test + @Benchmark + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + double[][] firstMatrix = { + new double[]{1d, 5d}, + new double[]{2d, 3d}, + new double[]{1d, 7d} + }; + + double[][] secondMatrix = { + new double[]{1d, 2d, 3d, 7d}, + new double[]{5d, 2d, 8d, 1d} + }; + + double[][] expected = { + new double[]{26d, 12d, 43d, 12d}, + new double[]{17d, 10d, 30d, 17d}, + new double[]{36d, 16d, 59d, 14d} + }; + + double[][] actual = multiplyMatrices(firstMatrix, secondMatrix); + + assertThat(actual).isEqualTo(expected); + } + + private double[][] multiplyMatrices(double[][] firstMatrix, double[][] secondMatrix) { + double[][] result = new double[firstMatrix.length][secondMatrix[0].length]; + + for (int row = 0; row < result.length; row++) { + for (int col = 0; col < result[row].length; col++) { + result[row][col] = multiplyMatricesCell(firstMatrix, secondMatrix, row, col); + } + } + + return result; + } + + private double multiplyMatricesCell(double[][] firstMatrix, double[][] secondMatrix, int row, int col) { + double cell = 0; + for (int i = 0; i < secondMatrix.length; i++) { + cell += firstMatrix[row][i] * secondMatrix[i][col]; + } + return cell; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java new file mode 100644 index 0000000000..afb84ff3db --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.matrices.la4j; + +import org.junit.jupiter.api.Test; +import org.la4j.Matrix; +import org.la4j.matrix.dense.Basic2DMatrix; +import org.openjdk.jmh.annotations.*; + +import static org.assertj.core.api.Assertions.assertThat; + +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class Basic2DMatrixUnitTest { + + @Test + @Benchmark + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + Matrix firstMatrix = new Basic2DMatrix( + new double[][]{ + new double[]{1d, 5d}, + new double[]{2d, 3d}, + new double[]{1d, 7d} + } + ); + + Matrix secondMatrix = new Basic2DMatrix( + new double[][]{ + new double[]{1d, 2d, 3d, 7d}, + new double[]{5d, 2d, 8d, 1d} + } + ); + + Matrix expected = new Basic2DMatrix( + new double[][]{ + new double[]{26d, 12d, 43d, 12d}, + new double[]{17d, 10d, 30d, 17d}, + new double[]{36d, 16d, 59d, 14d} + } + ); + + Matrix actual = firstMatrix.multiply(secondMatrix); + + assertThat(actual).isEqualTo(expected); + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java new file mode 100644 index 0000000000..fb3030bccf --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.matrices.nd4j; + +import org.junit.jupiter.api.Test; +import org.nd4j.linalg.api.ndarray.INDArray; +import org.nd4j.linalg.factory.Nd4j; +import org.openjdk.jmh.annotations.*; + +import static org.assertj.core.api.Assertions.assertThat; + +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class INDArrayUnitTest { + + @Test + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + INDArray firstMatrix = Nd4j.create( + new double[][]{ + new double[]{1d, 5d}, + new double[]{2d, 3d}, + new double[]{1d, 7d} + } + ); + + INDArray secondMatrix = Nd4j.create( + new double[][] { + new double[] {1d, 2d, 3d, 7d}, + new double[] {5d, 2d, 8d, 1d} + } + ); + + INDArray expected = Nd4j.create( + new double[][] { + new double[] {26d, 12d, 43d, 12d}, + new double[] {17d, 10d, 30d, 17d}, + new double[] {36d, 16d, 59d, 14d} + } + ); + + INDArray actual = firstMatrix.mmul(secondMatrix); + + assertThat(actual).isEqualTo(expected); + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java b/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java new file mode 100644 index 0000000000..11a295031a --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java @@ -0,0 +1,102 @@ +package com.baeldung.okhttp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.ResponseBody; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.io.InputStreamReader; + +public class ResponseDecoderUnitTest { + + @Rule public ExpectedException exceptionRule = ExpectedException.none(); + + @Rule public MockWebServer server = new MockWebServer(); + + SimpleEntity sampleResponse; + + MockResponse mockResponse; + + OkHttpClient client; + + @Before + public void setUp() { + sampleResponse = new SimpleEntity("Baeldung"); + client = new OkHttpClient.Builder().build(); + mockResponse = new MockResponse() + .setResponseCode(200) + .setHeader("Content-Type", "application/json") + .setBody(new Gson().toJson(sampleResponse)); + } + + @Test + public void givenJacksonDecoder_whenGetStringOfResponse_thenExpectSimpleEntity() throws Exception { + server.enqueue(mockResponse); + Request request = new Request.Builder() + .url(server.url("")) + .build(); + ResponseBody responseBody = client + .newCall(request) + .execute() + .body(); + + Assert.assertNotNull(responseBody); + Assert.assertNotEquals(0, responseBody.contentLength()); + + ObjectMapper objectMapper = new ObjectMapper(); + SimpleEntity entity = objectMapper.readValue(responseBody.string(), SimpleEntity.class); + + Assert.assertNotNull(entity); + Assert.assertEquals(sampleResponse.getName(), entity.getName()); + } + + @Test + public void givenGsonDecoder_whenGetByteStreamOfResponse_thenExpectSimpleEntity() throws Exception { + server.enqueue(mockResponse); + Request request = new Request.Builder() + .url(server.url("")) + .build(); + ResponseBody responseBody = client + .newCall(request) + .execute() + .body(); + + Assert.assertNotNull(responseBody); + Assert.assertNotEquals(0, responseBody.contentLength()); + + Gson gson = new Gson(); + SimpleEntity entity = gson.fromJson(new InputStreamReader(responseBody.byteStream()), SimpleEntity.class); + + Assert.assertNotNull(entity); + Assert.assertEquals(sampleResponse.getName(), entity.getName()); + } + + @Test + public void givenGsonDecoder_whenGetStringOfResponse_thenExpectSimpleEntity() throws Exception { + server.enqueue(mockResponse); + Request request = new Request.Builder() + .url(server.url("")) + .build(); + ResponseBody responseBody = client + .newCall(request) + .execute() + .body(); + + Assert.assertNotNull(responseBody); + + Gson gson = new Gson(); + SimpleEntity entity = gson.fromJson(responseBody.string(), SimpleEntity.class); + + Assert.assertNotNull(entity); + Assert.assertEquals(sampleResponse.getName(), entity.getName()); + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java b/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java new file mode 100644 index 0000000000..211e43e556 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java @@ -0,0 +1,22 @@ +package com.baeldung.okhttp; + +public class SimpleEntity { + protected String name; + + public SimpleEntity(String name) { + this.name = name; + } + + //no-arg constructor, getters and setters here + + public SimpleEntity() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java b/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java new file mode 100644 index 0000000000..adc753a8ad --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java @@ -0,0 +1,168 @@ +package com.baeldung.parallel_collectors; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +import static com.pivovarit.collectors.ParallelCollectors.parallel; +import static com.pivovarit.collectors.ParallelCollectors.parallelOrdered; +import static com.pivovarit.collectors.ParallelCollectors.parallelToCollection; +import static com.pivovarit.collectors.ParallelCollectors.parallelToList; +import static com.pivovarit.collectors.ParallelCollectors.parallelToMap; +import static com.pivovarit.collectors.ParallelCollectors.parallelToStream; + +public class ParallelCollectorsUnitTest { + + @Test + public void shouldProcessInParallelWithStreams() { + List ids = Arrays.asList(1, 2, 3); + + List results = ids.parallelStream() + .map(i -> fetchById(i)) + .collect(Collectors.toList()); + + System.out.println(results); + } + + @Test + public void shouldProcessInParallelWithParallelCollectors() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + CompletableFuture> results = ids.stream() + .collect(parallelToList(i -> fetchById(i), executor, 4)); + + System.out.println(results.join()); + } + + @Test + public void shouldCollectToList() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + List results = ids.stream() + .collect(parallelToList(i -> fetchById(i), executor, 4)) + .join(); + + System.out.println(results); // [user-1, user-2, user-3] + } + + @Test + public void shouldCollectToCollection() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + List results = ids.stream() + .collect(parallelToCollection(i -> fetchById(i), LinkedList::new, executor, 4)) + .join(); + + System.out.println(results); // [user-1, user-2, user-3] + } + + @Test + public void shouldCollectToStream() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + Map> results = ids.stream() + .collect(parallelToStream(i -> fetchById(i), executor, 4)) + .thenApply(stream -> stream.collect(Collectors.groupingBy(i -> i.length()))) + .join(); + + System.out.println(results); // [user-1, user-2, user-3] + } + + @Test + public void shouldStreamInCompletionOrder() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + ids.stream() + .collect(parallel(i -> fetchByIdWithRandomDelay(i), executor, 4)) + .forEach(System.out::println); + } + + @Test + public void shouldStreamInOriginalOrder() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + ids.stream() + .collect(parallelOrdered(i -> fetchByIdWithRandomDelay(i), executor, 4)) + .forEach(System.out::println); + } + + @Test + public void shouldCollectToMap() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + Map results = ids.stream() + .collect(parallelToMap(i -> i, i -> fetchById(i), executor, 4)) + .join(); + + System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} + } + + @Test + public void shouldCollectToTreeMap() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + Map results = ids.stream() + .collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, executor, 4)) + .join(); + + System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} + } + + @Test + public void shouldCollectToTreeMapAndResolveClashes() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + Map results = ids.stream() + .collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, (s1, s2) -> s1, executor, 4)) + .join(); + + System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} + } + + private static String fetchById(int id) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // ignore shamelessly + } + + return "user-" + id; + } + + private static String fetchByIdWithRandomDelay(int id) { + try { + Thread.sleep(ThreadLocalRandom.current().nextInt(1000)); + } catch (InterruptedException e) { + // ignore shamelessly + } + + return "user-" + id; + } +} diff --git a/libraries-2/src/test/resources/greeting.hbs b/libraries-2/src/test/resources/greeting.hbs new file mode 100644 index 0000000000..71a8266bce --- /dev/null +++ b/libraries-2/src/test/resources/greeting.hbs @@ -0,0 +1 @@ +Hi {{name}}! \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/each.html b/libraries-2/src/test/resources/handlebars/each.html new file mode 100644 index 0000000000..1570311bfc --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/each.html @@ -0,0 +1,3 @@ +{{#each friends}} +{{name}} is my friend. +{{/each}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/each_mustache.html b/libraries-2/src/test/resources/handlebars/each_mustache.html new file mode 100644 index 0000000000..1570311bfc --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/each_mustache.html @@ -0,0 +1,3 @@ +{{#each friends}} +{{name}} is my friend. +{{/each}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/greeting.html b/libraries-2/src/test/resources/handlebars/greeting.html new file mode 100644 index 0000000000..71a8266bce --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/greeting.html @@ -0,0 +1 @@ +Hi {{name}}! \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/header.html b/libraries-2/src/test/resources/handlebars/header.html new file mode 100644 index 0000000000..80cca699e4 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/header.html @@ -0,0 +1 @@ +

Hi {{name}}!

\ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/if.html b/libraries-2/src/test/resources/handlebars/if.html new file mode 100644 index 0000000000..ebdc724f66 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/if.html @@ -0,0 +1,5 @@ +{{#if busy}} +

{{name}} is busy.

+{{else}} +

{{name}} is not busy.

+{{/if}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/if_mustache.html b/libraries-2/src/test/resources/handlebars/if_mustache.html new file mode 100644 index 0000000000..d75f5fa8f9 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/if_mustache.html @@ -0,0 +1,5 @@ +{{#if busy}} +

{{name}} is busy.

+{{^}} +

{{name}} is not busy.

+{{/if}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/messagebase.html b/libraries-2/src/test/resources/handlebars/messagebase.html new file mode 100644 index 0000000000..7ee3257e06 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/messagebase.html @@ -0,0 +1,9 @@ + + +{{#block "intro"}} + This is the intro +{{/block}} +{{#block "message"}} +{{/block}} + + \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/page.html b/libraries-2/src/test/resources/handlebars/page.html new file mode 100644 index 0000000000..27b20737f3 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/page.html @@ -0,0 +1,2 @@ +{{>header}} +

This is the page {{name}}

\ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/person.html b/libraries-2/src/test/resources/handlebars/person.html new file mode 100644 index 0000000000..9df7850f60 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/person.html @@ -0,0 +1 @@ +{{#isBusy this}}{{/isBusy}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/simplemessage.html b/libraries-2/src/test/resources/handlebars/simplemessage.html new file mode 100644 index 0000000000..3b3a01980a --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/simplemessage.html @@ -0,0 +1,4 @@ +{{#partial "message" }} + Hi there! +{{/partial}} +{{> messagebase}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/with.html b/libraries-2/src/test/resources/handlebars/with.html new file mode 100644 index 0000000000..90077b4835 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/with.html @@ -0,0 +1,3 @@ +{{#with address}} +

I live in {{street}}

+{{/with}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/with_mustache.html b/libraries-2/src/test/resources/handlebars/with_mustache.html new file mode 100644 index 0000000000..3adf6a7556 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/with_mustache.html @@ -0,0 +1,3 @@ +{{#address}} +

I live in {{street}}

+{{/address}} \ No newline at end of file diff --git a/libraries-apache-commons/pom.xml b/libraries-apache-commons/pom.xml index cb5990df22..05d11d83fe 100644 --- a/libraries-apache-commons/pom.xml +++ b/libraries-apache-commons/pom.xml @@ -25,7 +25,7 @@ org.apache.commons commons-lang3 - ${commons-lang.version} + ${commons-lang3.version} org.apache.commons @@ -35,7 +35,7 @@ commons-io commons-io - ${commons.io.version} + ${commons-io.version} commons-chain @@ -87,13 +87,12 @@ - 3.6 + 3.6 1.1 1.9.3 1.2 1.4 3.6.2 - 2.5 1.6 4.1 2.0.0.0 diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 3276ebcdbb..88dcceafaa 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -263,6 +263,16 @@ org.apache.storm storm-core ${storm.version} + + + org.slf4j + slf4j-log4j12 + + + org.slf4j + log4j-over-slf4j + + @@ -439,7 +449,6 @@ 2.8.2 1.1.0 1.5.0 - 2.9.7 3.0.0 3.6.2 3.8.4 diff --git a/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java index ab7d119c16..f46fffbb59 100644 --- a/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java @@ -26,6 +26,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class BackupCreatorIntegrationTest { @@ -88,7 +89,7 @@ public class BackupCreatorIntegrationTest { SerializationSchema serializationSchema = new BackupSerializationSchema(); byte[] backupProcessed = serializationSchema.serialize(backup); - assertEquals(backupSerialized, backupProcessed); + assertArrayEquals(backupSerialized, backupProcessed); } private static class CollectingSink implements SinkFunction { diff --git a/libraries-http/README.md b/libraries-http/README.md new file mode 100644 index 0000000000..dd8c6a5f67 --- /dev/null +++ b/libraries-http/README.md @@ -0,0 +1,7 @@ + +### Relevant Articles: + +- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) +- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client) +- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client) +- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets) diff --git a/libraries-http/pom.xml b/libraries-http/pom.xml new file mode 100644 index 0000000000..6006a93aef --- /dev/null +++ b/libraries-http/pom.xml @@ -0,0 +1,81 @@ + + + + 4.0.0 + libraries-http + libraries-http + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + + + + com.google.http-client + google-http-client + ${googleclient.version} + + + com.google.http-client + google-http-client-jackson2 + ${googleclient.version} + + + com.google.http-client + google-http-client-gson + ${googleclient.version} + + + + + org.asynchttpclient + async-http-client + ${async.http.client.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + com.google.code.gson + gson + 2.8.5 + + + + com.squareup.okhttp3 + mockwebserver + ${com.squareup.okhttp3.version} + test + + + + + + 3.6.2 + 3.14.2 + 1.23.0 + 2.2.0 + + diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/User.java similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/User.java diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/logging.properties similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/logging.properties diff --git a/rest-with-spark-java/src/main/resources/logback.xml b/libraries-http/src/main/resources/logback.xml similarity index 100% rename from rest-with-spark-java/src/main/resources/logback.xml rename to libraries-http/src/main/resources/logback.xml diff --git a/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java b/libraries-http/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java rename to libraries-http/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/client/Consts.java b/libraries-http/src/test/java/com/baeldung/client/Consts.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/client/Consts.java rename to libraries-http/src/test/java/com/baeldung/client/Consts.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java b/libraries-http/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java rename to libraries-http/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java similarity index 93% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index 75980a5360..7b28c17607 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -19,6 +19,9 @@ import okhttp3.Response; import org.junit.Before; import org.junit.Test; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpFileUploadingLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java similarity index 93% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java index 3edd2eab06..5efc4aa998 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java @@ -17,6 +17,9 @@ import okhttp3.Response; import org.junit.Before; import org.junit.Test; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java similarity index 95% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java index 207ad14e71..24617794d1 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -20,6 +20,9 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpMiscLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java similarity index 94% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java index 66fee0b626..19e689c093 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -20,6 +20,9 @@ import okhttp3.Response; import org.junit.Before; import org.junit.Test; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpPostingLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java b/libraries-http/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java rename to libraries-http/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java diff --git a/libraries-io/README.md b/libraries-io/README.md new file mode 100644 index 0000000000..90095a2f23 --- /dev/null +++ b/libraries-io/README.md @@ -0,0 +1,5 @@ + +### Relevant Articles: + +- [Transferring a File Through SFTP in Java](https://www.baeldung.com/java-file-sftp) + diff --git a/libraries-io/pom.xml b/libraries-io/pom.xml new file mode 100644 index 0000000000..5b78ae9442 --- /dev/null +++ b/libraries-io/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + libraries-io + libraries-io + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + com.jcraft + jsch + ${jsch.version} + + + com.hierynomus + sshj + ${sshj.version} + + + org.apache.commons + commons-vfs2 + ${vfs.version} + + + + + + 0.1.55 + 0.27.0 + 2.4 + + diff --git a/libraries-io/src/main/resources/input.txt b/libraries-io/src/main/resources/input.txt new file mode 100644 index 0000000000..a10db923e5 --- /dev/null +++ b/libraries-io/src/main/resources/input.txt @@ -0,0 +1 @@ +This is a sample text content \ No newline at end of file diff --git a/libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java b/libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java new file mode 100644 index 0000000000..192153bc90 --- /dev/null +++ b/libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java @@ -0,0 +1,106 @@ +package org.baeldung.java.io.remote; + +import java.io.IOException; + +import org.apache.commons.vfs2.FileObject; +import org.apache.commons.vfs2.FileSystemManager; +import org.apache.commons.vfs2.Selectors; +import org.apache.commons.vfs2.VFS; +import org.junit.Test; + +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.Session; +import com.jcraft.jsch.SftpException; + +import net.schmizz.sshj.SSHClient; +import net.schmizz.sshj.sftp.SFTPClient; +import net.schmizz.sshj.transport.verification.PromiscuousVerifier; + +public class SftpFileTransferLiveTest { + + private String remoteHost = "HOST_NAME_HERE"; + private String username = "USERNAME_HERE"; + private String password = "PASSWORD_HERE"; + private String localFile = "src/main/resources/input.txt"; + private String remoteFile = "welcome.txt"; + private String localDir = "src/main/resources/"; + private String remoteDir = "remote_sftp_test/"; + private String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample"; + + @Test + public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException { + ChannelSftp channelSftp = setupJsch(); + channelSftp.connect(); + channelSftp.put(localFile, remoteDir + "jschFile.txt"); + channelSftp.exit(); + } + + @Test + public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException { + ChannelSftp channelSftp = setupJsch(); + channelSftp.connect(); + channelSftp.get(remoteFile, localDir + "jschFile.txt"); + channelSftp.exit(); + } + + @Test + public void whenUploadFileUsingSshj_thenSuccess() throws IOException { + SSHClient sshClient = setupSshj(); + SFTPClient sftpClient = sshClient.newSFTPClient(); + sftpClient.put(localFile, remoteDir + "sshjFile.txt"); + sftpClient.close(); + sshClient.disconnect(); + } + + @Test + public void whenDownloadFileUsingSshj_thenSuccess() throws IOException { + SSHClient sshClient = setupSshj(); + SFTPClient sftpClient = sshClient.newSFTPClient(); + sftpClient.get(remoteFile, localDir + "sshjFile.txt"); + sftpClient.close(); + sshClient.disconnect(); + } + + @Test + public void whenUploadFileUsingApacheVfs_thenSuccess() throws IOException { + FileSystemManager manager = VFS.getManager(); + FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localFile); + FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt"); + remote.copyFrom(local, Selectors.SELECT_SELF); + local.close(); + remote.close(); + } + + @Test + public void whenDownloadFileUsingApacheVfs_thenSuccess() throws IOException { + FileSystemManager manager = VFS.getManager(); + FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt"); + FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile); + local.copyFrom(remote, Selectors.SELECT_SELF); + local.close(); + remote.close(); + } + + // ====== ssh-keyscan -H -t rsa remoteHost >> known_hosts_sample + + private ChannelSftp setupJsch() throws JSchException { + JSch jsch = new JSch(); + jsch.setKnownHosts(knownHostsFileLoc); + Session jschSession = jsch.getSession(username, remoteHost); + jschSession.setPassword(password); + //jschSession.setConfig("StrictHostKeyChecking", "no"); + jschSession.connect(); + return (ChannelSftp) jschSession.openChannel("sftp"); + } + + private SSHClient setupSshj() throws IOException { + SSHClient client = new SSHClient(); + client.addHostKeyVerifier(new PromiscuousVerifier()); + client.connect(remoteHost); + client.authPassword(username, password); + return client; + } + +} diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index a6ead8fb31..9bed5e211b 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -52,7 +52,7 @@ commons-io commons-io - ${commons.io.version} + ${commons-io.version} io.netty @@ -65,7 +65,7 @@ ${junit.version} test - + org.apache.tomcat @@ -96,18 +96,31 @@ smack-java7 ${smack.version} + + + + org.nanohttpd + nanohttpd + ${nanohttpd.version} + + + org.nanohttpd + nanohttpd-nanolets + ${nanohttpd.version} + + 3.6.2 4.5.3 - 2.5 9.4.8.v20171121 4.1.20.Final 4.1 8.5.24 4.3.1 - 1.2.0 + 1.2.0 + 2.3.1 \ No newline at end of file diff --git a/libraries-server/src/main/java/com/baeldung/nanohttpd/ApplicationController.java b/libraries-server/src/main/java/com/baeldung/nanohttpd/ApplicationController.java new file mode 100644 index 0000000000..2fa54c3ae2 --- /dev/null +++ b/libraries-server/src/main/java/com/baeldung/nanohttpd/ApplicationController.java @@ -0,0 +1,38 @@ +package com.baeldung.nanohttpd; + +import fi.iki.elonen.NanoHTTPD; +import fi.iki.elonen.router.RouterNanoHTTPD; + +import java.io.IOException; + +public class ApplicationController extends RouterNanoHTTPD { + + ApplicationController() throws IOException { + super(8072); + addMappings(); + start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); + } + + @Override + public void addMappings() { + addRoute("/", IndexHandler.class); + addRoute("/users", UserHandler.class); + } + + public static class UserHandler extends DefaultHandler { + @Override + public String getText() { + return "UserA, UserB, UserC"; + } + + @Override + public String getMimeType() { + return MIME_PLAINTEXT; + } + + @Override + public Response.IStatus getStatus() { + return Response.Status.OK; + } + } +} \ No newline at end of file diff --git a/libraries-server/src/main/java/com/baeldung/nanohttpd/ItemGetController.java b/libraries-server/src/main/java/com/baeldung/nanohttpd/ItemGetController.java new file mode 100644 index 0000000000..4a9c48fbfd --- /dev/null +++ b/libraries-server/src/main/java/com/baeldung/nanohttpd/ItemGetController.java @@ -0,0 +1,22 @@ +package com.baeldung.nanohttpd; + +import fi.iki.elonen.NanoHTTPD; + +import java.io.IOException; + +public class ItemGetController extends NanoHTTPD { + + ItemGetController() throws IOException { + super(8071); + start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); + } + + @Override + public Response serve(IHTTPSession session) { + if (session.getMethod() == Method.GET) { + String itemIdRequestParam = session.getParameters().get("itemId").get(0); + return newFixedLengthResponse("Requested itemId = " + itemIdRequestParam); + } + return newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "The requested resource does not exist"); + } +} \ No newline at end of file diff --git a/libraries-server/src/test/java/com/baeldung/nanohttpd/ApplicationControllerUnitTest.java b/libraries-server/src/test/java/com/baeldung/nanohttpd/ApplicationControllerUnitTest.java new file mode 100644 index 0000000000..003f6ee3b7 --- /dev/null +++ b/libraries-server/src/test/java/com/baeldung/nanohttpd/ApplicationControllerUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.nanohttpd; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.*; + +public class ApplicationControllerUnitTest { + + private static final String BASE_URL = "http://localhost:8072/"; + private static final HttpClient CLIENT = HttpClientBuilder.create().build(); + + @BeforeClass + public static void setUp() throws IOException { + new ApplicationController(); + } + + @Test + public void givenServer_whenRootRouteRequested_thenHelloWorldReturned() throws IOException { + HttpResponse response = CLIENT.execute(new HttpGet(BASE_URL)); + assertTrue(IOUtils.toString(response.getEntity().getContent()).contains("Hello world!")); + assertEquals(200, response.getStatusLine().getStatusCode()); + } + + @Test + public void givenServer_whenUsersRequested_thenThenAllUsersReturned() throws IOException { + HttpResponse response = CLIENT.execute(new HttpGet(BASE_URL + "users")); + assertEquals("UserA, UserB, UserC", IOUtils.toString(response.getEntity().getContent())); + } +} \ No newline at end of file diff --git a/libraries-server/src/test/java/com/baeldung/nanohttpd/ItemGetControllerUnitTest.java b/libraries-server/src/test/java/com/baeldung/nanohttpd/ItemGetControllerUnitTest.java new file mode 100644 index 0000000000..3a4f0a4d98 --- /dev/null +++ b/libraries-server/src/test/java/com/baeldung/nanohttpd/ItemGetControllerUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.nanohttpd; + +import static org.junit.Assert.*; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.IOException; + +public class ItemGetControllerUnitTest { + + private static final String URL = "http://localhost:8071"; + private static final HttpClient CLIENT = HttpClientBuilder.create().build(); + + @BeforeClass + public static void setUp() throws IOException { + new ItemGetController(); + } + + @Test + public void givenServer_whenDoingGet_thenParamIsReadCorrectly() throws IOException { + HttpResponse response = CLIENT.execute(new HttpGet(URL + "?itemId=1234")); + assertEquals("Requested itemId = 1234", IOUtils.toString(response.getEntity().getContent())); + } + + @Test + public void givenServer_whenDoingPost_then404IsReturned() throws IOException { + HttpResponse response = CLIENT.execute(new HttpPost(URL)); + assertEquals(404, response.getStatusLine().getStatusCode()); + } +} \ No newline at end of file diff --git a/libraries/README.md b/libraries/README.md index f6a39daef1..c7b40e3c94 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -36,16 +36,12 @@ - [Introduction To Docx4J](http://www.baeldung.com/docx4j) - [Introduction to StreamEx](http://www.baeldung.com/streamex) - [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) -- [A 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) - [A Docker Guide for Java](http://www.baeldung.com/docker-java-api) - [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) - [Introduction to Smooks](http://www.baeldung.com/smooks) -- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets) - [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan) -- [Introduction to OpenCSV](http://www.baeldung.com/opencsv) - [A Guide to Unirest](http://www.baeldung.com/unirest) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy) diff --git a/libraries/pom.xml b/libraries/pom.xml index 7823732224..e8ffde5f99 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -18,20 +18,12 @@ akka-actor_2.12 ${typesafe-akka.version} - com.typesafe.akka akka-testkit_2.12 ${typesafe-akka.version} test - - - - org.asynchttpclient - async-http-client - ${async.http.client.version} - org.beykery @@ -53,7 +45,7 @@ org.apache.commons commons-lang3 - ${commons-lang.version} + ${commons-lang3.version} commons-net @@ -826,7 +818,6 @@ 0.1.0 0.7.0 3.2.7 - 3.6 1.9.2 1.2 3.21.0-GA @@ -834,11 +825,10 @@ 1.5.0 3.1.0 4.5.3 - 1.4.196 1.0 + 4.5.3 - 2.9.7 2.92 1.9.26 1.41.0 @@ -871,7 +861,6 @@ 2.0.0 1.7.0 3.0.14 - 2.2.0 9.1.5.Final 4.1 1.4.9 diff --git a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java index 209bed35f0..f885ff13b3 100644 --- a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java +++ b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java @@ -59,5 +59,6 @@ class FtpClient { void downloadFile(String source, String destination) throws IOException { FileOutputStream out = new FileOutputStream(destination); ftp.retrieveFile(source, out); + out.close(); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java index fc7067520d..3201908bf7 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java @@ -28,7 +28,7 @@ public class AdderMethodDirtiesContextIntegrationTest { @Test public void _1_givenNumber_whenAdd_thenSumWrong() { adderServiceSteps.whenAdd(); - adderServiceSteps.sumWrong(); + adderServiceSteps.summedUp(); } @Rule diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index ae658e034e..ce58f43e4e 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -101,7 +101,6 @@ 2.7 3.3.6 3.3.0.Final - 2.4
diff --git a/logging-modules/log4j2/pom.xml b/logging-modules/log4j2/pom.xml index 14420356de..db0c6eb659 100644 --- a/logging-modules/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -78,7 +78,7 @@ - integration + integration-lite-first diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java index 020aaafc74..e340ebb784 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java @@ -23,7 +23,7 @@ public class MapAppenderIntegrationTest { @Test public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception { - logger.info("Test from {}", this.getClass() + logger.error("Error log message from {}", this.getClass() .getSimpleName()); LoggerContext context = LoggerContext.getContext(false); Configuration config = context.getConfiguration(); diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java index 5ac82a74d8..604c45be3b 100644 --- a/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java @@ -13,9 +13,9 @@ public class GetterLazy { private static final String DELIMETER = ","; @Getter(lazy = true) - private final Map transactions = readTxnsFromFile(); + private final Map transactions = getTransactions(); - private Map readTxnsFromFile() { + private Map getTransactions() { final Map cache = new HashMap<>(); List txnRows = readTxnListFromFile(); diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/Utility.java b/lombok/src/main/java/com/baeldung/lombok/intro/Utility.java new file mode 100644 index 0000000000..07198d2ffc --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/intro/Utility.java @@ -0,0 +1,26 @@ +package com.baeldung.lombok.intro; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.stream.Collectors; + +import lombok.SneakyThrows; +import lombok.Synchronized; + +public class Utility { + + @SneakyThrows + public String resourceAsString() throws IOException { + try (InputStream is = this.getClass().getResourceAsStream("sure_in_my_jar.txt")) { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); + return br.lines().collect(Collectors.joining("\n")); + } + } + + @Synchronized + public void putValueInCache(String key, String value) { + System.out.println("Thread safe here with key : [" + key + "] and value[" + value + "]"); + } +} diff --git a/lombok/src/main/resources/sure_in_my_jar.txt b/lombok/src/main/resources/sure_in_my_jar.txt new file mode 100644 index 0000000000..5ab2f8a432 --- /dev/null +++ b/lombok/src/main/resources/sure_in_my_jar.txt @@ -0,0 +1 @@ +Hello \ No newline at end of file diff --git a/maven-java-11/multimodule-maven-project/daomodule/pom.xml b/maven-java-11/multimodule-maven-project/daomodule/pom.xml index de9be656d4..5520c5a90a 100644 --- a/maven-java-11/multimodule-maven-project/daomodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/daomodule/pom.xml @@ -1,14 +1,15 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.daomodule daomodule jar 1.0 daomodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml b/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml index 8e700e62b5..747722e912 100644 --- a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml @@ -1,16 +1,18 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.entitymodule entitymodule jar 1.0 entitymodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + + 11 11 diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml index d2c94527f1..3e5ec122ff 100644 --- a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml @@ -1,16 +1,17 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.mainappmodule mainappmodule 1.0 jar mainappmodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + diff --git a/maven-java-11/multimodule-maven-project/pom.xml b/maven-java-11/multimodule-maven-project/pom.xml index f22541738c..7e2eb0dd7b 100644 --- a/maven-java-11/multimodule-maven-project/pom.xml +++ b/maven-java-11/multimodule-maven-project/pom.xml @@ -6,12 +6,20 @@ 1.0 pom multimodule-maven-project + com.baeldung.maven-java-11 maven-java-11 1.0 + + entitymodule + daomodule + userdaomodule + mainappmodule + + @@ -45,13 +53,6 @@ - - entitymodule - daomodule - userdaomodule - mainappmodule - - UTF-8 diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml index b4fe7f0398..68e7ae9b82 100644 --- a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml @@ -1,16 +1,18 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.userdaomodule userdaomodule 1.0 jar userdaomodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + + com.baeldung.entitymodule diff --git a/maven-java-11/pom.xml b/maven-java-11/pom.xml index ff95840523..5ae4c00892 100644 --- a/maven-java-11/pom.xml +++ b/maven-java-11/pom.xml @@ -6,14 +6,17 @@ 1.0 pom maven-java-11 + - parent-modules - com.baeldung - 1.0.0-SNAPSHOT + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + multimodule-maven-project + UTF-8 11 diff --git a/maven-polyglot/maven-polyglot-json-app/pom.json b/maven-polyglot/maven-polyglot-json-app/pom.json index abd58f3127..3e809b7b83 100644 --- a/maven-polyglot/maven-polyglot-json-app/pom.json +++ b/maven-polyglot/maven-polyglot-json-app/pom.json @@ -5,10 +5,10 @@ "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 + "groupId": "com.baeldung", + "artifactId": "parent-boot-2", + "version": "0.0.1-SNAPSHOT", + "relativePath": "../../parent-boot-2" }, "properties": { "project.build.sourceEncoding": "UTF-8", diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml index 5b18529ec5..1170fe7aa6 100644 --- a/maven-polyglot/maven-polyglot-json-extension/pom.xml +++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -8,17 +8,24 @@ 1.0-SNAPSHOT maven-polyglot-json-extension + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../.. + + org.apache.maven maven-core - 3.5.4 + ${maven-core.version} provided com.fasterxml.jackson.core jackson-databind - 2.9.6 + ${jackson.version} @@ -42,6 +49,7 @@ 1.8 1.8 + 3.5.4 \ 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 index 445e2eec3b..393f7e9e15 100644 --- a/maven-polyglot/maven-polyglot-yml-app/pom.yml +++ b/maven-polyglot/maven-polyglot-yml-app/pom.yml @@ -4,4 +4,10 @@ artifactId: maven-polyglot-yml-app version: 1.0-SNAPSHOT name: 'YAML Demo' +parent: + groupId: "com.baeldung" + artifactId: "parent-modules" + version: "1.0.0-SNAPSHOT" + relativePath: "../.." + properties: {maven.compiler.source: 1.8, maven.compiler.target: 1.8} \ No newline at end of file diff --git a/maven/pom.xml b/maven/pom.xml index 942bf683e2..ef6e7b7d93 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -4,12 +4,19 @@ com.baeldung maven 0.0.1-SNAPSHOT + maven + pom + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + custom-rule maven-enforcer - maven - pom @@ -292,7 +299,6 @@ - 1.8 3.0.2 3.8.0 2.22.0 @@ -303,6 +309,5 @@ Baeldung 9.4.11.v20180605 2.27 - 4.12 \ No newline at end of file diff --git a/maven/versions-maven-plugin/original/pom.xml b/maven/versions-maven-plugin/original/pom.xml index 7608e4d168..df8ee9a20e 100644 --- a/maven/versions-maven-plugin/original/pom.xml +++ b/maven/versions-maven-plugin/original/pom.xml @@ -11,19 +11,19 @@ commons-io commons-io - 2.3 + ${commons-io.version} org.apache.commons commons-collections4 - 4.0 + ${commons-collections4.version} org.apache.commons commons-lang3 - 3.0 + ${commons-lang3.version} @@ -35,7 +35,7 @@ commons-beanutils commons-beanutils - 1.9.1-SNAPSHOT + ${commons-beanutils.version} @@ -71,6 +71,10 @@ 1.15 + 2.3 + 4.0 + 3.0 + 1.9.1 \ No newline at end of file diff --git a/maven/versions-maven-plugin/pom.xml b/maven/versions-maven-plugin/pom.xml index dc0cba75f9..e0714bf0e0 100644 --- a/maven/versions-maven-plugin/pom.xml +++ b/maven/versions-maven-plugin/pom.xml @@ -6,10 +6,6 @@ versions-maven-plugin 0.0.1-SNAPSHOT versions-maven-plugin - - - 1.15 - @@ -73,5 +69,9 @@ + + + 1.15 + \ No newline at end of file diff --git a/msf4j/pom.xml b/msf4j/pom.xml index 4a6f63159d..2a862ac289 100644 --- a/msf4j/pom.xml +++ b/msf4j/pom.xml @@ -23,6 +23,7 @@ + org.wso2.msf4j diff --git a/oauth2-framework-impl/oauth2-authorization-server/pom.xml b/oauth2-framework-impl/oauth2-authorization-server/pom.xml new file mode 100644 index 0000000000..8db2150558 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + oauth2-authorization-server + war + + + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + + + + 1.4.199 + 9080 + 9443 + + + + + com.nimbusds + nimbus-jose-jwt + 7.3 + + + org.bouncycastle + bcprov-jdk15on + 1.62 + + + org.bouncycastle + bcpkix-jdk15on + 1.62 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-h2-dependency + package + + copy + + + + + + + com.h2database + h2 + ${h2.version} + jar + ${project.build.directory}/liberty/wlp/usr/shared/resources/ + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java new file mode 100644 index 0000000000..62d6b04464 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java @@ -0,0 +1,8 @@ +package com.baeldung.oauth2.authorization.server; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/") +public class OAuth2ServerApplication extends Application { +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java new file mode 100644 index 0000000000..dab57b91a7 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java @@ -0,0 +1,17 @@ +package com.baeldung.oauth2.authorization.server; + +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static java.lang.Thread.currentThread; + + +public class PEMKeyUtils { + + public static String readKeyAsString(String keyLocation) throws Exception { + URI uri = currentThread().getContextClassLoader().getResource(keyLocation).toURI(); + byte[] byteArray = Files.readAllBytes(Paths.get(uri)); + return new String(byteArray); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java new file mode 100644 index 0000000000..10e78a2dfd --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java @@ -0,0 +1,185 @@ +package com.baeldung.oauth2.authorization.server.api; + +import com.baeldung.oauth2.authorization.server.handler.AuthorizationGrantTypeHandler; +import com.baeldung.oauth2.authorization.server.model.AppDataRepository; +import com.baeldung.oauth2.authorization.server.model.AuthorizationCode; +import com.baeldung.oauth2.authorization.server.model.Client; +import com.baeldung.oauth2.authorization.server.model.User; + +import javax.annotation.security.RolesAllowed; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Instance; +import javax.enterprise.inject.literal.NamedLiteral; +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.security.enterprise.SecurityContext; +import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.*; +import java.io.IOException; +import java.net.URI; +import java.security.Principal; +import java.time.LocalDateTime; +import java.util.*; + +@FormAuthenticationMechanismDefinition( + loginToContinue = @LoginToContinue(loginPage = "/login.jsp", errorPage = "/login.jsp") +) +@RolesAllowed("USER") +@RequestScoped +@Path("authorize") +public class AuthorizationEndpoint { + + @Inject + private SecurityContext securityContext; + + @Inject + private AppDataRepository appDataRepository; + + @Inject + Instance authorizationGrantTypeHandlers; + + @GET + @Produces(MediaType.TEXT_HTML) + public Response doGet(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @Context UriInfo uriInfo) throws ServletException, IOException { + MultivaluedMap params = uriInfo.getQueryParameters(); + Principal principal = securityContext.getCallerPrincipal(); + + //error about redirect_uri && client_id ==> forward user, thus to error.jsp. + //otherwise ==> sendRedirect redirect_uri?error=error&error_description=error_description + //1. client_id + String clientId = params.getFirst("client_id"); + if (clientId == null || clientId.isEmpty()) { + return informUserAboutError(request, response, "Invalid client_id :" + clientId); + } + Client client = appDataRepository.getClient(clientId); + if (client == null) { + return informUserAboutError(request, response, "Invalid client_id :" + clientId); + } + //2. Client Authorized Grant Type + String clientError = ""; + if (client.getAuthorizedGrantTypes() != null && !client.getAuthorizedGrantTypes().contains("authorization_code")) { + return informUserAboutError(request, response, "Authorization Grant type, authorization_code, is not allowed for this client :" + clientId); + } + + //3. redirectUri + String redirectUri = params.getFirst("redirect_uri"); + if (client.getRedirectUri() != null && !client.getRedirectUri().isEmpty()) { + if (redirectUri != null && !redirectUri.isEmpty() && !client.getRedirectUri().equals(redirectUri)) { + //sould be in the client.redirectUri + return informUserAboutError(request, response, "redirect_uri is pre-registred and should match"); + } + redirectUri = client.getRedirectUri(); + params.putSingle("resolved_redirect_uri", redirectUri); + } else { + if (redirectUri == null || redirectUri.isEmpty()) { + return informUserAboutError(request, response, "redirect_uri is not pre-registred and should be provided"); + } + params.putSingle("resolved_redirect_uri", redirectUri); + } + request.setAttribute("client", client); + + //4. response_type + String responseType = params.getFirst("response_type"); + if (!"code".equals(responseType) && !"token".equals(responseType)) { + //error = "invalid_grant :" + responseType + ", response_type params should be code or token:"; + //return informUserAboutError(error); + } + + //Save params in session + request.getSession().setAttribute("ORIGINAL_PARAMS", params); + + //4.scope: Optional + String requestedScope = request.getParameter("scope"); + if (requestedScope == null || requestedScope.isEmpty()) { + requestedScope = client.getScope(); + } + User user = appDataRepository.getUser(principal.getName()); + String allowedScopes = checkUserScopes(user.getScopes(), requestedScope); + request.setAttribute("scopes", allowedScopes); + + request.getRequestDispatcher("/authorize.jsp").forward(request, response); + return null; + } + + @POST + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Produces(MediaType.TEXT_HTML) + public Response doPost(@Context HttpServletRequest request, + @Context HttpServletResponse response, + MultivaluedMap params) throws Exception { + MultivaluedMap originalParams = (MultivaluedMap) request.getSession().getAttribute("ORIGINAL_PARAMS"); + if (originalParams == null) { + return informUserAboutError(request, response, "No pending authorization request."); + } + String redirectUri = originalParams.getFirst("resolved_redirect_uri"); + StringBuilder sb = new StringBuilder(redirectUri); + + String approbationStatus = params.getFirst("approbation_status"); + if ("NO".equals(approbationStatus)) { + URI location = UriBuilder.fromUri(sb.toString()) + .queryParam("error", "User doesn't approved the request.") + .queryParam("error_description", "User doesn't approved the request.") + .build(); + return Response.seeOther(location).build(); + } + //==> YES + List approvedScopes = params.get("scope"); + if (approvedScopes == null || approvedScopes.isEmpty()) { + URI location = UriBuilder.fromUri(sb.toString()) + .queryParam("error", "User doesn't approved the request.") + .queryParam("error_description", "User doesn't approved the request.") + .build(); + return Response.seeOther(location).build(); + } + + String responseType = originalParams.getFirst("response_type"); + String clientId = originalParams.getFirst("client_id"); + if ("code".equals(responseType)) { + String userId = securityContext.getCallerPrincipal().getName(); + AuthorizationCode authorizationCode = new AuthorizationCode(); + authorizationCode.setClientId(clientId); + authorizationCode.setUserId(userId); + authorizationCode.setApprovedScopes(String.join(" ", approvedScopes)); + authorizationCode.setExpirationDate(LocalDateTime.now().plusMinutes(10)); + authorizationCode.setRedirectUri(redirectUri); + appDataRepository.save(authorizationCode); + String code = authorizationCode.getCode(); + sb.append("?code=").append(code); + } else { + //Implicit: responseType=token + AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of("implicit")).get(); + JsonObject tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); + sb.append("#access_token=").append(tokenResponse.getString("access_token")) + .append("&token_type=").append(tokenResponse.getString("token_type")) + .append("&scope=").append(tokenResponse.getString("scope")); + } + String state = originalParams.getFirst("state"); + if (state != null) { + sb.append("&state=").append(state); + } + return Response.seeOther(UriBuilder.fromUri(sb.toString()).build()).build(); + } + + private String checkUserScopes(String userScopes, String requestedScope) { + Set allowedScopes = new LinkedHashSet<>(); + Set rScopes = new HashSet(Arrays.asList(requestedScope.split(" "))); + Set uScopes = new HashSet(Arrays.asList(userScopes.split(" "))); + for (String scope : uScopes) { + if (rScopes.contains(scope)) allowedScopes.add(scope); + } + return String.join(" ", allowedScopes); + } + + private Response informUserAboutError(HttpServletRequest request, HttpServletResponse response, String error) throws ServletException, IOException { + request.setAttribute("error", error); + request.getRequestDispatcher("/error.jsp").forward(request, response); + return null; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java new file mode 100644 index 0000000000..9d38c823b9 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java @@ -0,0 +1,38 @@ +package com.baeldung.oauth2.authorization.server.api; + +import com.baeldung.oauth2.authorization.server.PEMKeyUtils; +import com.nimbusds.jose.jwk.JWK; +import org.eclipse.microprofile.config.Config; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Arrays; + +@Path("jwk") +@ApplicationScoped +public class JWKEndpoint { + + @Inject + private Config config; + + @GET + public Response getKey(@QueryParam("format") String format) throws Exception { + if (format != null && !Arrays.asList("jwk", "pem").contains(format)) { + return Response.status(Response.Status.BAD_REQUEST).entity("Public Key Format should be : jwk or pem").build(); + } + String verificationkey = config.getValue("verificationkey", String.class); + String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey); + if (format == null || format.equals("jwk")) { + JWK jwk = JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey); + return Response.ok(jwk.toJSONString()).type(MediaType.APPLICATION_JSON).build(); + } else if (format.equals("pem")) { + return Response.ok(pemEncodedRSAPublicKey).build(); + } + return null; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java new file mode 100644 index 0000000000..f39bb2ea2d --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java @@ -0,0 +1,86 @@ +package com.baeldung.oauth2.authorization.server.api; + +import com.baeldung.oauth2.authorization.server.handler.AuthorizationGrantTypeHandler; +import com.baeldung.oauth2.authorization.server.model.AppDataRepository; +import com.baeldung.oauth2.authorization.server.model.Client; +import com.nimbusds.jose.JOSEException; + +import javax.enterprise.inject.Instance; +import javax.enterprise.inject.literal.NamedLiteral; +import javax.inject.Inject; +import javax.json.Json; +import javax.json.JsonObject; +import javax.ws.rs.*; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +@Path("token") +public class TokenEndpoint { + + List supportedGrantTypes = Collections.singletonList("authorization_code"); + + @Inject + private AppDataRepository appDataRepository; + + @Inject + Instance authorizationGrantTypeHandlers; + + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + public Response token(MultivaluedMap params, + @HeaderParam(HttpHeaders.AUTHORIZATION) String authHeader) throws JOSEException { + + //Check grant_type params + String grantType = params.getFirst("grant_type"); + Objects.requireNonNull(grantType, "grant_type params is required"); + if (!supportedGrantTypes.contains(grantType)) { + JsonObject error = Json.createObjectBuilder() + .add("error", "unsupported_grant_type") + .add("error_description", "grant type should be one of :" + supportedGrantTypes) + .build(); + return Response.status(Response.Status.BAD_REQUEST) + .entity(error).build(); + + } + + //Client Authentication + String[] clientCredentials = extract(authHeader); + String clientId = clientCredentials[0]; + String clientSecret = clientCredentials[1]; + Client client = appDataRepository.getClient(clientId); + if (client == null || clientSecret == null || !clientSecret.equals(client.getClientSecret())) { + JsonObject error = Json.createObjectBuilder() + .add("error", "invalid_client") + .build(); + return Response.status(Response.Status.UNAUTHORIZED) + .entity(error).build(); + } + + AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); + JsonObject tokenResponse = null; + try { + tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); + } catch (Exception e) { + e.printStackTrace(); + } + + return Response.ok(tokenResponse) + .header("Cache-Control", "no-store") + .header("Pragma", "no-cache") + .build(); + } + + private String[] extract(String authHeader) { + if (authHeader != null && authHeader.startsWith("Basic ")) { + return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":"); + } + return null; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java new file mode 100644 index 0000000000..889c7fcea2 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java @@ -0,0 +1,99 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import com.baeldung.oauth2.authorization.server.PEMKeyUtils; +import com.baeldung.oauth2.authorization.server.model.AuthorizationCode; +import com.nimbusds.jose.JOSEObjectType; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.jwk.JWK; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.json.Json; +import javax.json.JsonObject; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MultivaluedMap; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Date; +import java.util.UUID; + +@Named("authorization_code") +public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantTypeHandler { + + @PersistenceContext + private EntityManager entityManager; + + @Inject + private Config config; + + @Override + public JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception { + //1. code is required + String code = params.getFirst("code"); + if (code == null || "".equals(code)) { + throw new WebApplicationException("invalid_grant"); + } + AuthorizationCode authorizationCode = entityManager.find(AuthorizationCode.class, code); + if (!authorizationCode.getExpirationDate().isAfter(LocalDateTime.now())) { + throw new WebApplicationException("code Expired !"); + } + String redirectUri = params.getFirst("redirect_uri"); + //redirecturi match + if (authorizationCode.getRedirectUri() != null && !authorizationCode.getRedirectUri().equals(redirectUri)) { + //redirectUri params should be the same as the requested redirectUri. + throw new WebApplicationException("invalid_grant"); + } + //client match + if (!clientId.equals(authorizationCode.getClientId())) { + throw new WebApplicationException("invalid_grant"); + } + + //JWT Header + JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); + + Instant now = Instant.now(); + Long expiresInMin = 30L; + Date expiresIn = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES)); + + //3. JWT Payload or claims + JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() + .issuer("http://localhost:9080") + .subject(authorizationCode.getUserId()) + .claim("upn", authorizationCode.getUserId()) + .audience("http://localhost:9280") + .claim("scope", authorizationCode.getApprovedScopes()) + .claim("groups", Arrays.asList(authorizationCode.getApprovedScopes().split(" "))) + .expirationTime(expiresIn) // expires in 30 minutes + .notBeforeTime(Date.from(now)) + .issueTime(Date.from(now)) + .jwtID(UUID.randomUUID().toString()) + .build(); + SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); + + //4. Signing + String signingkey = config.getValue("signingkey", String.class); + String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey); + RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey); + signedJWT.sign(new RSASSASigner(rsaKey.toRSAPrivateKey())); + + //5. Finally the JWT access token + String accessToken = signedJWT.serialize(); + + return Json.createObjectBuilder() + .add("token_type", "Bearer") + .add("access_token", accessToken) + .add("expires_in", expiresInMin * 60) + .add("scope", authorizationCode.getApprovedScopes()) + .build(); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java new file mode 100644 index 0000000000..a5afe293ef --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java @@ -0,0 +1,8 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import javax.json.JsonObject; +import javax.ws.rs.core.MultivaluedMap; + +public interface AuthorizationGrantTypeHandler { + JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception; +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java new file mode 100644 index 0000000000..6b827d6a3d --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java @@ -0,0 +1,27 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.transaction.Transactional; + +@ApplicationScoped +public class AppDataRepository { + + @PersistenceContext + private EntityManager entityManager; + + public Client getClient(String clientId) { + return entityManager.find(Client.class, clientId); + } + + public User getUser(String userId) { + return entityManager.find(User.class, userId); + } + + @Transactional + public AuthorizationCode save(AuthorizationCode authorizationCode) { + entityManager.persist(authorizationCode); + return authorizationCode; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java new file mode 100644 index 0000000000..a2ec088eb9 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java @@ -0,0 +1,73 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Entity +@Table(name = "authorization_code") +public class AuthorizationCode { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "code") + private String code; + @Column(name = "client_id") + private String clientId; + @Column(name = "user_id") + private String userId; + @Column(name = "approved_scopes") + private String approvedScopes; + + @Column(name = "redirect_uri") + private String redirectUri; + + @Column(name = "expiration_date") + private LocalDateTime expirationDate; + + public String getUserId() { + return userId; + } + + public void setUserId(String username) { + this.userId = username; + } + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getApprovedScopes() { + return approvedScopes; + } + + public void setApprovedScopes(String approvedScopes) { + this.approvedScopes = approvedScopes; + } + + public String getRedirectUri() { + return redirectUri; + } + + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } + + public LocalDateTime getExpirationDate() { + return expirationDate; + } + + public void setExpirationDate(LocalDateTime expirationDate) { + this.expirationDate = expirationDate; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java new file mode 100644 index 0000000000..9b5ad2f904 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java @@ -0,0 +1,62 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "clients") +public class Client { + @Id + @Column(name = "client_id") + private String clientId; + @Column(name = "client_secret") + private String clientSecret; + @Column(name = "redirect_uri") + private String redirectUri; + @Column(name = "scope") + private String scope; + @Column(name = "authorized_grant_types") + private String authorizedGrantTypes; + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public String getRedirectUri() { + return redirectUri; + } + + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + public String getAuthorizedGrantTypes() { + return authorizedGrantTypes; + } + + public void setAuthorizedGrantTypes(String authorizedGrantTypes) { + this.authorizedGrantTypes = authorizedGrantTypes; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java new file mode 100644 index 0000000000..b3821715f4 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java @@ -0,0 +1,58 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.security.Principal; + +@Entity +@Table(name = "users") +public class User implements Principal { + @Id + @Column(name = "user_id") + private String userId; + @Column(name = "password") + private String password; + @Column(name = "roles") + private String roles; + @Column(name = "scopes") + private String scopes; + + public String getUserId() { + return userId; + } + + public void setUserId(String username) { + this.userId = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getRoles() { + return roles; + } + + public void setRoles(String roles) { + this.roles = roles; + } + + public String getScopes() { + return scopes; + } + + public void setScopes(String scopes) { + this.scopes = scopes; + } + + @Override + public String getName() { + return getUserId(); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java new file mode 100644 index 0000000000..a32ab32cd4 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java @@ -0,0 +1,37 @@ +package com.baeldung.oauth2.authorization.server.security; + +import com.baeldung.oauth2.authorization.server.model.AppDataRepository; +import com.baeldung.oauth2.authorization.server.model.User; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.security.enterprise.credential.Credential; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import javax.transaction.Transactional; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Objects; + +import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT; + +@ApplicationScoped +@Transactional +public class UserIdentityStore implements IdentityStore { + + @Inject + private AppDataRepository appDataRepository; + + @Override + public CredentialValidationResult validate(Credential credential) { + UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential; + String userId = usernamePasswordCredential.getCaller(); + User user = appDataRepository.getUser(userId); + Objects.requireNonNull(user, "User should be not null"); + if (usernamePasswordCredential.getPasswordAsString().equals(user.getPassword())) { + return new CredentialValidationResult(userId, new HashSet<>(Arrays.asList(user.getRoles().split(",")))); + } + return INVALID_RESULT; + } +} \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java new file mode 100644 index 0000000000..84b9a89c54 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java @@ -0,0 +1,209 @@ +//package com.baeldung.security.oauth2.server.web; +// +//import AuthorizationCode; +//import Client; +//import User; +//import com.baeldung.security.oauth2.server.service.AuthCodeService; +// +//import javax.ejb.EJB; +//import javax.enterprise.context.RequestScoped; +//import javax.inject.Inject; +//import javax.persistence.EntityManager; +//import javax.persistence.PersistenceContext; +//import javax.security.enterprise.SecurityContext; +//import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; +//import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; +//import javax.servlet.ServletException; +//import javax.servlet.annotation.HttpConstraint; +//import javax.servlet.annotation.ServletSecurity; +//import javax.servlet.annotation.WebServlet; +//import javax.servlet.http.HttpServlet; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import java.io.IOException; +//import java.security.Principal; +//import java.util.*; +// +///** +// * 1. GET http://localhost:8080/app/ (302) +// * 2. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302) +// * 3. GET http://localhost:8080/uaa/login (200) with initial request as hidden input +// * 4. POST http://localhost:8080/uaa/login (username, password, initial client request) (302) +// * 5. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (200) +// * 7. POST http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302) +// * 8. GET http://localhost:8080/app/?code=rkWijq06mL&state=A123 (200) +// */ +///* +// +//Query Params: +// client_id: app +// redirect_uri: http://localhost:8080/app/ +// response_type: code +// state: A123 +// +// ==> GET user login WITH client request as hidden input: +// +// +// ==> After user login ==> Initial client request +// ==> gen code +// == redirect to redirect uri + params code & state : 302, location : http://localhost:8080/app/?code=w6A0YQFzzg&state=A123 +//*/ +// +////authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 +////http://localhost:9080/authorize?response_type=code&client_id=client_id_1&redirect_uri=http://localhost:9080/app&state=A123 +// +////@RequestScoped +//@FormAuthenticationMechanismDefinition( +// loginToContinue = @LoginToContinue( +// loginPage = "/login-servlet", +// errorPage = "/login-error-servlet" +// ) +//) +//@WebServlet({"/authorize"}) +//@ServletSecurity(@HttpConstraint(rolesAllowed = "user")) +////@Stateless +//@RequestScoped +//public class AuthorizationEndpoint extends HttpServlet { +// +// private static final List authorizedResponseTypes = Arrays.asList("code", "token"); +// +// @Inject +// private SecurityContext securityContext; +// +// @PersistenceContext(name = "jpa-oauth2-pu") +// private EntityManager entityManager; +// +// @EJB +// private AuthCodeService authCodeService; +// +// //HTTP GET IS A MUST, POST IS OPTIONAL +// @Override +// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +// +// String error = ""; +// +// //1. User Authentication +// Principal principal = securityContext.getCallerPrincipal(); +// +// //2. Check for a valid client_id +// String clientId = request.getParameter("client_id"); +// if (clientId == null) { +// request.setAttribute("error", "The client " + clientId + " doesn't exist."); +// } +// request.setAttribute("clientId", clientId); +// Client client = entityManager.find(Client.class, clientId); +// if (client == null) { +// request.setAttribute("error", "The client " + clientId + " doesn't exist."); +// } +// +// //3. check for a valid response_type +// String responseType = request.getParameter("response_type"); +// if (!authorizedResponseTypes.contains(responseType)) { +// error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes; +// request.setAttribute("error", error); +// request.getRequestDispatcher("/error.jsp") +// .forward(request, response); +// } +// +// //4. Optional redirect_uri, if provided should match +// String redirectUri = request.getParameter("redirect_uri"); +// checkRedirectUri(client, redirectUri); +// +// //save params +// String currentUri = request.getRequestURI(); +// request.setAttribute("post_redirect_uri", currentUri); +// +// String state = request.getParameter("state"); +// Map requestMap = new HashMap<>(); +// requestMap.put("response_type", responseType); +// requestMap.put("client_id", clientId); +// requestMap.put("redirect_uri", redirectUri); +// requestMap.put("state", state); +// request.setAttribute("requestMap", requestMap); +// +// //5.scope: Optional +// String requestedScope = request.getParameter("scope"); +// if (requestedScope.isEmpty()) { +// requestedScope = client.getScope(); +// } +// //requestedScope should be a subset of the client scope: clientScopes.containsAll(requestedScopes) +// //checkRequestedScope(requestedScope, client.getScope()); +// +// //sub set of user scope +// //allowed scope by the user +// +// User user = entityManager.find(User.class, principal.getName()); +// request.setAttribute("scopes", requestedScope); +// +// +// forward("/authorize.jsp", request, response); +// } +// +// @Override +// protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +// String clientId = request.getParameter("client_id"); +// +// String responseType = request.getParameter("response_type"); +// if (!authorizedResponseTypes.contains(responseType)) { +// String error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes; +// request.setAttribute("error", error); +// forward("/error.jsp", request, response); +// } +// +// Client client = entityManager.find(Client.class, clientId); +// Objects.requireNonNull(client); +// +// String userId = securityContext.getCallerPrincipal().getName(); +// AuthorizationCode authorizationCode = new AuthorizationCode(); +// authorizationCode.setClientId(clientId); +// authorizationCode.setUserId(userId); +// String redirectUri = request.getParameter("redirect_uri"); +// authorizationCode.setRedirectUri(redirectUri); +// +// redirectUri = checkRedirectUri(client, redirectUri); +// +// String[] scope = request.getParameterValues("scope"); +// if (scope == null) { +// request.setAttribute("error", "User doesn't approved any scope"); +// forward("/error.jsp", request, response); +// } +// +// String approvedScopes = String.join(" ", scope); +// authorizationCode.setApprovedScopes(approvedScopes); +// +// //entityManager.persist(authorizationCode); +// authCodeService.save(authorizationCode); +// String code = authorizationCode.getCode(); +// +// StringBuilder sb = new StringBuilder(redirectUri); +// sb.append("?code=").append(code); +// +// //If the client send a state, Send it back +// String state = request.getParameter("state"); +// if (state != null) { +// sb.append("&state=").append(state); +// } +// response.sendRedirect(sb.toString()); +// } +// +// private String checkRedirectUri(Client client, String redirectUri) { +// //redirect uri +// if (redirectUri == null) { +// //erreur: param redirect_uri && client redirect_uri don't match. +// redirectUri = client.getRedirectUri(); +// if (redirectUri == null) { +// throw new IllegalStateException("redirectUri shloud be not null, unless a registred client have a redirect_uri."); +// } +// } else if (!redirectUri.equals(client.getRedirectUri())) { +// throw new IllegalStateException("request redirectUri and client registred redirect_uri should match."); +// } +// return redirectUri; +// } +// +// private void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +// request.getRequestDispatcher(path) +// .forward(request, response); +// } +//} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java new file mode 100644 index 0000000000..73085a68d1 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java @@ -0,0 +1,70 @@ +//package com.baeldung.security.oauth2.server.web; +// +//import AuthorizationGrantTypeHandler; +//import TokenResponse; +//import com.baeldung.security.oauth2.server.security.Authenticated; +//import com.nimbusds.jose.JOSEException; +// +//import javax.enterprise.inject.Instance; +//import javax.enterprise.inject.literal.NamedLiteral; +//import javax.inject.Inject; +//import javax.security.enterprise.SecurityContext; +//import javax.ws.rs.Consumes; +//import javax.ws.rs.POST; +//import javax.ws.rs.Path; +//import javax.ws.rs.Produces; +//import javax.ws.rs.core.MediaType; +//import javax.ws.rs.core.MultivaluedMap; +//import javax.ws.rs.core.Response; +//import java.security.Principal; +//import java.util.Arrays; +//import java.util.List; +//import java.util.Objects; +// +///** +// * { +// * "access_token" : "acb6803a48114d9fb4761e403c17f812", +// * "token_type" : "bearer", +// * "id_token" : "eyJhbGciOiJIUzI1NiIsImprdSI6Imh0dHBzOi8vbG9jYWxob3N0OjgwODAvdWFhL3Rva2VuX2tleXMiLCJraWQiOiJsZWdhY3ktdG9rZW4ta2V5IiwidHlwIjoiSldUIn0.eyJzdWIiOiIwNzYzZTM2MS02ODUwLTQ3N2ItYjk1Ny1iMmExZjU3MjczMTQiLCJhdWQiOlsibG9naW4iXSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbiIsImV4cCI6MTU1NzgzMDM4NSwiaWF0IjoxNTU3Nzg3MTg1LCJhenAiOiJsb2dpbiIsInNjb3BlIjpbIm9wZW5pZCJdLCJlbWFpbCI6IndyaHBONUB0ZXN0Lm9yZyIsInppZCI6InVhYSIsIm9yaWdpbiI6InVhYSIsImp0aSI6ImFjYjY4MDNhNDgxMTRkOWZiNDc2MWU0MDNjMTdmODEyIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImNsaWVudF9pZCI6ImxvZ2luIiwiY2lkIjoibG9naW4iLCJncmFudF90eXBlIjoiYXV0aG9yaXphdGlvbl9jb2RlIiwidXNlcl9uYW1lIjoid3JocE41QHRlc3Qub3JnIiwicmV2X3NpZyI6ImI3MjE5ZGYxIiwidXNlcl9pZCI6IjA3NjNlMzYxLTY4NTAtNDc3Yi1iOTU3LWIyYTFmNTcyNzMxNCIsImF1dGhfdGltZSI6MTU1Nzc4NzE4NX0.Fo8wZ_Zq9mwFks3LfXQ1PfJ4ugppjWvioZM6jSqAAQQ", +// * "refresh_token" : "f59dcb5dcbca45f981f16ce519d61486-r", +// * "expires_in" : 43199, +// * "scope" : "openid oauth.approvals", +// * "jti" : "acb6803a48114d9fb4761e403c17f812" +// * } +// */ +//@Path("token") +//public class TokenEndpoint { +// +// List supportedGrantTypes = Arrays.asList("authorization_code", "password", "refresh_token", "client_credentials"); +// +// @Inject +// private SecurityContext securityContext; +// +// @Inject +// Instance authorizationGrantTypeHandlers; +// +// @POST +// @Produces(MediaType.APPLICATION_JSON) +// @Consumes(MediaType.APPLICATION_FORM_URLENCODED) +// @Authenticated +// public Response token(MultivaluedMap params) throws JOSEException { +// //Authenticate client with [basic] http authentication mechanism +// Principal principal = securityContext.getCallerPrincipal(); +// Objects.requireNonNull(principal, "Client not authenticated!"); +// +// //Check grant_type params +// String grantType = params.getFirst("grant_type"); +// Objects.requireNonNull(grantType, "grant_type params is required"); +// //authorization_code, password, refresh, client_credentials +// if (!supportedGrantTypes.contains(grantType)) { +// throw new RuntimeException("grant_type parameter should be one of the following :" + supportedGrantTypes); +// } +// AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); +// TokenResponse tokenResponse = authorizationGrantTypeHandler.createAccessToken(principal.getName(), params); +// Response response = Response.ok(tokenResponse) +// .header("Cache-Control", "no-store") +// .header("Pragma", "no-cache") +// .build(); +// return response; +// } +//} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/liberty/config/server.xml b/oauth2-framework-impl/oauth2-authorization-server/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..97d9ec4a28 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/liberty/config/server.xml @@ -0,0 +1,32 @@ + + + + + localConnector-1.0 + cdi-2.0 + jaxrs-2.1 + jpa-2.2 + appSecurity-3.0 + jsp-2.3 + mpConfig-1.3 + + + + + + + + + + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/microprofile-config.properties b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 0000000000..d9c68bc111 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/microprofile-config.properties @@ -0,0 +1,2 @@ +signingkey=/META-INF/private-key.pem +verificationkey=/META-INF/public-key.pem diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/persistence.xml b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..a10ad3c886 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + + jdbc/OAuth2_DS + + + + + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/private-key.pem b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/private-key.pem new file mode 100644 index 0000000000..6e36cb4d78 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/private-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDYizUyvwY6qMd0 +ZkYPzP9mLTJOSczW8WtAbjhrgxk5LORIjcdv/aB1BAzDEOCX4UC+Rbs9YwaekIvW +7dL/t6xPzsA7+9tMt27TqUxXigWEFQG73w/WbEVzCG09IHqG7Ztjb6aGL+8pfcu+ +SLvOtXWrctHNbr35BYC5yBQaos9bH+nLYbh2Ff+emrpg7Kwoeis6MY6RgZIL/lxt +3beZt1NQhLEvB9t6XoSkyLQKSjT/OC8XOa4OYI4OfOSFqEUEp+8dKe3svZbQUNJf +KKehx78xx0rfwH+iBsFKkHdvt1ZHtINvYedAfGrc5rWnesunzOW7OKMAiIXAJSRA +rn9Iv5/fAgMBAAECggEAYHKwgSfAGIRwQhIDhqoh31qmG2SXjez9fjcZfhloNKUg +EIjFmcX3n+br4D42Kq+zbIwWd6MRobJz9oj6/9bJMsq9qHnnFWZmQHQZgqwBBPFu +UkVqAnE7BZ9tOFqs+EgAe+uQ2hejiHF1PA2dSNZd0L1VYRDAIJgo25aYDb0Sal0c +qaFmK1XzPnSIhgnopKP/TmUfALjeshtGvh6WkiXHTY2VKJlyLEiGd3/1tBZnzwSQ +QiS/2zfXL7lO0SYRA10m1BmtqGi3wSKIXUA6tNulmpXEMnYk4RtsqBClOanzQIm7 +f4Ie59AtUUlDdHzRmhxBaDprgAI/FdCxXkseLzk5sQKBgQDyptOhJ/VQ5tkgffJW +X2QwGIaNdvNCEL4GlgXKAWNkCzT4h+Q/2wFoKhaN2JH2YZwKCRwG/UZh4Hq22fdx +fa/DP8PK3zlX0c9dWQOtmBOe0/nG28kq9iqziP3ILLNuelfaMhxtRkUmR652VCzx +qazZmjoo2MxtA6BMiK3Vx5aikwKBgQDkdLalVveHKTVkrplQYNapQAtAwjlsNnMt +VJh6nLo3eOg1xBNA7JrYqx7sXRQInUGAyNKvgQL/lCQdMkTzyetLjJGsiFSEgeot +RMsDXBrJFYZiErbpQungpaevwAymaGi++nbCzhw1/n3AvVUhRKNknX8Ms0UKlLRZ +TCktCTChBQKBgGA7ZzzHgxPFqaCoMl6s0Cf+4gXigdDWoPYtszgM2uUHSMez5QKq +EWHFJ1Kz7BdBWMfmGvZupeYVR7WStf6NcRJHDJg9dRlt/QYxUjMbV9Sqjqmd6qce +H4s6LiOgDr0mygafzwRLVQs8bGVDNtvUhdd6wcwHRvOI957CqeZZlFT/AoGBAN2P +j79EW6U6wuyVJF0+vZDBauhwNQ6MtCEnZQWs0DCSUuop8d5KWVZ+huwGzTIZiPhk +S2goP4cs3eVu5k5k6oyHlJP2V7l24WzrxdPJVLTl6kFdEwWgfn//SGR7ZglRQxzM +fbcp+1QmL0FonZI5JhmjYR8pEXFUjJ/57AkgW4gdAoGASV3TlaNd+reb2l0kETqp +HrzzMIYkM2faZ8LmpcEO0wz606SK468bnl6SqVBYT2J0bkqCpEmPBtWs/OFCWd6x +93NndSfJk57/7AqNxfVyZWp2sjRzt5vZ4KPlRVvMHIGeJNbIV7RqUr6XGu+u3ZrS +B7SqwKZqdHVSULG9nMK7Iz8= +-----END PRIVATE KEY----- diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/public-key.pem b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/public-key.pem new file mode 100644 index 0000000000..f53ceca446 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/public-key.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Is1Mr8GOqjHdGZGD8z/ +Zi0yTknM1vFrQG44a4MZOSzkSI3Hb/2gdQQMwxDgl+FAvkW7PWMGnpCL1u3S/7es +T87AO/vbTLdu06lMV4oFhBUBu98P1mxFcwhtPSB6hu2bY2+mhi/vKX3Lvki7zrV1 +q3LRzW69+QWAucgUGqLPWx/py2G4dhX/npq6YOysKHorOjGOkYGSC/5cbd23mbdT +UISxLwfbel6EpMi0Cko0/zgvFzmuDmCODnzkhahFBKfvHSnt7L2W0FDSXyinoce/ +McdK38B/ogbBSpB3b7dWR7SDb2HnQHxq3Oa1p3rLp8zluzijAIiFwCUkQK5/SL+f +3wIDAQAB +-----END PUBLIC KEY----- diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/data.sql b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/data.sql new file mode 100644 index 0000000000..ecda0fa2ad --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/data.sql @@ -0,0 +1,3 @@ +INSERT INTO `users` (`user_id`, `password`, `roles`, `scopes`) VALUES ('appuser', 'appusersecret', 'USER', 'resource.read resource.write'); + +INSERT INTO `clients` (`client_id`, `client_secret`, `redirect_uri`,`scope`,`authorized_grant_types`) VALUES ('webappclient', 'webappclientsecret', 'http://localhost:9180/callback', 'resource.read resource.write', 'authorization_code refresh_token'); \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/WEB-INF/beans.xml b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..29595ff490 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,6 @@ + + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp new file mode 100644 index 0000000000..1004b5b8b7 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp @@ -0,0 +1,54 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + Authorization + + + + +
+

Want to Authorize scopes for client : ${client.clientId} ?

+
+ +
+ + + + + + + + + +
Scopes : + + ${scope}
+
+
+ + +
+
+ +
+ + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/error.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/error.jsp new file mode 100644 index 0000000000..edb0bf28b7 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/error.jsp @@ -0,0 +1,25 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> + + + + + + Error + + + + + + +
+

${error}

+
+ + + \ No newline at end of file diff --git a/spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File1.txt b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login-error.jsp similarity index 100% rename from spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File1.txt rename to oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login-error.jsp diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login.jsp new file mode 100644 index 0000000000..1d2dd93fd0 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login.jsp @@ -0,0 +1,49 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> + + + + + Login Form + + + + +
+

Login Form

+
+
+ + + + + + + + + + + + + +
Username
Password
+
+ +
+ + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-client/pom.xml b/oauth2-framework-impl/oauth2-client/pom.xml new file mode 100644 index 0000000000..e46a44268e --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + oauth2-client + war + + + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + + + + 9180 + 9543 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + + diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java new file mode 100644 index 0000000000..a5fdaf07f2 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java @@ -0,0 +1,39 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.UUID; + +@WebServlet(urlPatterns = "/authorize") +public class AuthorizationCodeServlet extends HttpServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + //... + request.getSession().removeAttribute("tokenResponse"); + String state = UUID.randomUUID().toString(); + request.getSession().setAttribute("CLIENT_LOCAL_STATE", state); + + String authorizationUri = config.getValue("provider.authorizationUri", String.class); + String clientId = config.getValue("client.clientId", String.class); + String redirectUri = config.getValue("client.redirectUri", String.class); + String scope = config.getValue("client.scope", String.class); + + String authorizationLocation = authorizationUri + "?response_type=code" + + "&client_id=" + clientId + + "&redirect_uri=" + redirectUri + + "&scope=" + scope + + "&state=" + state; + response.sendRedirect(authorizationLocation); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java new file mode 100644 index 0000000000..87aa8bc668 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java @@ -0,0 +1,76 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.util.Base64; + +@WebServlet(urlPatterns = "/callback") +public class CallbackServlet extends HttpServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + //Error: + String error = request.getParameter("error"); + if (error != null) { + request.setAttribute("error", error); + dispatch("/", request, response); + return; + } + String localState = (String) request.getSession().getAttribute("CLIENT_LOCAL_STATE"); + if (!localState.equals(request.getParameter("state"))) { + request.setAttribute("error", "The state attribute doesn't match !!"); + dispatch("/", request, response); + return; + } + + String code = request.getParameter("code"); + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(config.getValue("provider.tokenUri", String.class)); + + Form form = new Form(); + form.param("grant_type", "authorization_code"); + form.param("code", code); + form.param("redirect_uri", config.getValue("client.redirectUri", String.class)); + + JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue()) + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); + + request.getSession().setAttribute("tokenResponse", tokenResponse); + dispatch("/", request, response); + } + + private void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + RequestDispatcher requestDispatcher = request.getRequestDispatcher(location); + requestDispatcher.forward(request, response); + } + + private String getAuthorizationHeaderValue() { + String clientId = config.getValue("client.clientId", String.class); + String clientSecret = config.getValue("client.clientSecret", String.class); + String token = clientId + ":" + clientSecret; + String encodedString = Base64.getEncoder().encodeToString(token.getBytes()); + return "Basic " + encodedString; + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java new file mode 100644 index 0000000000..bbe850917b --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java @@ -0,0 +1,49 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.client.*; +import java.io.IOException; +import java.io.PrintWriter; + +@WebServlet(urlPatterns = "/downstream") +public class DownstreamCallServlet extends HttpServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { + resp.setContentType("text/html;charset=UTF-8"); + String action = request.getParameter("action"); + Client client = ClientBuilder.newClient(); + WebTarget webTarget = client.target(config.getValue("resourceServerUri", String.class)); + WebTarget resourceWebTarget; + String response = null; + JsonObject tokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse"); + if ("read".equals(action)) { + resourceWebTarget = webTarget.path("resource/read"); + Invocation.Builder invocationBuilder = resourceWebTarget.request(); + response = invocationBuilder + .header("authorization", tokenResponse.getString("access_token")) + .get(String.class); + } else if ("write".equals(action)) { + resourceWebTarget = webTarget.path("resource/write"); + Invocation.Builder invocationBuilder = resourceWebTarget.request(); + response = invocationBuilder + .header("authorization", tokenResponse.getString("access_token")) + .post(Entity.text("body string"), String.class); + } + PrintWriter out = resp.getWriter(); + out.println(response); + out.flush(); + out.close(); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/liberty/config/server.xml b/oauth2-framework-impl/oauth2-client/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..26dc730361 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/liberty/config/server.xml @@ -0,0 +1,19 @@ + + + + + localConnector-1.0 + cdi-2.0 + jsp-2.3 + mpConfig-1.3 + jaxrsClient-2.1 + jsonp-1.1 + + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-client/src/main/resources/META-INF/microprofile-config.properties b/oauth2-framework-impl/oauth2-client/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 0000000000..d66f4f6a74 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/resources/META-INF/microprofile-config.properties @@ -0,0 +1,12 @@ +#Client registration +client.clientId=webappclient +client.clientSecret=webappclientsecret +client.redirectUri=http://localhost:9180/callback +client.scope=resource.read resource.write + +#Provider +provider.authorizationUri=http://127.0.0.1:9080/authorize +provider.tokenUri=http://127.0.0.1:9080/token + +#Resource Server +resourceServerUri=http://localhost:9280/api \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/beans.xml b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..29595ff490 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,6 @@ + + + diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/web.xml b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..0203894c1b --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,5 @@ + + + index.jsp + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp new file mode 100644 index 0000000000..23fec70f33 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp @@ -0,0 +1,97 @@ +<%@ page import="org.eclipse.microprofile.config.Config" %> +<%@ page import="org.eclipse.microprofile.config.ConfigProvider" %> + + + + + + OAuth2 Client + + + + + +<% + Config config1 = ConfigProvider.getConfig(); +%> + +
"> + Error : ${error} +
+ +
+

OAuth2 Authorization Server

+
+

Client Registration :

+
    +
  • client_id: <%=config1.getValue("client.clientId", String.class)%> +
  • +
  • client_secret: <%=config1.getValue("client.clientSecret", String.class)%> +
  • +
  • redirect_uri: <%=config1.getValue("client.redirectUri", String.class)%> +
  • +
  • scope: <%=config1.getValue("client.scope", String.class)%> +
  • +
+

Authorization Server :

+
    +
  • authorization_uri: <%=config1.getValue("provider.authorizationUri", String.class)%> +
  • +
  • token_uri: <%=config1.getValue("provider.tokenUri", String.class)%> +
  • +
+
+
+

OAuth2 Client

+
+

Token Request :

+ + +

Token Response:

+
    +
  • access_token: ${tokenResponse.getString("access_token")}
  • +
  • scope: ${tokenResponse.getString("scope")}
  • +
  • Expires in (s): ${tokenResponse.getInt("expires_in")}
  • +
+
+
+

OAuth2 Resource Server Call

+
+ + +
+ + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-resource-server/pom.xml b/oauth2-framework-impl/oauth2-resource-server/pom.xml new file mode 100644 index 0000000000..9b58c33472 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + oauth2-resource-server + war + + + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + + + + 9280 + 8643 + http://localhost:9080 + http://localhost:9280 + + + + + org.eclipse.microprofile.jwt + microprofile-jwt-auth-api + 1.1 + provided + + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + + + diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java new file mode 100644 index 0000000000..835e80a416 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.oauth2.resource.server; + +import org.eclipse.microprofile.auth.LoginConfig; + +import javax.annotation.security.DeclareRoles; +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/api") +@DeclareRoles({"resource.read", "resource.write"}) +@LoginConfig(authMethod = "MP-JWT") +public class OAuth2ResourceServerApplication extends Application { +} diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java new file mode 100644 index 0000000000..300de83c6d --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java @@ -0,0 +1,38 @@ +package com.baeldung.oauth2.resource.server.secure; + +import org.eclipse.microprofile.jwt.JsonWebToken; + +import javax.annotation.security.RolesAllowed; +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 java.util.UUID; + +@Path("/resource") +@RequestScoped +public class ProtectedResource { + + @Inject + private JsonWebToken principal; + + @GET + @RolesAllowed("resource.read") + @Path("/read") + public Response read() { + //DoStaff + return Response.ok("Hello, " + principal.getName()).build(); + } + + @POST + @RolesAllowed("resource.write") + @Path("/write") + public Response write() { + //DoStaff + return Response.ok("Hello, " + principal.getName()) + .header("location", UUID.randomUUID().toString()) + .build(); + } +} diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/liberty/config/server.xml b/oauth2-framework-impl/oauth2-resource-server/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c54d698359 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/liberty/config/server.xml @@ -0,0 +1,20 @@ + + + + + localConnector-1.0 + cdi-2.0 + jaxrs-2.1 + jsonp-1.1 + mpConfig-1.3 + mpJwt-1.1 + + + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/microprofile-config.properties b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 0000000000..be6919ec50 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/microprofile-config.properties @@ -0,0 +1,2 @@ +mp.jwt.verify.publickey.location=/META-INF/public-key.pem +mp.jwt.verify.issuer=http://localhost:9080 \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/public-key.pem b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/public-key.pem new file mode 100644 index 0000000000..f53ceca446 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/public-key.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Is1Mr8GOqjHdGZGD8z/ +Zi0yTknM1vFrQG44a4MZOSzkSI3Hb/2gdQQMwxDgl+FAvkW7PWMGnpCL1u3S/7es +T87AO/vbTLdu06lMV4oFhBUBu98P1mxFcwhtPSB6hu2bY2+mhi/vKX3Lvki7zrV1 +q3LRzW69+QWAucgUGqLPWx/py2G4dhX/npq6YOysKHorOjGOkYGSC/5cbd23mbdT +UISxLwfbel6EpMi0Cko0/zgvFzmuDmCODnzkhahFBKfvHSnt7L2W0FDSXyinoce/ +McdK38B/ogbBSpB3b7dWR7SDb2HnQHxq3Oa1p3rLp8zluzijAIiFwCUkQK5/SL+f +3wIDAQAB +-----END PUBLIC KEY----- diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/WEB-INF/beans.xml b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..2777559c20 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,6 @@ + + + diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/index.html b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/index.html new file mode 100644 index 0000000000..7ea29c1097 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/index.html @@ -0,0 +1,37 @@ + + + + + Eclipse MicroProfile demo + + + +

MicroProfile

+ +Hello JAX-RS endpoint
+ + +

Config

+Injected config values
+Config values by lookup
+ + + + + + + + + +

JWT Auth

+Look at readme.md on how to test protected endpoint. + + + + + + + + + + \ No newline at end of file diff --git a/oauth2-framework-impl/pom.xml b/oauth2-framework-impl/pom.xml new file mode 100644 index 0000000000..281103660b --- /dev/null +++ b/oauth2-framework-impl/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + pom + + + 1.8 + 1.8 + false + RELEASE + 2.6.4 + + + + + javax + javaee-web-api + 8.0 + provided + + + org.eclipse.microprofile.config + microprofile-config-api + 1.3 + provided + + + + + ${project.artifactId} + + + ${basedir}/src/main/resources + + **/*.* + + + + true + ${basedir}/src/main/liberty + + **/*.* + + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${openliberty.maven.version} + + + package-server + package + + create-server + install-apps + + + target/wlp-package + + + + + + io.openliberty + openliberty-webProfile8 + ${openliberty.version} + zip + + target/classes/config/server.xml + ${project.build.directory}/${project.build.finalName}.war + project + ${project.basedir}/src/main/liberty/server + apps + true + + + + + + + oauth2-authorization-server + oauth2-resource-server + oauth2-client + + diff --git a/optaplanner/pom.xml b/optaplanner/pom.xml index fbce0ea072..93b1e68264 100644 --- a/optaplanner/pom.xml +++ b/optaplanner/pom.xml @@ -18,11 +18,6 @@ optaplanner-core 7.9.0.Final
- - - - -
\ No newline at end of file diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 4b81e27333..f0e921bf37 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -1,9 +1,9 @@ + 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-2 0.0.1-SNAPSHOT - parent-boot-2 + parent-boot-2 pom Parent for all Spring Boot 2 modules @@ -13,7 +13,7 @@ 1.0.0-SNAPSHOT - + org.springframework.boot @@ -28,7 +28,7 @@ io.rest-assured rest-assured - + org.springframework.boot spring-boot-starter-test @@ -36,22 +36,22 @@ - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - ${start-class} - - - - - - - + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + ${start-class} + + + + + + + thin-jar @@ -75,9 +75,9 @@ - 3.1.0 + 3.3.0 - 1.0.21.RELEASE - 2.1.3.RELEASE + 1.0.22.RELEASE + 2.1.6.RELEASE diff --git a/parent-boot-performance/README.md b/parent-boot-performance/README.md new file mode 100644 index 0000000000..fce9e101da --- /dev/null +++ b/parent-boot-performance/README.md @@ -0,0 +1 @@ +This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features. \ No newline at end of file diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml new file mode 100644 index 0000000000..b7d12e2ba4 --- /dev/null +++ b/parent-boot-performance/pom.xml @@ -0,0 +1,92 @@ + + 4.0.0 + parent-boot-performance + 0.0.1-SNAPSHOT + parent-boot-performance + pom + Parent for all modules that want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + io.rest-assured + rest-assured + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + ${start-class} + + + + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + + thin-jar + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.springframework.boot.experimental + spring-boot-thin-layout + ${thin.version} + + + + + + + + + + 3.1.0 + + 1.0.21.RELEASE + 2.2.0.M3 + + diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index 6f7fe6c102..d993fad3c6 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -26,6 +26,11 @@ kotlin-eap http://dl.bintray.com/kotlin/kotlin-eap + + spring-milestone + Spring Milestone Repository + http://repo.spring.io/milestone + @@ -40,7 +45,7 @@ org.springframework.boot spring-boot-dependencies - 2.0.1.RELEASE + 2.2.0.M4 pom import @@ -80,6 +85,10 @@ ktor-gson ${ktor.io.version} + + com.fasterxml.jackson.module + jackson-module-kotlin + org.jetbrains.kotlin diff --git a/parent-spring-4/pom.xml b/parent-spring-4/pom.xml index d7eea44989..ab66cf19bf 100644 --- a/parent-spring-4/pom.xml +++ b/parent-spring-4/pom.xml @@ -23,14 +23,36 @@ org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + 8082 + + + + + + + 4.3.22.RELEASE - 5.0.2 + 1.6.1 \ No newline at end of file diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 84df8cf30a..f85924b801 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -23,14 +23,13 @@ org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test 5.1.4.RELEASE - 5.0.2 5.1.4.RELEASE diff --git a/patterns/design-patterns-2/pom.xml b/patterns/design-patterns-2/pom.xml index 5c3e70b046..392035ab84 100644 --- a/patterns/design-patterns-2/pom.xml +++ b/patterns/design-patterns-2/pom.xml @@ -38,6 +38,5 @@ 1.8 1.8 16.0.2 - 3.5
diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index 605fdc0d6e..1c611f05d2 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -20,3 +20,4 @@ - [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) - [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern) - [Currying in Java](https://www.baeldung.com/java-currying) +- [The Proxy Pattern in Java](https://www.baeldung.com/java-proxy-pattern) diff --git a/patterns/design-patterns/pom.xml b/patterns/design-patterns/pom.xml index ac201ad653..e6bff64f9e 100644 --- a/patterns/design-patterns/pom.xml +++ b/patterns/design-patterns/pom.xml @@ -48,6 +48,7 @@ ${grep4j.version} + UTF-8 1.8 diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java index 374de31ba9..986c1d9660 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public abstract class AuthenticationProcessor { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java index 7b8771ca41..4d5e3bde24 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public interface AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java index 3bf20cfc85..5f994bad89 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class OAuthAuthenticationProcessor extends AuthenticationProcessor { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java index 92d5f94245..37f419b6e2 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class OAuthTokenProvider implements AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java index cd927932ad..3a0c35a9b9 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class SamlAuthenticationProvider implements AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java index 3885b2b79b..39038b1374 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class UsernamePasswordAuthenticationProcessor extends AuthenticationProcessor { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java index 9877039446..14dc93b8fc 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class UsernamePasswordProvider implements AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java b/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java index 30dcf08e89..878b67e0cf 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java @@ -1,10 +1,10 @@ -package com.baeldung.pattern.command.client; +package com.baeldung.command.client; -import com.baeldung.pattern.command.command.OpenTextFileOperation; -import com.baeldung.pattern.command.command.SaveTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.invoker.TextFileOperationExecutor; -import com.baeldung.pattern.command.receiver.TextFile; +import com.baeldung.command.command.OpenTextFileOperation; +import com.baeldung.command.command.SaveTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.invoker.TextFileOperationExecutor; +import com.baeldung.command.receiver.TextFile; public class TextFileApplication { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java b/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java index c90a162b88..74adce0116 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java @@ -1,6 +1,6 @@ -package com.baeldung.pattern.command.command; +package com.baeldung.command.command; -import com.baeldung.pattern.command.receiver.TextFile; +import com.baeldung.command.receiver.TextFile; public class OpenTextFileOperation implements TextFileOperation { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java b/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java index b908e2c44c..f0462622e3 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java @@ -1,6 +1,6 @@ -package com.baeldung.pattern.command.command; +package com.baeldung.command.command; -import com.baeldung.pattern.command.receiver.TextFile; +import com.baeldung.command.receiver.TextFile; public class SaveTextFileOperation implements TextFileOperation { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java b/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java index 506bb23d99..2d0267d315 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.command.command; +package com.baeldung.command.command; @FunctionalInterface public interface TextFileOperation { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java b/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java index bd2213706e..67c6dedd89 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java @@ -1,6 +1,6 @@ -package com.baeldung.pattern.command.invoker; +package com.baeldung.command.invoker; -import com.baeldung.pattern.command.command.TextFileOperation; +import com.baeldung.command.command.TextFileOperation; import java.util.ArrayList; import java.util.List; diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java b/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java index c0b2d3c41e..0163102256 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.command.receiver; +package com.baeldung.command.receiver; public class TextFile { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java index 9ab34c3cd8..353a369837 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java @@ -1,11 +1,9 @@ -package com.baeldung.pattern.templatemethod.application; +package com.baeldung.templatemethod.application; -import com.baeldung.pattern.templatemethod.model.Computer; -import com.baeldung.pattern.templatemethod.model.StandardComputer; -import com.baeldung.pattern.templatemethod.model.HighEndComputer; -import com.baeldung.pattern.templatemethod.model.ComputerBuilder; -import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; -import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder; +import com.baeldung.templatemethod.model.Computer; +import com.baeldung.templatemethod.model.ComputerBuilder; +import com.baeldung.templatemethod.model.HighEndComputerBuilder; +import com.baeldung.templatemethod.model.StandardComputerBuilder; public class Application { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java index 1419398f62..129a8d4c65 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; import java.util.HashMap; import java.util.Map; diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java index 515a6940f5..b5c7ee3987 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java @@ -1,6 +1,5 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; -import com.baeldung.pattern.templatemethod.model.Computer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java index 0684b1b233..55394d1df6 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java @@ -1,6 +1,5 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; -import com.baeldung.pattern.templatemethod.model.Computer; import java.util.Map; public class HighEndComputer extends Computer { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java index c992aa2bff..2ee6f93f9b 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; public class HighEndComputerBuilder extends ComputerBuilder { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java index 4e1d857016..3abe240316 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java @@ -1,6 +1,5 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; -import com.baeldung.pattern.templatemethod.model.Computer; import java.util.Map; public class StandardComputer extends Computer { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java index cc81dddc1b..da2c2e9b2d 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; public class StandardComputerBuilder extends ComputerBuilder { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java index 824b104f81..4556232815 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java @@ -1,14 +1,9 @@ package com.baeldung.chainofresponsibility; -import org.junit.Test; -import com.baeldung.pattern.chainofresponsibility.AuthenticationProcessor; -import com.baeldung.pattern.chainofresponsibility.OAuthAuthenticationProcessor; -import com.baeldung.pattern.chainofresponsibility.OAuthTokenProvider; -import com.baeldung.pattern.chainofresponsibility.UsernamePasswordProvider; -import com.baeldung.pattern.chainofresponsibility.SamlAuthenticationProvider; -import com.baeldung.pattern.chainofresponsibility.UsernamePasswordAuthenticationProcessor; import static org.junit.Assert.assertTrue; +import org.junit.Test; + public class ChainOfResponsibilityIntegrationTest { private static AuthenticationProcessor getChainOfAuthProcessor() { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java index 1c72bfdd2f..eac62313f7 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java @@ -1,10 +1,12 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.command.OpenTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.receiver.TextFile; import org.junit.Test; -import static org.assertj.core.api.Assertions.*; + +import com.baeldung.command.command.OpenTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.receiver.TextFile; public class OpenTextFileOperationUnitTest { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java index a7bc1f3025..3e47f10366 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java @@ -1,10 +1,12 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.command.SaveTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.receiver.TextFile; import org.junit.Test; -import static org.assertj.core.api.Assertions.*; + +import com.baeldung.command.command.SaveTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.receiver.TextFile; public class SaveTextFileOperationUnitTest { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java index efafa0d8a2..3861b1109e 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java @@ -1,14 +1,17 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.command.OpenTextFileOperation; -import com.baeldung.pattern.command.command.SaveTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.invoker.TextFileOperationExecutor; -import com.baeldung.pattern.command.receiver.TextFile; import java.util.function.Function; -import org.junit.Test; -import static org.assertj.core.api.Assertions.*; + import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.command.command.OpenTextFileOperation; +import com.baeldung.command.command.SaveTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.invoker.TextFileOperationExecutor; +import com.baeldung.command.receiver.TextFile; public class TextFileOperationExecutorUnitTest { @@ -65,4 +68,11 @@ public class TextFileOperationExecutorUnitTest { Function executeMethodReference = SaveTextFileOperation::execute; assertThat(executeMethodReference.apply(new SaveTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Saving file file1.txt"); } + + @Test + public void givenOpenAndSaveTextFileOperationExecutorInstance_whenCalledExecuteOperationWithLambdaExpression_thenBothAssertion() { + TextFileOperationExecutor textFileOperationExecutor = new TextFileOperationExecutor(); + assertThat(textFileOperationExecutor.executeOperation(() -> "Opening file file1.txt")).isEqualTo("Opening file file1.txt"); + assertThat(textFileOperationExecutor.executeOperation(() -> "Saving file file1.txt")).isEqualTo("Saving file file1.txt"); + } } diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java index 32b83897c9..e35c785f3e 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java @@ -1,9 +1,11 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.receiver.TextFile; -import org.junit.Test; -import static org.assertj.core.api.Assertions.*; import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.command.receiver.TextFile; public class TextFileUnitTest { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java index 4ad4debb27..2c721be5da 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java @@ -1,14 +1,16 @@ package com.baeldung.templatemethod.test; -import com.baeldung.pattern.templatemethod.model.Computer; -import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; -import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder; -import org.junit.Assert; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertThat; + +import com.baeldung.templatemethod.model.Computer; +import com.baeldung.templatemethod.model.HighEndComputerBuilder; +import com.baeldung.templatemethod.model.StandardComputerBuilder; public class TemplateMethodPatternIntegrationTest { diff --git a/patterns/dip/pom.xml b/patterns/dip/pom.xml index dac3f824f2..bc793c0090 100644 --- a/patterns/dip/pom.xml +++ b/patterns/dip/pom.xml @@ -19,13 +19,13 @@ junit junit - 4.12 + ${junit.version} test org.assertj assertj-core - 3.12.1 + ${assertj-core.version} test @@ -34,6 +34,7 @@ UTF-8 11 11 + 3.12.1 diff --git a/patterns/pom.xml b/patterns/pom.xml index 875af67d55..2be9d2519e 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -51,7 +51,6 @@ - 3.0.0 9.4.0.v20161208 diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOIntegrationTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java similarity index 98% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOIntegrationTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java index 5c20b6bf1e..3f69a0e333 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOIntegrationTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java @@ -12,7 +12,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -public class ArticleWithAuthorDAOIntegrationTest { +public class ArticleWithAuthorDAOLiveTest { private Connection connection; private ArticleWithAuthorDAO articleWithAuthorDAO; diff --git a/persistence-modules/deltaspike/pom.xml b/persistence-modules/deltaspike/pom.xml index 4dcef07695..46e774edff 100644 --- a/persistence-modules/deltaspike/pom.xml +++ b/persistence-modules/deltaspike/pom.xml @@ -317,7 +317,6 @@ 2.6 1.1.3 1.2.5.Final-redhat-1 - 3.5
diff --git a/persistence-modules/elasticsearch/.gitignore b/persistence-modules/elasticsearch/.gitignore new file mode 100644 index 0000000000..153c9335eb --- /dev/null +++ b/persistence-modules/elasticsearch/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/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/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ + +### VS Code ### +.vscode/ diff --git a/persistence-modules/elasticsearch/README.md b/persistence-modules/elasticsearch/README.md new file mode 100644 index 0000000000..691e855314 --- /dev/null +++ b/persistence-modules/elasticsearch/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Jest – Elasticsearch Java Client](https://www.baeldung.com/elasticsearch-jest) diff --git a/persistence-modules/elasticsearch/pom.xml b/persistence-modules/elasticsearch/pom.xml new file mode 100644 index 0000000000..f7bfdb44de --- /dev/null +++ b/persistence-modules/elasticsearch/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + com.baeldung + elasticsearch + 0.0.1-SNAPSHOT + elasticsearch + Demo project for Java Elasticsearch libraries + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + + io.searchbox + jest + ${jest.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + 6.3.1 + + diff --git a/persistence-modules/elasticsearch/src/main/java/com/baeldung/jest/Employee.java b/persistence-modules/elasticsearch/src/main/java/com/baeldung/jest/Employee.java new file mode 100644 index 0000000000..6f28a42a9c --- /dev/null +++ b/persistence-modules/elasticsearch/src/main/java/com/baeldung/jest/Employee.java @@ -0,0 +1,42 @@ +package com.baeldung.jest; + +import java.util.List; + +public class Employee { + String name; + String title; + List skills; + int yearsOfService; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getSkills() { + return skills; + } + + public void setSkills(List skills) { + this.skills = skills; + } + + public int getYearsOfService() { + return yearsOfService; + } + + public void setYearsOfService(int yearsOfService) { + this.yearsOfService = yearsOfService; + } +} diff --git a/persistence-modules/elasticsearch/src/main/java/com/baeldung/jest/JestDemoApplication.java b/persistence-modules/elasticsearch/src/main/java/com/baeldung/jest/JestDemoApplication.java new file mode 100644 index 0000000000..91e499da2e --- /dev/null +++ b/persistence-modules/elasticsearch/src/main/java/com/baeldung/jest/JestDemoApplication.java @@ -0,0 +1,174 @@ +package com.baeldung.jest; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.searchbox.client.JestClient; +import io.searchbox.client.JestClientFactory; +import io.searchbox.client.JestResult; +import io.searchbox.client.JestResultHandler; +import io.searchbox.client.config.HttpClientConfig; +import io.searchbox.core.*; +import io.searchbox.indices.CreateIndex; +import io.searchbox.indices.IndicesExists; +import io.searchbox.indices.aliases.AddAliasMapping; +import io.searchbox.indices.aliases.ModifyAliases; +import io.searchbox.indices.aliases.RemoveAliasMapping; + +import java.io.IOException; +import java.util.*; + +public class JestDemoApplication { + + public static void main(String[] args) throws IOException { + + // Demo the JestClient + JestClient jestClient = jestClient(); + + // Check an index + JestResult result = jestClient.execute(new IndicesExists.Builder("employees").build()); + if(!result.isSucceeded()) { + System.out.println(result.getErrorMessage()); + } + + // Create an index + jestClient.execute(new CreateIndex.Builder("employees").build()); + + // Create an index with options + Map settings = new HashMap<>(); + settings.put("number_of_shards", 11); + settings.put("number_of_replicas", 2); + jestClient.execute(new CreateIndex.Builder("employees").settings(settings).build()); + + // Create an alias, then remove it + jestClient.execute(new ModifyAliases.Builder( + new AddAliasMapping.Builder( + "employees", + "e") + .build()) + .build()); + JestResult jestResult = jestClient.execute(new ModifyAliases.Builder( + new RemoveAliasMapping.Builder( + "employees", + "e") + .build()) + .build()); + + if(jestResult.isSucceeded()) { + System.out.println("Success!"); + } + else { + System.out.println(jestResult.getErrorMessage()); + } + + // Sample JSON for indexing + + // { + // "name": "Michael Pratt", + // "title": "Java Developer", + // "skills": ["java", "spring", "elasticsearch"], + // "yearsOfService": 2 + // } + + // Index a document from String + ObjectMapper mapper = new ObjectMapper(); + JsonNode employeeJsonNode = mapper.createObjectNode() + .put("name", "Michael Pratt") + .put("title", "Java Developer") + .put("yearsOfService", 2) + .set("skills", mapper.createArrayNode() + .add("java") + .add("spring") + .add("elasticsearch")); + jestClient.execute(new Index.Builder(employeeJsonNode.toString()).index("employees").build()); + + // Index a document from Map + Map employeeHashMap = new LinkedHashMap<>(); + employeeHashMap.put("name", "Michael Pratt"); + employeeHashMap.put("title", "Java Developer"); + employeeHashMap.put("yearsOfService", 2); + employeeHashMap.put("skills", Arrays.asList("java", "spring", "elasticsearch")); + jestClient.execute(new Index.Builder(employeeHashMap).index("employees").build()); + + // Index a document from POJO + Employee employee = new Employee(); + employee.setName("Michael Pratt"); + employee.setTitle("Java Developer"); + employee.setYearsOfService(2); + employee.setSkills(Arrays.asList("java", "spring", "elasticsearch")); + jestClient.execute(new Index.Builder(employee).index("employees").build()); + + // Read document by ID + Employee getResult = jestClient.execute(new Get.Builder("employees", "1").build()).getSourceAsObject(Employee.class); + + // Search documents + String search = "{\n" + + " \"query\": {\n" + + " \"bool\": {\n" + + " \"must\": [\n" + + " { \"match\": { \"name\": \"Michael Pratt\" }}\n" + + " ]\n" + + " }\n" + + " }\n" + + "}"; + List> searchResults = + jestClient.execute(new Search.Builder(search).build()) + .getHits(Employee.class); + + searchResults.forEach(hit -> { + System.out.println(String.format("Document %s has score %s", hit.id, hit.score)); + }); + + // Update document + employee.setYearsOfService(3); + jestClient.execute(new Update.Builder(employee).index("employees").id("1").build()); + + // Delete documents + jestClient.execute(new Delete.Builder("2") .index("employees") .build()); + + // Bulk operations + Employee employeeObject1 = new Employee(); + employee.setName("John Smith"); + employee.setTitle("Python Developer"); + employee.setYearsOfService(10); + employee.setSkills(Arrays.asList("python")); + + Employee employeeObject2 = new Employee(); + employee.setName("Kate Smith"); + employee.setTitle("Senior JavaScript Developer"); + employee.setYearsOfService(10); + employee.setSkills(Arrays.asList("javascript", "angular")); + + jestClient.execute(new Bulk.Builder().defaultIndex("employees") + .addAction(new Index.Builder(employeeObject1).build()) + .addAction(new Index.Builder(employeeObject2).build()) + .addAction(new Delete.Builder("3").build()) .build()); + + // Async operations + Employee employeeObject3 = new Employee(); + employee.setName("Jane Doe"); + employee.setTitle("Manager"); + employee.setYearsOfService(20); + employee.setSkills(Arrays.asList("managing")); + + jestClient.executeAsync( new Index.Builder(employeeObject3).build(), new JestResultHandler() { + @Override public void completed(JestResult result) { + // handle result + } + @Override public void failed(Exception ex) { + // handle exception + } + }); + } + + private static JestClient jestClient() + { + JestClientFactory factory = new JestClientFactory(); + factory.setHttpClientConfig( + new HttpClientConfig.Builder("http://localhost:9200") + .multiThreaded(true) + .defaultMaxTotalConnectionPerRoute(2) + .maxTotalConnection(20) + .build()); + return factory.getObject(); + } +} diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 203cb2f8e4..99374f9135 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -3,3 +3,5 @@ - [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) - [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) +- [Hibernate Validator Specific Constraints](https://www.baeldung.com/hibernate-validator-constraints) +- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 6bab3c5b1f..e90d7463bd 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -2,18 +2,17 @@ - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - - hibernate-mapping 1.0.0-SNAPSHOT 4.0.0 + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + .. + + org.hibernate @@ -31,40 +30,47 @@ h2 ${h2.version} - + org.hibernate hibernate-validator ${hibernate-validator.version} - - javax.el - javax.el-api - ${javax.el-api.version} - org.glassfish javax.el ${org.glassfish.javax.el.version} + + javax.money + money-api + ${money-api.version} + + + org.javamoney + moneta + ${moneta.version} + pom + hibernate-mapping - src/test/resources + src/main/resources true - 5.3.7.Final + 5.3.10.Final 3.8.0 - 5.3.3.Final - 2.2.5 - 3.0.1-b08 + 6.0.16.Final + 3.0.1-b11 + 1.0.3 + 1.3 - \ No newline at end of file + diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java similarity index 65% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java index e522dab48d..46e6824f42 100644 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -1,8 +1,9 @@ package com.baeldung.hibernate.oneToMany.config; import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateAnnotationUtil { @@ -12,16 +13,12 @@ public class HibernateAnnotationUtil { private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate-annotation.cfg.xml - Configuration configuration = new Configuration(); - configuration.configure("hibernate-annotation.cfg.xml"); - System.out.println("Hibernate Annotation Configuration loaded"); - - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); - System.out.println("Hibernate Annotation serviceRegistry created"); - - SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build(); + Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build(); + SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); return sessionFactory; + } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java index f6e8f1cdd6..b2ee7e85fe 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java @@ -4,8 +4,11 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.validation.constraints.Size; +import javax.money.MonetaryAmount; import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.CreditCardNumber; +import org.hibernate.validator.constraints.Currency; @Entity public class User { @@ -62,5 +65,4 @@ public class User { public void setCity(String city) { this.city = city; } - } diff --git a/persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml b/persistence-modules/hibernate-mapping/src/main/resources/hibernate-annotation.cfg.xml similarity index 67% rename from persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml rename to persistence-modules/hibernate-mapping/src/main/resources/hibernate-annotation.cfg.xml index 14d853d3fd..9b97c03935 100644 --- a/persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml +++ b/persistence-modules/hibernate-mapping/src/main/resources/hibernate-annotation.cfg.xml @@ -4,11 +4,11 @@ "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> - com.mysql.jdbc.Driver - mypassword - jdbc:mysql://localhost:3306/spring_hibernate_one_to_many?createDatabaseIfNotExist=true - myuser - org.hibernate.dialect.MySQLDialect + org.h2.Driver + + jdbc:h2:mem:spring_hibernate_one_to_many + sa + org.hibernate.dialect.H2Dialect create thread true diff --git a/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties b/persistence-modules/hibernate-mapping/src/main/resources/hibernate.properties similarity index 100% rename from persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties rename to persistence-modules/hibernate-mapping/src/main/resources/hibernate.properties diff --git a/persistence-modules/spring-hibernate4/src/main/resources/one_to_many.sql b/persistence-modules/hibernate-mapping/src/main/resources/one_to_many.sql similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/resources/one_to_many.sql rename to persistence-modules/hibernate-mapping/src/main/resources/one_to_many.sql diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java similarity index 90% rename from persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java index b3a091ebf1..3bc5a6e12a 100644 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java @@ -10,7 +10,7 @@ import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.HSQLDialect; +import org.hibernate.dialect.H2Dialect; import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.AfterClass; @@ -18,6 +18,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; + import com.baeldung.hibernate.oneToMany.model.Cart; import com.baeldung.hibernate.oneToMany.model.Items; @@ -33,9 +34,9 @@ public class HibernateOneToManyAnnotationMainIntegrationTest { @BeforeClass public static void beforeTests() { Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class) - .setProperty("hibernate.dialect", HSQLDialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") + .setProperty("hibernate.dialect", H2Dialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "") .setProperty("hibernate.hbm2ddl.auto", "update"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java new file mode 100644 index 0000000000..0f2a0403e9 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java @@ -0,0 +1,290 @@ +package com.baeldung.hibernate.validation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.math.BigDecimal; +import java.time.Duration; +import java.util.Set; + +import javax.money.CurrencyContextBuilder; +import javax.money.Monetary; +import javax.money.MonetaryAmount; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.hibernate.validator.constraints.CodePointLength; +import org.hibernate.validator.constraints.CreditCardNumber; +import org.hibernate.validator.constraints.Currency; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.LuhnCheck; +import org.hibernate.validator.constraints.Range; +import org.hibernate.validator.constraints.SafeHtml; +import org.hibernate.validator.constraints.ScriptAssert; +import org.hibernate.validator.constraints.URL; +import org.hibernate.validator.constraints.time.DurationMax; +import org.hibernate.validator.constraints.time.DurationMin; +import org.javamoney.moneta.CurrencyUnitBuilder; +import org.javamoney.moneta.Money; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserAdditionalValidationUnitTest { + + private static Validator validator; + private Set> constraintViolations; + + @BeforeClass + public static void before() { + ValidatorFactory config = Validation.buildDefaultValidatorFactory(); + validator = config.getValidator(); + } + + @Test + public void whenValidationWithCCNAndNullCCN_thenNoConstraintViolation() { + AdditionalValidations validations = new AdditionalValidations(); + constraintViolations = validator.validateProperty(validations, "creditCardNumber"); + assertTrue(constraintViolations.isEmpty()); + } + + @Test + public void whenValidationWithCCNAndValidCCN_thenNoConstraintViolation() { + AdditionalValidations validations = new AdditionalValidations(); + validations.setCreditCardNumber("79927398713"); + constraintViolations = validator.validateProperty(validations, "creditCardNumber"); + assertTrue(constraintViolations.isEmpty()); + } + + @Test + public void whenValidationWithCCNAndInvalidCCN_thenConstraintViolation() { + AdditionalValidations validations = new AdditionalValidations(); + validations.setCreditCardNumber("79927398714"); + constraintViolations = validator.validateProperty(validations, "creditCardNumber"); + assertEquals(constraintViolations.size(), 2); + } + + @Test + public void whenValidationWithCCNAndValidCCNWithDashes_thenConstraintViolation() { + AdditionalValidations validations = new AdditionalValidations(); + validations.setCreditCardNumber("7992-7398-713"); + constraintViolations = validator.validateProperty(validations, "creditCardNumber"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenValidationWithLenientCCNAndValidCCNWithDashes_thenNoConstraintViolation() { + AdditionalValidations validations = new AdditionalValidations(); + validations.setLenientCreditCardNumber("7992-7398-713"); + constraintViolations = validator.validateProperty(validations, "lenientCreditCardNumber"); + assertTrue(constraintViolations.isEmpty()); + } + + @Test + public void whenMonetaryAmountWithRightCurrency_thenNoConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setBalance(Money.of(new BigDecimal(100.0), Monetary.getCurrency("EUR"))); + constraintViolations = validator.validateProperty(bean, "balance"); + assertEquals(0, constraintViolations.size()); + } + + @Test + public void whenMonetaryAmountWithWrongCurrency_thenConstraintViolation() { + AdditionalValidations validations = new AdditionalValidations(); + validations.setBalance(Money.of(new BigDecimal(100.0), Monetary.getCurrency("USD"))); + constraintViolations = validator.validateProperty(validations, "balance"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenDurationShorterThanMin_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setDuration(Duration.ofDays(1).plusHours(1)); + constraintViolations = validator.validateProperty(bean, "duration"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenDurationLongerThanMax_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setDuration(Duration.ofDays(2).plusHours(3)); + constraintViolations = validator.validateProperty(bean, "duration"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenDurationBetweenMinAndMax_thenNoConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setDuration(Duration.ofDays(2)); + constraintViolations = validator.validateProperty(bean, "duration"); + assertEquals(0, constraintViolations.size()); + } + + @Test + public void whenValueBelowRangeMin_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setPercent(new BigDecimal("-1.4")); + constraintViolations = validator.validateProperty(bean, "percent"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenValueAboveRangeMax_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setPercent(new BigDecimal("100.03")); + constraintViolations = validator.validateProperty(bean, "percent"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenValueInRange_thenNoConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setPercent(new BigDecimal("53.23")); + constraintViolations = validator.validateProperty(bean, "percent"); + assertEquals(0, constraintViolations.size()); + } + + @Test + public void whenLengthInRange_thenNoConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setSomeString("aaa"); + constraintViolations = validator.validateProperty(bean, "someString"); + assertEquals(0, constraintViolations.size()); + } + + @Test + public void whenCodePointLengthNotInRange_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setSomeString("aa\uD835\uDD0A"); + constraintViolations = validator.validateProperty(bean, "someString"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenValidUrlWithWrongProtocol_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + + bean.setUrl("https://www.google.com/"); + constraintViolations = validator.validateProperty(bean, "url"); + assertEquals(0, constraintViolations.size()); + + bean.setUrl("http://www.google.com/"); + constraintViolations = validator.validateProperty(bean, "url"); + assertEquals(1, constraintViolations.size()); + + bean.setUrl("https://foo:bar"); + constraintViolations = validator.validateProperty(bean, "url"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenScriptAssertFails_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + + constraintViolations = validator.validate(bean); + assertEquals(0, constraintViolations.size()); + + bean.setValid(false); + + constraintViolations = validator.validate(bean); + assertEquals(1, constraintViolations.size()); + + constraintViolations = validator.validateProperty(bean, "valid"); + assertEquals(0, constraintViolations.size()); + } + + @ScriptAssert(lang = "nashorn", script = "_this.valid") + public class AdditionalValidations { + private boolean valid = true; + + @CreditCardNumber + @LuhnCheck(startIndex = 0, endIndex = Integer.MAX_VALUE, checkDigitIndex = -1) + private String creditCardNumber; + + @CreditCardNumber(ignoreNonDigitCharacters = true) + private String lenientCreditCardNumber; + + @Currency("EUR") + private MonetaryAmount balance; + + @DurationMin(days = 1, hours = 2) + @DurationMax(days = 2, hours = 1) + private Duration duration; + + @Range(min = 0, max = 100) + private BigDecimal percent; + + @Length(min = 1, max = 3) + @CodePointLength(min = 1, max = 3) + private String someString; + + @URL(protocol = "https") + private String url; + + public String getCreditCardNumber() { + return creditCardNumber; + } + + public void setCreditCardNumber(String creditCardNumber) { + this.creditCardNumber = creditCardNumber; + } + + public String getLenientCreditCardNumber() { + return lenientCreditCardNumber; + } + + public void setLenientCreditCardNumber(String lenientCreditCardNumber) { + this.lenientCreditCardNumber = lenientCreditCardNumber; + } + + public MonetaryAmount getBalance() { + return balance; + } + + public void setBalance(MonetaryAmount balance) { + this.balance = balance; + } + + public Duration getDuration() { + return duration; + } + + public void setDuration(Duration duration) { + this.duration = duration; + } + + public BigDecimal getPercent() { + return percent; + } + + public void setPercent(BigDecimal percent) { + this.percent = percent; + } + + public String getSomeString() { + return someString; + } + + public void setSomeString(String someString) { + this.someString = someString; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public boolean isValid() { + return valid; + } + + public void setValid(boolean valid) { + this.valid = valid; + } + + } +} diff --git a/persistence-modules/hibernate-ogm/pom.xml b/persistence-modules/hibernate-ogm/pom.xml index 2ccac03bd3..7ac29b1720 100644 --- a/persistence-modules/hibernate-ogm/pom.xml +++ b/persistence-modules/hibernate-ogm/pom.xml @@ -19,31 +19,31 @@ org.hibernate.ogm hibernate-ogm-mongodb - 5.4.0.Final + ${hibernate.version} org.hibernate.ogm hibernate-ogm-neo4j - 5.4.0.Final + ${hibernate.version} org.jboss.narayana.jta narayana-jta - 5.5.23.Final + ${narayana-jta.version} junit junit - 4.12 + ${junit.version} test org.easytesting fest-assert - 1.4 + ${fest-assert.version} test @@ -57,4 +57,10 @@ + + + 5.4.0.Final + 1.4 + 5.5.23.Final + \ No newline at end of file diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index 68008bc8fe..65322f0cea 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -33,3 +33,4 @@ - [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) - [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) - [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) +- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 7a9fdc0d34..bf4b2d27ec 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -60,7 +60,7 @@ org.hibernate hibernate-testing - 5.2.2.Final + ${hibernate.version} com.fasterxml.jackson.core @@ -70,7 +70,7 @@ net.bytebuddy byte-buddy - 1.9.5 + ${byte-buddy.version} @@ -91,7 +91,7 @@ javax.xml.bind jaxb-api - 2.3.0 + ${jaxb-api.version} @@ -120,6 +120,8 @@ 3.8.0 1.21 0.9 + 1.9.5 + 2.3.0
diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index aac5d49547..708d2b3c76 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -39,6 +39,7 @@ 3.1.2 3.1.1.0 + 18.0
diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index ca9ec0d74d..5a99217f45 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -8,6 +8,9 @@ - [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) - [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates) - [Types of JPA Queries](https://www.baeldung.com/jpa-queries) +- [JPA/Hibernate Projections](https://www.baeldung.com/jpa-hibernate-projections) +- [Composite Primary Keys in JPA](https://www.baeldung.com/jpa-composite-primary-keys) - [Defining JPA Entities](https://www.baeldung.com/jpa-entities) - [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation) - [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values) +- [Persisting Enums in JPA](https://www.baeldung.com/jpa-persisting-enums-in-jpa) diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index f23040fbdc..ced049d281 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -19,6 +19,11 @@ hibernate-core ${hibernate.version} + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + com.h2database h2 @@ -29,7 +34,7 @@ javax.persistence javax.persistence-api - 2.2 + ${javax.persistence-api.version} @@ -47,10 +52,64 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + -proc:none + + + + org.bsc.maven + maven-processor-plugin + 3.3.3 + + + process + + process + + generate-sources + + target/metamodel + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + target/metamodel + + + + + + + + 5.4.0.Final 2.7.4-RC1 42.2.5 + 2.2 \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java new file mode 100644 index 0000000000..bf3d459530 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java @@ -0,0 +1,79 @@ +package com.baeldung.jpa.queryparams; + +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 = "employees") +public class Employee { + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "employee_number", unique = true) + private String empNumber; + + @Column(name = "employee_name") + private String name; + + @Column(name = "employee_age") + private int age; + + public Employee() { + super(); + } + + public Employee(Long id, String empNumber) { + super(); + this.id = id; + this.empNumber = empNumber; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmpNumber() { + return empNumber; + } + + public void setEmpNumber(String empNumber) { + this.empNumber = empNumber; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + +} 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 1f16bee3ba..6a236f0840 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 @@ -224,4 +224,26 @@ value="products_jpa.sql" /> + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.queryparams.Employee + true + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java new file mode 100644 index 0000000000..4f320935cf --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java @@ -0,0 +1,109 @@ +package com.baeldung.jpa.queryparams; + +import java.util.Arrays; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.ParameterExpression; +import javax.persistence.criteria.Root; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * JPAQueryParamsTest class tests. + * + * @author gmlopez.mackinnon@gmail.com + */ +public class JPAQueryParamsUnitTest { + + private static EntityManager entityManager; + + @BeforeClass + public static void setup() { + EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-queryparams"); + entityManager = factory.createEntityManager(); + } + + @Test + public void givenEmpNumber_whenUsingPositionalParameter_thenReturnExpectedEmployee() { + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber = ?1", Employee.class); + String empNumber = "A123"; + Employee employee = query.setParameter(1, empNumber) + .getSingleResult(); + Assert.assertNotNull("Employee not found", employee); + } + + @Test + public void givenEmpNumberList_whenUsingPositionalParameter_thenReturnExpectedEmployee() { + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber IN (?1)", Employee.class); + List empNumbers = Arrays.asList("A123", "A124"); + List employees = query.setParameter(1, empNumbers) + .getResultList(); + Assert.assertNotNull("Employees not found", employees); + Assert.assertFalse("Employees not found", employees.isEmpty()); + } + + @Test + public void givenEmpNumber_whenUsingNamedParameter_thenReturnExpectedEmployee() { + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber = :number", Employee.class); + String empNumber = "A123"; + Employee employee = query.setParameter("number", empNumber) + .getSingleResult(); + Assert.assertNotNull("Employee not found", employee); + } + + @Test + public void givenEmpNumberList_whenUsingNamedParameter_thenReturnExpectedEmployee() { + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber IN (:numbers)", Employee.class); + List empNumbers = Arrays.asList("A123", "A124"); + List employees = query.setParameter("numbers", empNumbers) + .getResultList(); + Assert.assertNotNull("Employees not found", employees); + Assert.assertFalse("Employees not found", employees.isEmpty()); + } + + @Test + public void givenEmpNameAndEmpAge_whenUsingTwoNamedParameters_thenReturnExpectedEmployees() { + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.name = :name AND e.age = :empAge", Employee.class); + String empName = "John Doe"; + int empAge = 55; + List employees = query.setParameter("name", empName) + .setParameter("empAge", empAge) + .getResultList(); + Assert.assertNotNull("Employees not found!", employees); + Assert.assertTrue("Employees not found!", !employees.isEmpty()); + } + + @Test + public void givenEmpNumber_whenUsingCriteriaQuery_thenReturnExpectedEmployee() { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + + CriteriaQuery cQuery = cb.createQuery(Employee.class); + Root c = cQuery.from(Employee.class); + ParameterExpression paramEmpNumber = cb.parameter(String.class); + cQuery.select(c) + .where(cb.equal(c.get(Employee_.empNumber), paramEmpNumber)); + + TypedQuery query = entityManager.createQuery(cQuery); + String empNumber = "A123"; + query.setParameter(paramEmpNumber, empNumber); + Employee employee = query.getSingleResult(); + Assert.assertNotNull("Employee not found!", employee); + } + + @Test + public void givenEmpNumber_whenUsingLiteral_thenReturnExpectedEmployee() { + String empNumber = "A123"; + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber = '" + empNumber + "'", Employee.class); + Employee employee = query.getSingleResult(); + Assert.assertNotNull("Employee not found!", employee); + } + +} diff --git a/persistence-modules/java-jpa/src/test/resources/employees2.sql b/persistence-modules/java-jpa/src/test/resources/employees2.sql new file mode 100644 index 0000000000..d3ae46f6a0 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/resources/employees2.sql @@ -0,0 +1,2 @@ +INSERT INTO employees (employee_number, employee_name, employee_age) VALUES ('111', 'John Doe', 55); +INSERT INTO employees (employee_number, employee_name, employee_age) VALUES ('A123', 'John Doe Junior', 25); \ No newline at end of file diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index 0f5efedb96..35e59e60c6 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -1,42 +1,49 @@ - - 4.0.0 - com.baeldung - java-mongodb - 1.0-SNAPSHOT + + 4.0.0 + com.baeldung + java-mongodb + 1.0-SNAPSHOT java-mongodb - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + - + - - de.flapdoodle.embedmongo - de.flapdoodle.embedmongo - ${flapdoodle.version} - test - + + de.flapdoodle.embedmongo + de.flapdoodle.embedmongo + ${flapdoodle.version} + test + + + org.mongodb + mongo-java-driver + ${mongo.version} + + + dev.morphia.morphia + core + ${morphia.version} + - - org.mongodb - mongo-java-driver - ${mongo.version} - + - - - - 1.8 - 1.8 - 3.10.1 - 1.11 - + + 1.8 + 1.8 + 3.10.1 + 1.11 + 1.5.3 + diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Author.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Author.java new file mode 100644 index 0000000000..b45aee6068 --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Author.java @@ -0,0 +1,31 @@ +package com.baeldung.morphia.domain; + +import java.util.List; + +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Id; + +@Entity +public class Author { + + @Id + private String name; + private List books; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + +} diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java new file mode 100644 index 0000000000..172c916ad9 --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java @@ -0,0 +1,116 @@ +package com.baeldung.morphia.domain; + +import java.util.HashSet; +import java.util.Set; + +import dev.morphia.annotations.Embedded; +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Field; +import dev.morphia.annotations.Id; +import dev.morphia.annotations.Index; +import dev.morphia.annotations.IndexOptions; +import dev.morphia.annotations.Indexes; +import dev.morphia.annotations.Property; +import dev.morphia.annotations.Reference; +import dev.morphia.annotations.Validation; + +@Entity("Books") +@Indexes({ @Index(fields = @Field("title"), options = @IndexOptions(name = "book_title")) }) +@Validation("{ price : { $gt : 0 } }") +public class Book { + @Id + private String isbn; + @Property + private String title; + private String author; + @Embedded + private Publisher publisher; + @Property("price") + private double cost; + @Reference + private Set companionBooks; + + public Book() { + + } + + public String getTitle() { + return title; + } + + public String getAuthor() { + return author; + } + + public double getCost() { + return cost; + } + + public void addCompanionBooks(Book book) { + if (companionBooks != null) + this.companionBooks.add(book); + } + + public Book(String isbn, String title, String author, double cost, Publisher publisher) { + this.isbn = isbn; + this.title = title; + this.author = author; + this.cost = cost; + this.publisher = publisher; + this.companionBooks = new HashSet<>(); + } + + @Override + public String toString() { + return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((author == null) ? 0 : author.hashCode()); + long temp; + temp = Double.doubleToLongBits(cost); + result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + ((isbn == null) ? 0 : isbn.hashCode()); + result = prime * result + ((publisher == null) ? 0 : publisher.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Book other = (Book) obj; + if (author == null) { + if (other.author != null) + return false; + } else if (!author.equals(other.author)) + return false; + if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost)) + return false; + if (isbn == null) { + if (other.isbn != null) + return false; + } else if (!isbn.equals(other.isbn)) + return false; + if (publisher == null) { + if (other.publisher != null) + return false; + } else if (!publisher.equals(other.publisher)) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + +} \ No newline at end of file diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Publisher.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Publisher.java new file mode 100644 index 0000000000..b9e054e9ab --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Publisher.java @@ -0,0 +1,70 @@ +package com.baeldung.morphia.domain; + +import org.bson.types.ObjectId; + +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Id; + +@Entity +public class Publisher { + + @Id + private ObjectId id; + private String name; + + public Publisher() { + + } + + public Publisher(ObjectId id, String name) { + this.id = id; + this.name = name; + } + + public ObjectId getId() { + return id; + } + + public void setId(ObjectId id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Catalog [id=" + id + ", 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(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Publisher other = (Publisher) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java new file mode 100644 index 0000000000..f508c5f525 --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java @@ -0,0 +1,131 @@ +package com.baeldung.morphia; + +import static dev.morphia.aggregation.Group.grouping; +import static dev.morphia.aggregation.Group.push; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Iterator; +import java.util.List; + +import org.bson.types.ObjectId; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import com.baeldung.morphia.domain.Author; +import com.baeldung.morphia.domain.Book; +import com.baeldung.morphia.domain.Publisher; +import com.mongodb.MongoClient; + +import dev.morphia.Datastore; +import dev.morphia.Morphia; +import dev.morphia.query.Query; +import dev.morphia.query.UpdateOperations; + +@Ignore +public class MorphiaIntegrationTest { + + private static Datastore datastore; + private static ObjectId id = new ObjectId(); + + @BeforeClass + public static void setUp() { + Morphia morphia = new Morphia(); + morphia.mapPackage("com.baeldung.morphia"); + datastore = morphia.createDatastore(new MongoClient(), "library"); + datastore.ensureIndexes(); + } + + @Test + public void givenDataSource_whenCreateEntity_thenEntityCreated() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + Book companionBook = new Book("9789332575103", "Java Performance Companion", "Tom Kirkman", 1.95, publisher); + book.addCompanionBooks(companionBook); + datastore.save(companionBook); + datastore.save(book); + + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .find() + .toList(); + assertEquals(1, books.size()); + assertEquals(book, books.get(0)); + } + + @Test + public void givenDocument_whenUpdated_thenUpdateReflected() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + datastore.save(book); + Query query = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java"); + UpdateOperations updates = datastore.createUpdateOperations(Book.class) + .inc("price", 1); + datastore.update(query, updates); + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .find() + .toList(); + assertEquals(4.95, books.get(0) + .getCost()); + } + + @Test + public void givenDocument_whenDeleted_thenDeleteReflected() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + datastore.save(book); + Query query = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java"); + datastore.delete(query); + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .find() + .toList(); + assertEquals(0, books.size()); + } + + @Test + public void givenDocument_whenAggregated_thenResultsCollected() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + datastore.save(new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher)); + datastore.save(new Book("9781449313142", "Learning Perl", "Mark Pence", 2.95, publisher)); + datastore.save(new Book("9787564100476", "Learning Python", "Mark Pence", 5.95, publisher)); + datastore.save(new Book("9781449368814", "Learning Scala", "Mark Pence", 6.95, publisher)); + datastore.save(new Book("9781784392338", "Learning Go", "Jonathan Sawyer", 8.95, publisher)); + + Iterator authors = datastore.createAggregation(Book.class) + .group("author", grouping("books", push("title"))) + .out(Author.class); + + assertTrue(authors.hasNext()); + + } + + @Test + public void givenDocument_whenProjected_thenOnlyProjectionReceived() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + datastore.save(book); + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .project("title", true) + .find() + .toList(); + assertEquals(books.size(), 1); + assertEquals("Learning Java", books.get(0) + .getTitle()); + assertNull(books.get(0) + .getAuthor()); + } + +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/README.md b/persistence-modules/jpa-hibernate-cascade-type/README.md new file mode 100644 index 0000000000..d7f3d7dd7c --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Overview of JPA/Hibernate Cascade Types](https://www.baeldung.com/jpa-cascade-types) diff --git a/persistence-modules/jpa-hibernate-cascade-type/pom.xml b/persistence-modules/jpa-hibernate-cascade-type/pom.xml new file mode 100644 index 0000000000..a45f297a6b --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/pom.xml @@ -0,0 +1,71 @@ + + + jpa-hibernate-cascade-type + 4.0.0 + 1.0.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + javax.el + javax.el-api + ${javax.el-api.version} + + + org.glassfish + javax.el + ${org.glassfish.javax.el.version} + + + + + jpa-hibernate-cascade-type + + + src/test/resources + true + + + + + + 5.4.3.Final + 3.12.2 + 6.0.17.Final + 3.0.0 + 3.0.1-b11 + 1.8 + 1.8 + + + \ No newline at end of file diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/HibernateUtil.java b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/HibernateUtil.java new file mode 100644 index 0000000000..700c289e38 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/HibernateUtil.java @@ -0,0 +1,45 @@ +package com.baeldung.cascading; + +import com.baeldung.cascading.domain.Address; +import com.baeldung.cascading.domain.Person; +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +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; + + public static SessionFactory getSessionFactory() { + try { + Properties properties = getProperties(); + Configuration configuration = new Configuration(); + configuration.setProperties(properties); + configuration.addAnnotatedClass(Person.class); + configuration.addAnnotatedClass(Address.class); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()).build(); + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + return sessionFactory; + } catch (IOException e) { + e.printStackTrace(); + } + return sessionFactory; + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource("hibernate.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Address.java b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Address.java new file mode 100644 index 0000000000..a16b0f81b6 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Address.java @@ -0,0 +1,64 @@ +package com.baeldung.cascading.domain; + +import javax.persistence.*; + +@Entity +public class Address { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + private String street; + private int houseNumber; + private String city; + private int zipCode; + @ManyToOne(fetch = FetchType.LAZY) + private Person person; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Person getPerson() { + return person; + } + + public void setPerson(Person person) { + this.person = person; + } + + public String getStreet() { + return street; + } + + public int getHouseNumber() { + return houseNumber; + } + + public void setHouseNumber(int houseNumber) { + this.houseNumber = houseNumber; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public int getZipCode() { + return zipCode; + } + + public void setZipCode(int zipCode) { + this.zipCode = zipCode; + } + + public void setStreet(String street) { + this.street = street; + } +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Person.java b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Person.java new file mode 100644 index 0000000000..9ca61323b3 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.cascading.domain; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class Person { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + private String name; + @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) + private List
addresses; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public List
getAddresses() { + return addresses; + } + + public void setAddresses(List
addresses) { + this.addresses = addresses; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/test/java/com/baeldung/cascading/CasCadeTypeUnitTest.java b/persistence-modules/jpa-hibernate-cascade-type/src/test/java/com/baeldung/cascading/CasCadeTypeUnitTest.java new file mode 100644 index 0000000000..a196bdac12 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/test/java/com/baeldung/cascading/CasCadeTypeUnitTest.java @@ -0,0 +1,169 @@ +package com.baeldung.cascading; + +import com.baeldung.cascading.domain.Address; +import com.baeldung.cascading.domain.Person; +import org.assertj.core.api.Assertions; +import org.hibernate.*; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.Arrays; + +public class CasCadeTypeUnitTest { + private static SessionFactory sessionFactory; + private Session session; + private Transaction transaction; + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void testPersist() { + Person person = new Person(); + Address address = new Address(); + address.setPerson(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + session.clear(); + } + + @Test + public void testMerge() { + int addressId; + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + addressId = address.getId(); + session.clear(); + + Address savedAddressEntity = session.find(Address.class, addressId); + Person savedPersonEntity = savedAddressEntity.getPerson(); + savedPersonEntity.setName("devender kumar"); + savedAddressEntity.setHouseNumber(24); + session.merge(savedPersonEntity); + session.flush(); + } + + @Test + public void testRemove() { + int personId; + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + personId = person.getId(); + session.clear(); + + Person savedPersonEntity = session.find(Person.class, personId); + session.remove(savedPersonEntity); + session.flush(); + } + + @Test + public void testDetach() { + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + Assertions.assertThat(session.contains(person)).isTrue(); + Assertions.assertThat(session.contains(address)).isTrue(); + + session.detach(person); + Assertions.assertThat(session.contains(person)).isFalse(); + Assertions.assertThat(session.contains(address)).isFalse(); + } + + @Test + public void testLock() { + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + Assertions.assertThat(session.contains(person)).isTrue(); + Assertions.assertThat(session.contains(address)).isTrue(); + + session.detach(person); + Assertions.assertThat(session.contains(person)).isFalse(); + Assertions.assertThat(session.contains(address)).isFalse(); + session.unwrap(Session.class) + .buildLockRequest(new LockOptions(LockMode.NONE)) + .lock(person); + + Assertions.assertThat(session.contains(person)).isTrue(); + Assertions.assertThat(session.contains(address)).isTrue(); + } + + @Test + public void testRefresh() { + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + person.setName("Devender Kumar"); + address.setHouseNumber(24); + session.refresh(person); + Assertions.assertThat(person.getName()).isEqualTo("devender"); + Assertions.assertThat(address.getHouseNumber()).isEqualTo(23); + } + + @Test + public void testReplicate() { + Person person = buildPerson("devender"); + person.setId(2); + Address address = buildAddress(person); + address.setId(2); + person.setAddresses(Arrays.asList(address)); + session.unwrap(Session.class).replicate(person, ReplicationMode.OVERWRITE); + session.flush(); + Assertions.assertThat(person.getId()).isEqualTo(2); + Assertions.assertThat(address.getId()).isEqualTo(2); + } + + @Test + public void testSaveOrUpdate() { + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.saveOrUpdate(person); + session.flush(); + } + + private Address buildAddress(Person person) { + Address address = new Address(); + address.setCity("Berlin"); + address.setHouseNumber(23); + address.setStreet("Zeughofstraße"); + address.setZipCode(123001); + address.setPerson(person); + return address; + } + + private Person buildPerson(String name) { + Person person = new Person(); + person.setName(name); + return person; + } +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c22da2496b --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.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.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index ba3baf6636..390bcc9d51 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -18,6 +18,7 @@ apache-cayenne core-java-persistence deltaspike + elasticsearch flyway hbase hibernate5 @@ -56,5 +57,6 @@ spring-hibernate4 spring-jpa spring-persistence-simple + jpa-hibernate-cascade-type diff --git a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..90787681cf --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md index 40f9f40749..f277ef66ca 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/README.md +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -2,3 +2,4 @@ - [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field) - [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb) +- [Upload and Retrieve Files Using MongoDB and Spring Boot](https://www.baeldung.com/spring-boot-mongodb-upload-file) diff --git a/persistence-modules/spring-boot-persistence-mongodb/pom.xml b/persistence-modules/spring-boot-persistence-mongodb/pom.xml index 585e54bf57..dae5efa6d0 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb/pom.xml @@ -20,6 +20,10 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-thymeleaf + org.springframework.boot diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java new file mode 100644 index 0000000000..d38e11c055 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.mongodb.daos; + +import org.springframework.data.mongodb.repository.MongoRepository; + +import com.baeldung.mongodb.models.Photo; + +public interface PhotoRepository extends MongoRepository { + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java new file mode 100644 index 0000000000..13f1a3cd19 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java @@ -0,0 +1,51 @@ +package com.baeldung.mongodb.models; + +import org.bson.types.Binary; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collection = "photos") +public class Photo { + + @Id + private String id; + + private String title; + + private Binary image; + + public Photo(String title) { + super(); + this.title = title; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Binary getImage() { + return image; + } + + public void setImage(Binary image) { + this.image = image; + } + + @Override + public String toString() { + return "Photo [id=" + id + ", title=" + title + ", image=" + image + "]"; + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java new file mode 100644 index 0000000000..617f0cdbfd --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java @@ -0,0 +1,39 @@ +package com.baeldung.mongodb.models; + +import java.io.InputStream; + +public class Video { + private String title; + private InputStream stream; + + public Video() { + super(); + } + + public Video(String title) { + super(); + this.title = title; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public InputStream getStream() { + return stream; + } + + public void setStream(InputStream stream) { + this.stream = stream; + } + + @Override + public String toString() { + return "Video [title=" + title + "]"; + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java new file mode 100644 index 0000000000..d8d7541c76 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java @@ -0,0 +1,30 @@ +package com.baeldung.mongodb.services; + +import java.io.IOException; + +import org.bson.BsonBinarySubType; +import org.bson.types.Binary; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.daos.PhotoRepository; +import com.baeldung.mongodb.models.Photo; + +@Service +public class PhotoService { + + @Autowired + private PhotoRepository photoRepo; + + public Photo getPhoto(String id) { + return photoRepo.findById(id).get(); + } + + public String addPhoto(String title, MultipartFile file) throws IOException { + Photo photo = new Photo(title); + photo.setImage(new Binary(BsonBinarySubType.BINARY, file.getBytes())); + photo = photoRepo.insert(photo); + return photo.getId(); + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java new file mode 100644 index 0000000000..ade1f7c73a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java @@ -0,0 +1,44 @@ +package com.baeldung.mongodb.services; + +import java.io.IOException; + +import org.bson.types.ObjectId; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.gridfs.GridFsOperations; +import org.springframework.data.mongodb.gridfs.GridFsTemplate; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.models.Video; +import com.mongodb.BasicDBObject; +import com.mongodb.DBObject; +import com.mongodb.client.gridfs.model.GridFSFile; + +@Service +public class VideoService { + + @Autowired + private GridFsTemplate gridFsTemplate; + + @Autowired + private GridFsOperations operations; + + public Video getVideo(String id) throws IllegalStateException, IOException { + GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id))); + Video video = new Video(); + video.setTitle(file.getMetadata().get("title").toString()); + video.setStream(operations.getResource(file).getInputStream()); + return video; + } + + public String addVideo(String title, MultipartFile file) throws IOException { + DBObject metaData = new BasicDBObject(); + metaData.put("type", "video"); + metaData.put("title", title); + ObjectId id = gridFsTemplate.store(file.getInputStream(), file.getName(), file.getContentType(), metaData); + return id.toString(); + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java new file mode 100644 index 0000000000..4d5746f0d8 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java @@ -0,0 +1,43 @@ +package com.baeldung.mongodb.web; + +import java.io.IOException; +import java.util.Base64; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.models.Photo; +import com.baeldung.mongodb.services.PhotoService; + +@Controller +public class PhotoController { + + @Autowired + private PhotoService photoService; + + @GetMapping("/photos/{id}") + public String getPhoto(@PathVariable String id, Model model) { + Photo photo = photoService.getPhoto(id); + model.addAttribute("title", photo.getTitle()); + model.addAttribute("image", Base64.getEncoder().encodeToString(photo.getImage().getData())); + return "photos"; + } + + @GetMapping("/photos/upload") + public String uploadPhoto(Model model) { + model.addAttribute("message", "hello"); + return "uploadPhoto"; + } + + @PostMapping("/photos/add") + public String addPhoto(@RequestParam("title") String title, @RequestParam("image") MultipartFile image, Model model) throws IOException { + String id = photoService.addPhoto(title, image); + return "redirect:/photos/" + id; + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java new file mode 100644 index 0000000000..313ce9e650 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java @@ -0,0 +1,51 @@ +package com.baeldung.mongodb.web; + +import java.io.IOException; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.util.FileCopyUtils; +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.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.models.Video; +import com.baeldung.mongodb.services.VideoService; + +@Controller +public class VideoController { + + @Autowired + private VideoService videoService; + + @GetMapping("/videos/{id}") + public String getVideo(@PathVariable String id, Model model) throws IllegalStateException, IOException { + Video video = videoService.getVideo(id); + model.addAttribute("title", video.getTitle()); + model.addAttribute("url", "/videos/stream/" + id); + return "videos"; + } + + @GetMapping("/videos/stream/{id}") + public void streamVideo(@PathVariable String id, HttpServletResponse response) throws IllegalStateException, IOException { + Video video = videoService.getVideo(id); + FileCopyUtils.copy(video.getStream(), response.getOutputStream()); + } + + @GetMapping("/videos/upload") + public String uploadVideo(Model model) { + model.addAttribute("message", "hello"); + return "uploadVideo"; + } + + @PostMapping("/videos/add") + public String addVideo(@RequestParam("title") String title, @RequestParam("file") MultipartFile file, Model model) throws IOException { + String id = videoService.addVideo(title, file); + return "redirect:/videos/" + id; + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties index 5b1b8000d0..6548f2b28a 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties @@ -1,8 +1,13 @@ spring.application.name=spring-boot-persistence -server.port=${PORT:0} +server.port=8082 #spring boot mongodb spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=springboot-mongo +spring.thymeleaf.cache=false + +spring.servlet.multipart.max-file-size=256MB +spring.servlet.multipart.max-request-size=256MB +spring.servlet.multipart.enabled=true \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/index.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/index.html new file mode 100644 index 0000000000..f99e9caa8b --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/index.html @@ -0,0 +1,14 @@ + + + +Upload Files MongoDB + + +

Home Page

+
Message
+
+ Upload new Photo +

+ Upload new Video + + diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/photos.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/photos.html new file mode 100644 index 0000000000..b5d56d020a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/photos.html @@ -0,0 +1,10 @@ + + +

View Photo

+ Title: name +
+ sample +

+ Back to home page + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadPhoto.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadPhoto.html new file mode 100644 index 0000000000..6d51c06d8f --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadPhoto.html @@ -0,0 +1,15 @@ + + + +

Upload new Photo

+
+ Title: +
+ Image: +
+
+ +
+ + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadVideo.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadVideo.html new file mode 100644 index 0000000000..ebc29d98e2 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadVideo.html @@ -0,0 +1,15 @@ + + + +

Upload new Video

+
+ Title: +
+ Video: +
+
+ +
+ + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/videos.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/videos.html new file mode 100644 index 0000000000..b0ee0fc577 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/videos.html @@ -0,0 +1,15 @@ + + +

View Video

+ Title: title +
+
+ + + +

+ Back to home page + + \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra-reactive/pom.xml b/persistence-modules/spring-data-cassandra-reactive/pom.xml index 5a34d90c9f..288f842201 100644 --- a/persistence-modules/spring-data-cassandra-reactive/pom.xml +++ b/persistence-modules/spring-data-cassandra-reactive/pom.xml @@ -46,6 +46,13 @@ reactor-test test
+ + org.cassandraunit + cassandra-unit-spring + ${cassandra-unit-spring.version} + test + + @@ -53,6 +60,7 @@ UTF-8 2.1.2.RELEASE + 3.11.2.0 diff --git a/persistence-modules/spring-data-cassandra-reactive/src/test/java/com/baeldung/cassandra/reactive/ReactiveEmployeeRepositoryIntegrationTest.java b/persistence-modules/spring-data-cassandra-reactive/src/test/java/com/baeldung/cassandra/reactive/ReactiveEmployeeRepositoryIntegrationTest.java index ad726fe969..ae314db5e7 100644 --- a/persistence-modules/spring-data-cassandra-reactive/src/test/java/com/baeldung/cassandra/reactive/ReactiveEmployeeRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-cassandra-reactive/src/test/java/com/baeldung/cassandra/reactive/ReactiveEmployeeRepositoryIntegrationTest.java @@ -1,13 +1,23 @@ package com.baeldung.cassandra.reactive; -import com.baeldung.cassandra.reactive.model.Employee; -import com.baeldung.cassandra.reactive.repository.EmployeeRepository; +import org.cassandraunit.spring.CassandraDataSet; +import org.cassandraunit.spring.CassandraUnitDependencyInjectionTestExecutionListener; +import org.cassandraunit.spring.CassandraUnitTestExecutionListener; +import org.cassandraunit.spring.EmbeddedCassandra; 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.TestExecutionListeners; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; +import org.springframework.test.context.web.ServletTestExecutionListener; + +import com.baeldung.cassandra.reactive.model.Employee; +import com.baeldung.cassandra.reactive.repository.EmployeeRepository; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -15,6 +25,15 @@ import reactor.test.StepVerifier; @RunWith(SpringRunner.class) @SpringBootTest +@TestExecutionListeners(listeners = { + CassandraUnitDependencyInjectionTestExecutionListener.class, + CassandraUnitTestExecutionListener.class, + ServletTestExecutionListener.class, + DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class +}) +@EmbeddedCassandra(timeout = 60000, configuration = "cassandra-server.yaml") +@CassandraDataSet(value = {"cassandra-init.cql"}, keyspace = "practice") public class ReactiveEmployeeRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-cassandra-reactive/src/test/resources/cassandra-init.cql b/persistence-modules/spring-data-cassandra-reactive/src/test/resources/cassandra-init.cql new file mode 100644 index 0000000000..b28fda5320 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/test/resources/cassandra-init.cql @@ -0,0 +1,7 @@ +CREATE TABLE employee( + id int PRIMARY KEY, + name text, + address text, + email text, + age int +); \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra-reactive/src/test/resources/cassandra-server.yaml b/persistence-modules/spring-data-cassandra-reactive/src/test/resources/cassandra-server.yaml new file mode 100644 index 0000000000..af3fb21e54 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/test/resources/cassandra-server.yaml @@ -0,0 +1,590 @@ +# Cassandra storage config YAML + +# NOTE: +# See http://wiki.apache.org/cassandra/StorageConfiguration for +# full explanations of configuration directives +# /NOTE + +# The name of the cluster. This is mainly used to prevent machines in +# one logical cluster from joining another. +cluster_name: 'Test Cluster' + +# You should always specify InitialToken when setting up a production +# cluster for the first time, and often when adding capacity later. +# The principle is that each node should be given an equal slice of +# the token ring; see http://wiki.apache.org/cassandra/Operations +# for more details. +# +# If blank, Cassandra will request a token bisecting the range of +# the heaviest-loaded existing node. If there is no load information +# available, such as is the case with a new cluster, it will pick +# a random token, which will lead to hot spots. +#initial_token: + +# See http://wiki.apache.org/cassandra/HintedHandoff +hinted_handoff_enabled: true +# this defines the maximum amount of time a dead host will have hints +# generated. After it has been dead this long, new hints for it will not be +# created until it has been seen alive and gone down again. +max_hint_window_in_ms: 10800000 # 3 hours +# Maximum throttle in KBs per second, per delivery thread. This will be +# reduced proportionally to the number of nodes in the cluster. (If there +# are two nodes in the cluster, each delivery thread will use the maximum +# rate; if there are three, each will throttle to half of the maximum, +# since we expect two nodes to be delivering hints simultaneously.) +hinted_handoff_throttle_in_kb: 1024 +# Number of threads with which to deliver hints; +# Consider increasing this number when you have multi-dc deployments, since +# cross-dc handoff tends to be slower +max_hints_delivery_threads: 2 + +hints_directory: target/embeddedCassandra/hints + +# The following setting populates the page cache on memtable flush and compaction +# WARNING: Enable this setting only when the whole node's data fits in memory. +# Defaults to: false +# populate_io_cache_on_flush: false + +# Authentication backend, implementing IAuthenticator; used to identify users +# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthenticator, +# PasswordAuthenticator}. +# +# - AllowAllAuthenticator performs no checks - set it to disable authentication. +# - PasswordAuthenticator relies on username/password pairs to authenticate +# users. It keeps usernames and hashed passwords in system_auth.credentials table. +# Please increase system_auth keyspace replication factor if you use this authenticator. +authenticator: AllowAllAuthenticator + +# Authorization backend, implementing IAuthorizer; used to limit access/provide permissions +# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthorizer, +# CassandraAuthorizer}. +# +# - AllowAllAuthorizer allows any action to any user - set it to disable authorization. +# - CassandraAuthorizer stores permissions in system_auth.permissions table. Please +# increase system_auth keyspace replication factor if you use this authorizer. +authorizer: AllowAllAuthorizer + +# Validity period for permissions cache (fetching permissions can be an +# expensive operation depending on the authorizer, CassandraAuthorizer is +# one example). Defaults to 2000, set to 0 to disable. +# Will be disabled automatically for AllowAllAuthorizer. +permissions_validity_in_ms: 2000 + + +# The partitioner is responsible for distributing rows (by key) across +# nodes in the cluster. Any IPartitioner may be used, including your/m +# own as long as it is on the classpath. Out of the box, Cassandra +# provides org.apache.cassandra.dht.{Murmur3Partitioner, RandomPartitioner +# ByteOrderedPartitioner, OrderPreservingPartitioner (deprecated)}. +# +# - RandomPartitioner distributes rows across the cluster evenly by md5. +# This is the default prior to 1.2 and is retained for compatibility. +# - Murmur3Partitioner is similar to RandomPartioner but uses Murmur3_128 +# Hash Function instead of md5. When in doubt, this is the best option. +# - ByteOrderedPartitioner orders rows lexically by key bytes. BOP allows +# scanning rows in key order, but the ordering can generate hot spots +# for sequential insertion workloads. +# - OrderPreservingPartitioner is an obsolete form of BOP, that stores +# - keys in a less-efficient format and only works with keys that are +# UTF8-encoded Strings. +# - CollatingOPP collates according to EN,US rules rather than lexical byte +# ordering. Use this as an example if you need custom collation. +# +# See http://wiki.apache.org/cassandra/Operations for more on +# partitioners and token selection. +partitioner: org.apache.cassandra.dht.Murmur3Partitioner + +# directories where Cassandra should store data on disk. +data_file_directories: + - target/embeddedCassandra/data + +# commit log +commitlog_directory: target/embeddedCassandra/commitlog + +cdc_raw_directory: target/embeddedCassandra/cdc + +# policy for data disk failures: +# stop: shut down gossip and Thrift, leaving the node effectively dead, but +# can still be inspected via JMX. +# best_effort: stop using the failed disk and respond to requests based on +# remaining available sstables. This means you WILL see obsolete +# data at CL.ONE! +# ignore: ignore fatal errors and let requests fail, as in pre-1.2 Cassandra +disk_failure_policy: stop + + +# Maximum size of the key cache in memory. +# +# Each key cache hit saves 1 seek and each row cache hit saves 2 seeks at the +# minimum, sometimes more. The key cache is fairly tiny for the amount of +# time it saves, so it's worthwhile to use it at large numbers. +# The row cache saves even more time, but must store the whole values of +# its rows, so it is extremely space-intensive. It's best to only use the +# row cache if you have hot rows or static rows. +# +# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup. +# +# Default value is empty to make it "auto" (min(5% of Heap (in MB), 100MB)). Set to 0 to disable key cache. +key_cache_size_in_mb: + +# Duration in seconds after which Cassandra should +# safe the keys cache. Caches are saved to saved_caches_directory as +# specified in this configuration file. +# +# Saved caches greatly improve cold-start speeds, and is relatively cheap in +# terms of I/O for the key cache. Row cache saving is much more expensive and +# has limited use. +# +# Default is 14400 or 4 hours. +key_cache_save_period: 14400 + +# Number of keys from the key cache to save +# Disabled by default, meaning all keys are going to be saved +# key_cache_keys_to_save: 100 + +# Maximum size of the row cache in memory. +# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup. +# +# Default value is 0, to disable row caching. +row_cache_size_in_mb: 0 + +# Duration in seconds after which Cassandra should +# safe the row cache. Caches are saved to saved_caches_directory as specified +# in this configuration file. +# +# Saved caches greatly improve cold-start speeds, and is relatively cheap in +# terms of I/O for the key cache. Row cache saving is much more expensive and +# has limited use. +# +# Default is 0 to disable saving the row cache. +row_cache_save_period: 0 + +# Number of keys from the row cache to save +# Disabled by default, meaning all keys are going to be saved +# row_cache_keys_to_save: 100 + +# saved caches +saved_caches_directory: target/embeddedCassandra/saved_caches + +# commitlog_sync may be either "periodic" or "batch." +# When in batch mode, Cassandra won't ack writes until the commit log +# has been fsynced to disk. It will wait up to +# commitlog_sync_batch_window_in_ms milliseconds for other writes, before +# performing the sync. +# +# commitlog_sync: batch +# commitlog_sync_batch_window_in_ms: 50 +# +# the other option is "periodic" where writes may be acked immediately +# and the CommitLog is simply synced every commitlog_sync_period_in_ms +# milliseconds. +commitlog_sync: periodic +commitlog_sync_period_in_ms: 10000 + +# The size of the individual commitlog file segments. A commitlog +# segment may be archived, deleted, or recycled once all the data +# in it (potentially from each columnfamily in the system) has been +# flushed to sstables. +# +# The default size is 32, which is almost always fine, but if you are +# archiving commitlog segments (see commitlog_archiving.properties), +# then you probably want a finer granularity of archiving; 8 or 16 MB +# is reasonable. +commitlog_segment_size_in_mb: 32 + +# any class that implements the SeedProvider interface and has a +# constructor that takes a Map of parameters will do. +seed_provider: + # Addresses of hosts that are deemed contact points. + # Cassandra nodes use this list of hosts to find each other and learn + # the topology of the ring. You must change this if you are running + # multiple nodes! + - class_name: org.apache.cassandra.locator.SimpleSeedProvider + parameters: + # seeds is actually a comma-delimited list of addresses. + # Ex: ",," + - seeds: "127.0.0.1" + + +# For workloads with more data than can fit in memory, Cassandra's +# bottleneck will be reads that need to fetch data from +# disk. "concurrent_reads" should be set to (16 * number_of_drives) in +# order to allow the operations to enqueue low enough in the stack +# that the OS and drives can reorder them. +# +# On the other hand, since writes are almost never IO bound, the ideal +# number of "concurrent_writes" is dependent on the number of cores in +# your system; (8 * number_of_cores) is a good rule of thumb. +concurrent_reads: 32 +concurrent_writes: 32 + +# Total memory to use for memtables. Cassandra will flush the largest +# memtable when this much memory is used. +# If omitted, Cassandra will set it to 1/3 of the heap. +# memtable_total_space_in_mb: 2048 + +# Total space to use for commitlogs. +# If space gets above this value (it will round up to the next nearest +# segment multiple), Cassandra will flush every dirty CF in the oldest +# segment and remove it. +# commitlog_total_space_in_mb: 4096 + +# This sets the amount of memtable flush writer threads. These will +# be blocked by disk io, and each one will hold a memtable in memory +# while blocked. If you have a large heap and many data directories, +# you can increase this value for better flush performance. +# By default this will be set to the amount of data directories defined. +#memtable_flush_writers: 1 + +# the number of full memtables to allow pending flush, that is, +# waiting for a writer thread. At a minimum, this should be set to +# the maximum number of secondary indexes created on a single CF. +#memtable_flush_queue_size: 4 + +# Whether to, when doing sequential writing, fsync() at intervals in +# order to force the operating system to flush the dirty +# buffers. Enable this to avoid sudden dirty buffer flushing from +# impacting read latencies. Almost always a good idea on SSD:s; not +# necessarily on platters. +trickle_fsync: false +trickle_fsync_interval_in_kb: 10240 + +# TCP port, for commands and data +storage_port: 7010 + +# SSL port, for encrypted communication. Unused unless enabled in +# encryption_options +ssl_storage_port: 7011 + +# Address to bind to and tell other Cassandra nodes to connect to. You +# _must_ change this if you want multiple nodes to be able to +# communicate! +# +# Leaving it blank leaves it up to InetAddress.getLocalHost(). This +# will always do the Right Thing *if* the node is properly configured +# (hostname, name resolution, etc), and the Right Thing is to use the +# address associated with the hostname (it might not be). +# +# Setting this to 0.0.0.0 is always wrong. +listen_address: 127.0.0.1 + +start_native_transport: true +# port for the CQL native transport to listen for clients on +native_transport_port: 9042 + +# Whether to start the thrift rpc server. +start_rpc: true + +# Address to broadcast to other Cassandra nodes +# Leaving this blank will set it to the same value as listen_address +# broadcast_address: 1.2.3.4 + +# The address to bind the Thrift RPC service to -- clients connect +# here. Unlike ListenAddress above, you *can* specify 0.0.0.0 here if +# you want Thrift to listen on all interfaces. +# +# Leaving this blank has the same effect it does for ListenAddress, +# (i.e. it will be based on the configured hostname of the node). +rpc_address: localhost +# port for Thrift to listen for clients on +rpc_port: 9171 + +# enable or disable keepalive on rpc connections +rpc_keepalive: true + +# Cassandra provides three options for the RPC Server: +# +# sync -> One connection per thread in the rpc pool (see below). +# For a very large number of clients, memory will be your limiting +# factor; on a 64 bit JVM, 128KB is the minimum stack size per thread. +# Connection pooling is very, very strongly recommended. +# +# async -> Nonblocking server implementation with one thread to serve +# rpc connections. This is not recommended for high throughput use +# cases. Async has been tested to be about 50% slower than sync +# or hsha and is deprecated: it will be removed in the next major release. +# +# hsha -> Stands for "half synchronous, half asynchronous." The rpc thread pool +# (see below) is used to manage requests, but the threads are multiplexed +# across the different clients. +# +# The default is sync because on Windows hsha is about 30% slower. On Linux, +# sync/hsha performance is about the same, with hsha of course using less memory. +rpc_server_type: sync + +# Uncomment rpc_min|max|thread to set request pool size. +# You would primarily set max for the sync server to safeguard against +# misbehaved clients; if you do hit the max, Cassandra will block until one +# disconnects before accepting more. The defaults for sync are min of 16 and max +# unlimited. +# +# For the Hsha server, the min and max both default to quadruple the number of +# CPU cores. +# +# This configuration is ignored by the async server. +# +# rpc_min_threads: 16 +# rpc_max_threads: 2048 + +# uncomment to set socket buffer sizes on rpc connections +# rpc_send_buff_size_in_bytes: +# rpc_recv_buff_size_in_bytes: + +# Frame size for thrift (maximum field length). +# 0 disables TFramedTransport in favor of TSocket. This option +# is deprecated; we strongly recommend using Framed mode. +thrift_framed_transport_size_in_mb: 15 + +# The max length of a thrift message, including all fields and +# internal thrift overhead. +thrift_max_message_length_in_mb: 16 + +# Set to true to have Cassandra create a hard link to each sstable +# flushed or streamed locally in a backups/ subdirectory of the +# Keyspace data. Removing these links is the operator's +# responsibility. +incremental_backups: false + +# Whether or not to take a snapshot before each compaction. Be +# careful using this option, since Cassandra won't clean up the +# snapshots for you. Mostly useful if you're paranoid when there +# is a data format change. +snapshot_before_compaction: false + +# Whether or not a snapshot is taken of the data before keyspace truncation +# or dropping of column families. The STRONGLY advised default of true +# should be used to provide data safety. If you set this flag to false, you will +# lose data on truncation or drop. +auto_snapshot: false + +# Add column indexes to a row after its contents reach this size. +# Increase if your column values are large, or if you have a very large +# number of columns. The competing causes are, Cassandra has to +# deserialize this much of the row to read a single column, so you want +# it to be small - at least if you do many partial-row reads - but all +# the index data is read for each access, so you don't want to generate +# that wastefully either. +column_index_size_in_kb: 64 + +# Size limit for rows being compacted in memory. Larger rows will spill +# over to disk and use a slower two-pass compaction process. A message +# will be logged specifying the row key. +#in_memory_compaction_limit_in_mb: 64 + +# Number of simultaneous compactions to allow, NOT including +# validation "compactions" for anti-entropy repair. Simultaneous +# compactions can help preserve read performance in a mixed read/write +# workload, by mitigating the tendency of small sstables to accumulate +# during a single long running compactions. The default is usually +# fine and if you experience problems with compaction running too +# slowly or too fast, you should look at +# compaction_throughput_mb_per_sec first. +# +# This setting has no effect on LeveledCompactionStrategy. +# +# concurrent_compactors defaults to the number of cores. +# Uncomment to make compaction mono-threaded, the pre-0.8 default. +#concurrent_compactors: 1 + +# Multi-threaded compaction. When enabled, each compaction will use +# up to one thread per core, plus one thread per sstable being merged. +# This is usually only useful for SSD-based hardware: otherwise, +# your concern is usually to get compaction to do LESS i/o (see: +# compaction_throughput_mb_per_sec), not more. +#multithreaded_compaction: false + +# Throttles compaction to the given total throughput across the entire +# system. The faster you insert data, the faster you need to compact in +# order to keep the sstable count down, but in general, setting this to +# 16 to 32 times the rate you are inserting data is more than sufficient. +# Setting this to 0 disables throttling. Note that this account for all types +# of compaction, including validation compaction. +compaction_throughput_mb_per_sec: 16 + +# Track cached row keys during compaction, and re-cache their new +# positions in the compacted sstable. Disable if you use really large +# key caches. +#compaction_preheat_key_cache: true + +# Throttles all outbound streaming file transfers on this node to the +# given total throughput in Mbps. This is necessary because Cassandra does +# mostly sequential IO when streaming data during bootstrap or repair, which +# can lead to saturating the network connection and degrading rpc performance. +# When unset, the default is 200 Mbps or 25 MB/s. +# stream_throughput_outbound_megabits_per_sec: 200 + +# How long the coordinator should wait for read operations to complete +read_request_timeout_in_ms: 5000 +# How long the coordinator should wait for seq or index scans to complete +range_request_timeout_in_ms: 10000 +# How long the coordinator should wait for writes to complete +write_request_timeout_in_ms: 2000 +# How long a coordinator should continue to retry a CAS operation +# that contends with other proposals for the same row +cas_contention_timeout_in_ms: 1000 +# How long the coordinator should wait for truncates to complete +# (This can be much longer, because unless auto_snapshot is disabled +# we need to flush first so we can snapshot before removing the data.) +truncate_request_timeout_in_ms: 60000 +# The default timeout for other, miscellaneous operations +request_timeout_in_ms: 10000 + +# Enable operation timeout information exchange between nodes to accurately +# measure request timeouts. If disabled, replicas will assume that requests +# were forwarded to them instantly by the coordinator, which means that +# under overload conditions we will waste that much extra time processing +# already-timed-out requests. +# +# Warning: before enabling this property make sure to ntp is installed +# and the times are synchronized between the nodes. +cross_node_timeout: false + +# Enable socket timeout for streaming operation. +# When a timeout occurs during streaming, streaming is retried from the start +# of the current file. This _can_ involve re-streaming an important amount of +# data, so you should avoid setting the value too low. +# Default value is 0, which never timeout streams. +# streaming_socket_timeout_in_ms: 0 + +# phi value that must be reached for a host to be marked down. +# most users should never need to adjust this. +# phi_convict_threshold: 8 + +# endpoint_snitch -- Set this to a class that implements +# IEndpointSnitch. The snitch has two functions: +# - it teaches Cassandra enough about your network topology to route +# requests efficiently +# - it allows Cassandra to spread replicas around your cluster to avoid +# correlated failures. It does this by grouping machines into +# "datacenters" and "racks." Cassandra will do its best not to have +# more than one replica on the same "rack" (which may not actually +# be a physical location) +# +# IF YOU CHANGE THE SNITCH AFTER DATA IS INSERTED INTO THE CLUSTER, +# YOU MUST RUN A FULL REPAIR, SINCE THE SNITCH AFFECTS WHERE REPLICAS +# ARE PLACED. +# +# Out of the box, Cassandra provides +# - SimpleSnitch: +# Treats Strategy order as proximity. This improves cache locality +# when disabling read repair, which can further improve throughput. +# Only appropriate for single-datacenter deployments. +# - PropertyFileSnitch: +# Proximity is determined by rack and data center, which are +# explicitly configured in cassandra-topology.properties. +# - RackInferringSnitch: +# Proximity is determined by rack and data center, which are +# assumed to correspond to the 3rd and 2nd octet of each node's +# IP address, respectively. Unless this happens to match your +# deployment conventions (as it did Facebook's), this is best used +# as an example of writing a custom Snitch class. +# - Ec2Snitch: +# Appropriate for EC2 deployments in a single Region. Loads Region +# and Availability Zone information from the EC2 API. The Region is +# treated as the Datacenter, and the Availability Zone as the rack. +# Only private IPs are used, so this will not work across multiple +# Regions. +# - Ec2MultiRegionSnitch: +# Uses public IPs as broadcast_address to allow cross-region +# connectivity. (Thus, you should set seed addresses to the public +# IP as well.) You will need to open the storage_port or +# ssl_storage_port on the public IP firewall. (For intra-Region +# traffic, Cassandra will switch to the private IP after +# establishing a connection.) +# +# You can use a custom Snitch by setting this to the full class name +# of the snitch, which will be assumed to be on your classpath. +endpoint_snitch: SimpleSnitch + +# controls how often to perform the more expensive part of host score +# calculation +dynamic_snitch_update_interval_in_ms: 100 +# controls how often to reset all host scores, allowing a bad host to +# possibly recover +dynamic_snitch_reset_interval_in_ms: 600000 +# if set greater than zero and read_repair_chance is < 1.0, this will allow +# 'pinning' of replicas to hosts in order to increase cache capacity. +# The badness threshold will control how much worse the pinned host has to be +# before the dynamic snitch will prefer other replicas over it. This is +# expressed as a double which represents a percentage. Thus, a value of +# 0.2 means Cassandra would continue to prefer the static snitch values +# until the pinned host was 20% worse than the fastest. +dynamic_snitch_badness_threshold: 0.1 + +# request_scheduler -- Set this to a class that implements +# RequestScheduler, which will schedule incoming client requests +# according to the specific policy. This is useful for multi-tenancy +# with a single Cassandra cluster. +# NOTE: This is specifically for requests from the client and does +# not affect inter node communication. +# org.apache.cassandra.scheduler.NoScheduler - No scheduling takes place +# org.apache.cassandra.scheduler.RoundRobinScheduler - Round robin of +# client requests to a node with a separate queue for each +# request_scheduler_id. The scheduler is further customized by +# request_scheduler_options as described below. +request_scheduler: org.apache.cassandra.scheduler.NoScheduler + +# Scheduler Options vary based on the type of scheduler +# NoScheduler - Has no options +# RoundRobin +# - throttle_limit -- The throttle_limit is the number of in-flight +# requests per client. Requests beyond +# that limit are queued up until +# running requests can complete. +# The value of 80 here is twice the number of +# concurrent_reads + concurrent_writes. +# - default_weight -- default_weight is optional and allows for +# overriding the default which is 1. +# - weights -- Weights are optional and will default to 1 or the +# overridden default_weight. The weight translates into how +# many requests are handled during each turn of the +# RoundRobin, based on the scheduler id. +# +# request_scheduler_options: +# throttle_limit: 80 +# default_weight: 5 +# weights: +# Keyspace1: 1 +# Keyspace2: 5 + +# request_scheduler_id -- An identifer based on which to perform +# the request scheduling. Currently the only valid option is keyspace. +# request_scheduler_id: keyspace + +# index_interval controls the sampling of entries from the primrary +# row index in terms of space versus time. The larger the interval, +# the smaller and less effective the sampling will be. In technicial +# terms, the interval coresponds to the number of index entries that +# are skipped between taking each sample. All the sampled entries +# must fit in memory. Generally, a value between 128 and 512 here +# coupled with a large key cache size on CFs results in the best trade +# offs. This value is not often changed, however if you have many +# very small rows (many to an OS page), then increasing this will +# often lower memory usage without a impact on performance. +index_interval: 128 + +# Enable or disable inter-node encryption +# Default settings are TLS v1, RSA 1024-bit keys (it is imperative that +# users generate their own keys) TLS_RSA_WITH_AES_128_CBC_SHA as the cipher +# suite for authentication, key exchange and encryption of the actual data transfers. +# NOTE: No custom encryption options are enabled at the moment +# The available internode options are : all, none, dc, rack +# +# If set to dc cassandra will encrypt the traffic between the DCs +# If set to rack cassandra will encrypt the traffic between the racks +# +# The passwords used in these options must match the passwords used when generating +# the keystore and truststore. For instructions on generating these files, see: +# http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore +# +encryption_options: + internode_encryption: none + keystore: conf/.keystore + keystore_password: cassandra + truststore: conf/.truststore + truststore_password: cassandra + # More advanced defaults below: + # protocol: TLS + # algorithm: SunX509 + # store_type: JKS + # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA] \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..89e729da86 --- /dev/null +++ b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + 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/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4c69245f65 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3772e22137 --- /dev/null +++ b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index 6b73729f9a..1f7de81c02 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -1,7 +1,3 @@ -========= - -## Spring Data JPA Example Project - ### Relevant Articles: - [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby) - [JPA Join Types](https://www.baeldung.com/jpa-join-types) @@ -15,3 +11,5 @@ - [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs) - [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update) - [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) +- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) +- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) diff --git a/persistence-modules/spring-data-jpa-2/pom.xml b/persistence-modules/spring-data-jpa-2/pom.xml index fbc19810ef..08be64670b 100644 --- a/persistence-modules/spring-data-jpa-2/pom.xml +++ b/persistence-modules/spring-data-jpa-2/pom.xml @@ -29,7 +29,7 @@ net.ttddyy datasource-proxy - 1.4.1 + ${datasource-proxy.version} @@ -42,4 +42,8 @@ spring-oxm + + + 1.4.1 + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml index a7788065c9..af92f331d1 100644 --- a/persistence-modules/spring-data-jpa/pom.xml +++ b/persistence-modules/spring-data-jpa/pom.xml @@ -37,14 +37,14 @@ org.testcontainers postgresql - 1.10.6 + ${testcontainers.postgresql.version} test org.postgresql postgresql - 42.2.5 + ${postgresql.version} @@ -66,7 +66,7 @@ com.google.guava guava - 21.0 + ${guava.version} @@ -92,6 +92,9 @@ com.baeldung.boot.Application + 1.10.6 + 42.2.5 + 21.0 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..db7b156415 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.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.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e6cc5c15af --- /dev/null +++ b/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index 7156cdf071..33ad3a5267 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -21,7 +21,7 @@ org.springframework.data spring-data-releasetrain - Lovelace-SR3 + Lovelace-SR9 pom @@ -95,7 +95,7 @@ - 2.1.2.RELEASE + 2.1.9.RELEASE 4.1.4 1.1.3 1.9.2 diff --git a/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5bf54fc0bd --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index fb80b0413f..4ae8ac0a87 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -79,6 +79,21 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + true + true + -Xmx1024m + + + + + 3.2.4 2.9.0 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 index e48aa1e06a..1333f94653 100644 --- 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 @@ -2,6 +2,9 @@ package com.baeldung.spring.data.reactive.redis.template; import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; + +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -9,22 +12,40 @@ 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.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.junit4.SpringRunner; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import redis.embedded.RedisServerBuilder; +import java.io.IOException; import java.nio.ByteBuffer; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class RedisKeyCommandsIntegrationTest { + + private static redis.embedded.RedisServer redisServer; @Autowired private ReactiveKeyCommands keyCommands; @Autowired private ReactiveStringCommands stringCommands; + + @BeforeClass + public static void startRedisServer() throws IOException { + redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() throws IOException { + redisServer.stop(); + } @Test public void givenFluxOfKeys_whenPerformOperations_thenPerformOperations() { 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 index 3ebeff87b1..88c4fa6eed 100644 --- 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 @@ -2,27 +2,48 @@ package com.baeldung.spring.data.reactive.redis.template; import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; + +import java.io.IOException; + +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.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.ReactiveListOperations; import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.junit4.SpringRunner; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import redis.embedded.RedisServerBuilder; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class RedisTemplateListOpsIntegrationTest { private static final String LIST_NAME = "demo_list"; + private static redis.embedded.RedisServer redisServer; @Autowired private ReactiveRedisTemplate redisTemplate; private ReactiveListOperations reactiveListOps; + + @BeforeClass + public static void startRedisServer() throws IOException { + redisServer = new RedisServerBuilder().port(6379).setting("maxheap 128M").build(); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() throws IOException { + redisServer.stop(); + } @Before public void setup() { 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 index 9490568089..afa5267582 100644 --- 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 @@ -1,29 +1,51 @@ 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 java.io.IOException; +import java.time.Duration; + +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.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.data.redis.core.ReactiveValueOperations; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; +import com.baeldung.spring.data.reactive.redis.model.Employee; + import reactor.core.publisher.Mono; import reactor.test.StepVerifier; - -import java.time.Duration; +import redis.embedded.RedisServerBuilder; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class RedisTemplateValueOpsIntegrationTest { + + private static redis.embedded.RedisServer redisServer; @Autowired private ReactiveRedisTemplate redisTemplate; private ReactiveValueOperations reactiveValueOps; + + @BeforeClass + public static void startRedisServer() throws IOException { + redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() throws IOException { + redisServer.stop(); + } @Before public void setup() { 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 99febb6430..1c69b63c09 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 @@ -19,9 +19,11 @@ import com.baeldung.spring.data.redis.config.RedisConfig; import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; +import redis.embedded.RedisServerBuilder; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RedisConfig.class) -@DirtiesContext(classMode = ClassMode.AFTER_CLASS) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class RedisMessageListenerIntegrationTest { private static redis.embedded.RedisServer redisServer; @@ -31,7 +33,7 @@ public class RedisMessageListenerIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new redis.embedded.RedisServer(6380); + redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); 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 43aadefc01..b1a36475c3 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 @@ -20,9 +20,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.spring.data.redis.config.RedisConfig; import com.baeldung.spring.data.redis.model.Student; +import redis.embedded.RedisServerBuilder; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RedisConfig.class) -@DirtiesContext(classMode = ClassMode.AFTER_CLASS) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class StudentRepositoryIntegrationTest { @Autowired @@ -32,7 +34,7 @@ public class StudentRepositoryIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new redis.embedded.RedisServer(6380); + redisServer = new RedisServerBuilder().port(6379).setting("maxheap 128M").build(); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6652345595 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..09bf0255a0 --- /dev/null +++ b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml index ec35f35bb3..4349492370 100644 --- a/persistence-modules/spring-hibernate-3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -93,7 +93,6 @@ 8.5.8 19.0 - 3.5 diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..956d5279a3 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index 16e55cb0c0..e27775c76f 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -146,7 +146,6 @@ 21.0 - 3.5 diff --git a/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6815ebf304 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index 6f8d83aa9d..426944c149 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -9,7 +9,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 One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) - [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) ### Quick Start diff --git a/persistence-modules/spring-hibernate4/pom.xml b/persistence-modules/spring-hibernate4/pom.xml index 4289c9c3d5..c22342a34a 100644 --- a/persistence-modules/spring-hibernate4/pom.xml +++ b/persistence-modules/spring-hibernate4/pom.xml @@ -7,10 +7,10 @@ spring-hibernate4 + parent-spring-4 com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + 0.0.1-SNAPSHOT + ../../parent-spring-4 @@ -167,7 +167,6 @@ 19.0 - 3.5 4.4.1 4.5 @@ -176,7 +175,6 @@ 2.7 - 1.6.1 diff --git a/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6815ebf304 --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 0fdffad8db..0961cabaff 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -174,11 +174,7 @@ 21.0 - 3.5 3.8.0 - - - 2.6 \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..291e49d0c4 --- /dev/null +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.baeldung.config.PersistenceJPAConfigL2Cache; +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.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +@DirtiesContext +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index 1afacab164..d0b3f5fe29 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -147,7 +147,6 @@ 21.0 - 3.5 3.8.0 diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java index 9fae34d99e..e202e45b32 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java @@ -39,7 +39,7 @@ public class PersistenceJPAConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java index 9ba4ebdb6d..eef085f386 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java @@ -16,6 +16,7 @@ import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils; +import org.springframework.jdbc.core.simple.SimpleJdbcCall; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; @@ -27,6 +28,8 @@ public class EmployeeDAO { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private SimpleJdbcInsert simpleJdbcInsert; + + private SimpleJdbcCall simpleJdbcCall; @Autowired public void setDataSource(final DataSource dataSource) { @@ -36,7 +39,9 @@ public class EmployeeDAO { namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("EMPLOYEE"); - + + // Commented as the database is H2, change the database and create procedure READ_EMPLOYEE before calling getEmployeeUsingSimpleJdbcCall + //simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("READ_EMPLOYEE"); } public int getCountOfEmployees() { @@ -110,4 +115,15 @@ public class EmployeeDAO { final int[] updateCounts = namedParameterJdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch); return updateCounts; } + + public Employee getEmployeeUsingSimpleJdbcCall(int id) { + SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id); + Map out = simpleJdbcCall.execute(in); + + Employee emp = new Employee(); + emp.setFirstName((String) out.get("FIRST_NAME")); + emp.setLastName((String) out.get("LAST_NAME")); + + return emp; + } } diff --git a/pom.xml b/pom.xml index 185c0a4015..21a42f89d6 100644 --- a/pom.xml +++ b/pom.xml @@ -1,18 +1,18 @@ + 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 parent-modules 1.0.0-SNAPSHOT - parent-modules + parent-modules pom - - quarkus - + + quarkus + @@ -57,11 +57,11 @@ test - org.junit.jupiter - junit-jupiter-api + org.junit.jupiter + junit-jupiter-api ${junit-jupiter.version} test - + org.hamcrest hamcrest-core @@ -123,22 +123,22 @@ - - 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.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 @@ -312,6 +312,10 @@ 3 true + + SpringContextTest + **/*UnitTest + **/*IntegrationTest.java **/*IntTest.java @@ -328,62 +332,62 @@ parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - akka-streams - algorithms-genetic - algorithms-miscellaneous-1 - algorithms-miscellaneous-2 - algorithms-miscellaneous-3 - algorithms-sorting - animal-sniffer-mvn-plugin - annotations - antlr - apache-avro - apache-bval - apache-curator - apache-cxf - apache-fop - apache-geode - apache-meecrowave - apache-opennlp - apache-poi - apache-pulsar - apache-shiro - apache-solrj - apache-spark - apache-thrift - apache-tika - apache-velocity - apache-zookeeper - asciidoctor - asm - atomix - autovalue - aws - aws-lambda - axon - azure + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + akka-streams + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-miscellaneous-3 + algorithms-sorting + animal-sniffer-mvn-plugin + annotations + antlr + apache-avro + apache-bval + apache-curator + apache-cxf + apache-fop + apache-geode + apache-meecrowave + apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix + autovalue + aws + aws-lambda + axon + azure - blade + blade - bootique + bootique - cas - cdi - checker-plugin - core-groovy - core-groovy-2 - core-groovy-collections - - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 + cas + cdi + checker-plugin + core-groovy + core-groovy-2 + core-groovy-collections + + + + core-java-modules/core-java-8 + core-java-modules/core-java-8-2 core-java-modules/core-java-lambdas @@ -461,10 +465,11 @@ java-lite java-numbers + java-numbers-2 java-rmi java-spi java-streams - java-streams-2 + java-strings java-strings-2 java-vavr-stream @@ -475,83 +480,83 @@ jaxb - jee-7-security - jersey - JGit - jgroups - jhipster - jhipster-5 - jib - jjwt - jmeter - jmh - jni - jooby - jsf - json - json-path - jsoup - jta + jee-7-security + jersey + JGit + jgroups + jhipster-5 + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta - - kotlin-libraries - kotlin-libraries-2 + + kotlin-libraries + kotlin-libraries-2 - - libraries - libraries-2 - libraries-data - libraries-apache-commons - libraries-primitive - libraries-security - libraries-server - linkrest - logging-modules - lombok - lucene + + libraries + libraries-2 + libraries-data + libraries-apache-commons + libraries-primitive + libraries-security + libraries-server + libraries-http + libraries-io + linkrest + logging-modules + lombok + lucene - mapstruct - maven - maven-archetype - - maven-polyglot/maven-polyglot-json-extension - - mesos-marathon - metrics - - microprofile - msf4j - - mustache - mybatis + mapstruct + maven + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + + mesos-marathon + metrics + + microprofile + msf4j + + mustache + mybatis - optaplanner - orika - osgi + optaplanner + orika + osgi - patterns - pdf - performance-tests - - protobuffer + patterns + pdf + performance-tests + + protobuffer - persistence-modules - quarkus + persistence-modules + quarkus - rabbitmq - - ratpack - reactor-core - rest-with-spark-java - resteasy - restx - - rule-engines + rabbitmq + + ratpack + reactor-core + resteasy + restx + + rule-engines rsocket - rxjava - rxjava-2 - software-security/sql-injection-samples + rxjava + rxjava-2 + software-security/sql-injection-samples tensorflow-java spring-boot-flowable @@ -561,236 +566,239 @@ - - default-second - - + + 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 - - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + SpringContextTest + **/*UnitTest + + + **/*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 + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - saas - spark-java + saas + spark-java - spring-4 + spring-4 - spring-5 - spring-5-webflux - spring-5-data-reactive - spring-5-mvc - spring-5-reactive - spring-5-reactive-client - spring-5-reactive-oauth - spring-5-reactive-security - spring-5-security - spring-5-security-oauth - spring-5-security-cognito + spring-5 + spring-5-webflux + spring-5-data-reactive + spring-5-mvc + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth + spring-5-security-cognito - spring-activiti - spring-akka - spring-all - spring-amqp - spring-amqp-simple - spring-aop - spring-apache-camel - spring-batch - spring-bom + spring-activiti + spring-akka + spring-all + spring-amqp + spring-amqp-simple + spring-aop + spring-apache-camel + spring-batch + spring-bom - spring-boot - spring-boot-admin - spring-boot-angular - spring-boot-angular-ecommerce - spring-boot-autoconfiguration - spring-boot-bootstrap - spring-boot-camel - - spring-boot-client + spring-boot + spring-boot-admin + spring-boot-angular + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client - spring-boot-crud - spring-boot-ctx-fluent - spring-boot-custom-starter - spring-boot-disable-console-logging - - spring-boot-jasypt - spring-boot-keycloak - spring-boot-logging-log4j2 - spring-boot-mvc - spring-boot-mvc-birt - spring-boot-ops - spring-boot-ops-2 - spring-boot-rest - spring-boot-data - spring-boot-property-exp - spring-boot-security - spring-boot-testing - spring-boot-vue - spring-boot-libraries + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + spring-boot-disable-console-logging + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-kotlin + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-mvc-birt + spring-boot-ops + spring-boot-ops-2 + spring-boot-rest + spring-boot-data + spring-boot-parent + spring-boot-property-exp + spring-boot-security + spring-boot-testing + spring-boot-vue + spring-boot-libraries - spring-cloud - spring-cloud-bus - - spring-cloud-data-flow + spring-cloud + spring-cloud-bus + + spring-cloud-data-flow - spring-core - spring-cucumber + spring-core + spring-core-2 + spring-cucumber - spring-data-rest - spring-data-rest-querydsl - spring-dispatcher-servlet - spring-drools + spring-data-rest + spring-data-rest-querydsl + spring-dispatcher-servlet + spring-drools - spring-ehcache - spring-ejb - spring-exceptions + spring-ehcache + spring-ejb + spring-exceptions - spring-freemarker + spring-freemarker - spring-groovy + spring-groovy - spring-integration + spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jinq - spring-jms - spring-jooq + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-jooq - spring-kafka - spring-katharsis + spring-kafka + spring-katharsis - spring-ldap + spring-ldap - spring-mobile - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-kotlin - spring-mvc-simple - spring-mvc-simple-2 - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml + spring-mobile + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple + spring-mvc-simple-2 + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml - spring-protobuf - + spring-protobuf + - spring-quartz + spring-quartz - spring-reactive-kotlin - spring-reactor - spring-remoting - spring-rest - spring-rest-angular - spring-rest-full - spring-rest-hal-browser - spring-rest-query-language - spring-rest-shell - spring-rest-simple - spring-resttemplate - spring-roo - spring-security-acl - spring-security-angular/server - spring-security-cache-control + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-resttemplate + spring-roo + spring-security-acl + spring-security-angular/server + spring-security-cache-control - spring-security-client + spring-security-client - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth spring-security-mvc-jsonview - 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 - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-sso - spring-security-stormpath - spring-security-thymeleaf - spring-security-x509 - spring-session - spring-sleuth - spring-soap - spring-social-login - spring-spel - spring-state-machine - spring-static-resources - spring-swagger-codegen + 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 + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + spring-session + spring-sleuth + spring-soap + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spring-thymeleaf + spring-thymeleaf - spring-userservice + spring-vault + spring-vertx - spring-vault - spring-vertx + spring-webflux-amqp - spring-webflux-amqp + spring-zuul - spring-zuul + static-analysis + stripe + structurizr + struts-2 - static-analysis - stripe - structurizr - struts-2 + testing-modules - testing-modules + twilio + Twitter4J - twilio - Twitter4J + undertow - undertow + vertx + vertx-and-rxjava + video-tutorials + vraptor - vavr - vertx - vertx-and-rxjava - video-tutorials - vraptor + wicket - wicket - - xml - xmlunit-2 - xstream + xml + xstream tensorflow-java spring-boot-flowable spring-security-kerberos - + - + spring-context @@ -835,6 +843,7 @@ spring-boot-camel spring-boot-client spring-boot-custom-starter + spring-boot-di greeter-spring-boot-autoconfigure greeter-spring-boot-sample-app persistence-modules/spring-boot-h2/spring-boot-h2-database @@ -922,10 +931,10 @@ spring-state-machine spring-swagger-codegen/spring-swagger-codegen-app spring-thymeleaf - spring-userservice spring-vault spring-vertx spring-zuul/spring-zuul-foos-resource + persistence-modules/hibernate-mapping persistence-modules/spring-data-dynamodb persistence-modules/spring-data-eclipselink persistence-modules/spring-data-solr @@ -937,568 +946,572 @@ - - default-heavy - - + + default-heavy + + - - 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 - - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + SpringContextTest + **/*UnitTest + + + **/*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 + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - core-java-modules/core-java-concurrency-advanced - core-kotlin - core-kotlin-2 - core-kotlin-io + core-java-modules/core-java-concurrency-advanced + core-kotlin + core-kotlin-2 + core-kotlin-io - jenkins/hello-world - jws + jenkins/hello-world + jhipster + jws - libraries + libraries + persistence-modules/hibernate5 + persistence-modules/hibernate-mapping + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql - persistence-modules/hibernate5 - persistence-modules/hibernate-mapping - persistence-modules/java-jpa - persistence-modules/java-mongodb - persistence-modules/jnosql + vaadin + vavr + + - vaadin - - + + integration-lite-first - - integration-lite-first + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + akka-streams + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-miscellaneous-3 + algorithms-sorting + animal-sniffer-mvn-plugin + annotations + antlr + apache-avro + apache-bval + apache-curator + apache-cxf + apache-fop + apache-geode + apache-meecrowave + apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix + autovalue + aws + aws-lambda + axon + azure - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - akka-streams - algorithms-genetic - algorithms-miscellaneous-1 - algorithms-miscellaneous-2 - algorithms-miscellaneous-3 - algorithms-sorting - animal-sniffer-mvn-plugin - annotations - antlr - apache-avro - apache-bval - apache-curator - apache-cxf - apache-fop - apache-geode - apache-meecrowave - apache-opennlp - apache-poi - apache-pulsar - apache-shiro - apache-solrj - apache-spark - apache-thrift - apache-tika - apache-velocity - apache-zookeeper - asciidoctor - asm - atomix - autovalue - aws - aws-lambda - axon - azure + bootique - bootique + cas + cdi + checker-plugin + core-groovy + core-groovy-2 + core-groovy-collections + + + core-java-modules/core-java-8 + core-java-modules/core-java-8-2 + + + core-java-modules/core-java-arrays + core-java-modules/core-java-collections + core-java-modules/core-java-collections-list + core-java-modules/core-java-collections-list-2 + core-java-modules/core-java-collections-array-list + core-java-modules/core-java-collections-set + core-java-modules/core-java-concurrency-basic + core-java-modules/core-java-concurrency-collections + core-java-modules/core-java-io + core-java-modules/core-java-nio + core-java-modules/core-java-security + core-java-modules/core-java-lang-syntax + core-java-modules/core-java-lang + core-java-modules/core-java-lang-oop + core-java-modules/core-java-lang-oop-2 + core-java-modules + core-java-modules/core-java-networking + core-java-modules/core-java-perf + core-java-modules/core-java-sun + core-scala + couchbase + custom-pmd - cas - cdi - checker-plugin - core-groovy - core-groovy-2 - core-groovy-collections - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - - - core-java-modules/core-java-arrays - core-java-modules/core-java-collections - core-java-modules/core-java-collections-list - core-java-modules/core-java-collections-list-2 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-set - core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-collections - core-java-modules/core-java-io - core-java-modules/core-java-nio - core-java-modules/core-java-security - core-java-modules/core-java-lang-syntax - core-java-modules/core-java-lang - core-java-modules/core-java-lang-oop - core-java-modules/core-java-lang-oop-2 - core-java-modules - core-java-modules/core-java-networking - core-java-modules/core-java-perf - core-java-modules/core-java-sun - core-scala - couchbase - custom-pmd + dagger + data-structures + ddd + deeplearning4j + disruptor + dozer + drools + dubbo - dagger - data-structures - ddd - deeplearning4j - disruptor - dozer - drools - dubbo + ethereum - ethereum + feign + flyway-cdi-extension - feign - flyway-cdi-extension + geotools + google-cloud + google-web-toolkit + + + graphql/graphql-java + grpc + gson + guava + guava-collections + guava-modules + + guice - geotools - google-cloud - google-web-toolkit - - - graphql/graphql-java - grpc - gson - guava - guava-collections - guava-modules - - guice + hazelcast + helidon + httpclient + httpclient-simple + hystrix - hazelcast - helidon - httpclient - httpclient-simple - hystrix + image-processing + immutables - image-processing - immutables - - jackson - jackson-2 - jackson-simple - java-collections-conversions - java-collections-maps - java-collections-maps-2 - - java-ee-8-security-api - java-lite - java-numbers - java-rmi - java-spi - java-streams - java-streams-2 - java-strings - java-strings-2 - java-vavr-stream - java-websocket - javafx - javax-servlets - javaxval - jaxb - + java-ee-8-security-api + java-lite + java-numbers + java-numbers-2 + java-rmi + java-spi + java-streams + + java-strings + java-strings-2 + java-vavr-stream + java-websocket + javafx + javax-servlets + javaxval + jaxb + - jee-7-security - jersey - JGit - jgroups - jhipster - jhipster-5 - jib - jjwt - jmeter - jmh - jni - jooby - jsf - json - json-path - jsoup - jta + jee-7-security + jersey + JGit + jgroups + jhipster-5 + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta - - kotlin-libraries + + kotlin-libraries - - libraries - libraries-data - libraries-apache-commons - libraries-security - libraries-server - linkrest - logging-modules - lombok - lucene + + libraries + libraries-data + libraries-apache-commons + libraries-security + libraries-server + libraries-http + linkrest + logging-modules + lombok + lucene - mapstruct - maven - - maven-archetype - - maven-polyglot/maven-polyglot-json-extension - - mesos-marathon - metrics - - microprofile - msf4j - - mustache - mybatis + mapstruct + maven + + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + + mesos-marathon + metrics + + microprofile + msf4j + + mustache + mybatis - optaplanner - orika - osgi + optaplanner + orika + osgi - patterns - pdf - performance-tests - - protobuffer + patterns + pdf + performance-tests + + protobuffer - persistence-modules + persistence-modules - rabbitmq - - ratpack - reactor-core - rest-with-spark-java - resteasy - restx - - rule-engines - rsocket - rxjava - rxjava-2 + rabbitmq + + ratpack + reactor-core + resteasy + restx + + rule-engines + rsocket + rxjava + rxjava-2 - + - + - - integration-lite-second + + integration-lite-second - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - saas - spark-java + saas + spark-java - spring-4 + spring-4 - spring-5 - spring-5-data-reactive - spring-5-mvc - spring-5-reactive - spring-5-reactive-client - spring-5-reactive-oauth - spring-5-reactive-security - spring-5-security - spring-5-security-oauth - spring-5-security-cognito - spring-activiti - spring-akka - spring-all - spring-amqp - spring-amqp-simple - spring-aop - spring-apache-camel - spring-batch - spring-bom + spring-5 + spring-5-data-reactive + spring-5-mvc + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth + spring-5-security-cognito + spring-activiti + spring-akka + spring-all + spring-amqp + spring-amqp-simple + spring-aop + spring-apache-camel + spring-batch + spring-bom - spring-boot - spring-boot-admin - spring-boot-angular - spring-boot-angular-ecommerce - spring-boot-autoconfiguration - spring-boot-bootstrap - spring-boot-camel - - spring-boot-client - spring-boot-crud - spring-boot-ctx-fluent - spring-boot-custom-starter - spring-boot-disable-console-logging - - spring-boot-jasypt - spring-boot-keycloak - spring-boot-logging-log4j2 - spring-boot-mvc - spring-boot-mvc-birt - spring-boot-ops - spring-boot-ops-2 - spring-boot-rest - spring-boot-data - spring-boot-property-exp - spring-boot-security - spring-boot-vue + spring-boot + spring-boot-admin + spring-boot-angular + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + spring-boot-disable-console-logging + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-mvc-birt + spring-boot-ops + spring-boot-ops-2 + spring-boot-rest + spring-boot-data + spring-boot-parent + spring-boot-property-exp + spring-boot-security + spring-boot-vue - spring-cloud - spring-cloud-bus - - spring-cloud-data-flow + spring-cloud + spring-cloud-bus + + spring-cloud-data-flow - spring-core - spring-cucumber + spring-core + spring-core-2 + spring-cucumber - spring-data-rest - spring-data-rest-querydsl - spring-dispatcher-servlet - spring-drools + spring-data-rest + spring-data-rest-querydsl + spring-dispatcher-servlet + spring-drools spring-ehcache - spring-ejb - spring-exceptions + spring-ejb + spring-exceptions - spring-freemarker + spring-freemarker - spring-groovy + spring-groovy - spring-integration + spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jinq - spring-jms - spring-jooq + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-jooq - spring-kafka - spring-katharsis + spring-kafka + spring-katharsis - spring-ldap + spring-ldap - spring-mobile - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-kotlin - spring-mvc-simple - spring-mvc-simple-2 - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml + spring-mobile + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple + spring-mvc-simple-2 + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml - spring-protobuf - + spring-protobuf + - spring-quartz + spring-quartz - spring-reactive-kotlin - spring-reactor - spring-remoting - spring-rest - spring-rest-angular - spring-rest-full - spring-rest-hal-browser - spring-rest-query-language - spring-rest-shell - spring-rest-simple - spring-resttemplate - spring-roo + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-resttemplate + spring-roo - spring-security-acl - spring-security-angular/server - spring-security-cache-control + spring-security-acl + spring-security-angular/server + spring-security-cache-control - spring-security-client + spring-security-client - 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 - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-sso - spring-security-stormpath - spring-security-thymeleaf - spring-security-x509 - spring-session - spring-sleuth - spring-soap - spring-social-login - spring-spel - spring-state-machine - spring-static-resources - spring-swagger-codegen + 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 + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + spring-session + spring-sleuth + spring-soap + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spring-thymeleaf + spring-thymeleaf - spring-userservice + spring-vault + spring-vertx - spring-vault - spring-vertx + spring-webflux-amqp - spring-webflux-amqp + spring-zuul - spring-zuul + static-analysis + stripe + structurizr + struts-2 - static-analysis - stripe - structurizr - struts-2 + testing-modules - testing-modules + twilio + Twitter4J - twilio - Twitter4J + undertow - undertow + vertx + vertx-and-rxjava + video-tutorials + vraptor - vavr - vertx - vertx-and-rxjava - video-tutorials - vraptor + wicket - wicket + xml + xstream + - xml - xmlunit-2 - xstream + - + + integration-heavy - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - integration-heavy + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + core-java-modules/core-java + core-java-modules/core-java-concurrency-advanced + core-kotlin + core-kotlin-2 - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + jenkins/hello-world + jhipster + jws - core-java-modules/core-java - core-java-modules/core-java-concurrency-advanced - core-kotlin - core-kotlin-2 + libraries - jenkins/hello-world - jws + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql - libraries + vaadin + vavr + - persistence-modules/hibernate5 - persistence-modules/java-jpa - persistence-modules/java-mongodb - persistence-modules/jnosql - - vaadin - - - + @@ -1532,7 +1545,7 @@ 1.1.7 - + 2.21.0 3.7.0 1.6.0 @@ -1546,6 +1559,8 @@ 1.6.0 2.21.0 2.5 + 2.6 + 3.5 1.4 3.0.0 3.1.0 diff --git a/quarkus/README.md b/quarkus/README.md index 01009eab3e..8116d16cb7 100644 --- a/quarkus/README.md +++ b/quarkus/README.md @@ -1,3 +1,3 @@ ## Relevant articles: -- [Guide to QuarkusIO](hhttps://www.baeldung.com/quarkus-io) +- [Guide to QuarkusIO](https://www.baeldung.com/quarkus-io) diff --git a/ratpack/README.md b/ratpack/README.md index 14bc3f6c74..78e2f8ccfc 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -6,3 +6,4 @@ - [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix) - [Ratpack HTTP Client](https://www.baeldung.com/ratpack-http-client) - [Ratpack with RxJava](https://www.baeldung.com/ratpack-rxjava) +- [Ratpack with Groovy](https://www.baeldung.com/ratpack-groovy) diff --git a/ratpack/build.gradle b/ratpack/build.gradle index 25af3ddb51..c997b4e697 100644 --- a/ratpack/build.gradle +++ b/ratpack/build.gradle @@ -14,6 +14,8 @@ if (!JavaVersion.current().java8Compatible) { apply plugin: "io.ratpack.ratpack-java" apply plugin: 'java' +apply plugin: 'groovy' +apply plugin: 'io.ratpack.ratpack-groovy' repositories { jcenter() diff --git a/ratpack/pom.xml b/ratpack/pom.xml index 7c145eff91..0df313c05e 100644 --- a/ratpack/pom.xml +++ b/ratpack/pom.xml @@ -26,11 +26,21 @@ ratpack-core ${ratpack.version} + + org.codehaus.groovy + groovy-sql + ${groovy.sql.version} + io.ratpack ratpack-hikari ${ratpack.version} + + io.ratpack + ratpack-groovy-test + ${ratpack.test.latest.version} + io.ratpack ratpack-hystrix @@ -91,6 +101,7 @@ 4.5.3 4.4.6 1.5.12 + 2.4.15 + 1.6.1 - diff --git a/ratpack/src/main/groovy/com/baeldung/Ratpack.groovy b/ratpack/src/main/groovy/com/baeldung/Ratpack.groovy new file mode 100644 index 0000000000..4d8814b627 --- /dev/null +++ b/ratpack/src/main/groovy/com/baeldung/Ratpack.groovy @@ -0,0 +1,76 @@ +package com.baeldung; + +@Grab('io.ratpack:ratpack-groovy:1.6.1') +import static ratpack.groovy.Groovy.ratpack + +import com.baeldung.model.User +import com.google.common.reflect.TypeToken +import ratpack.exec.Promise +import ratpack.handling.Context +import ratpack.jackson.Jackson +import groovy.sql.Sql +import java.sql.Connection +import java.sql.PreparedStatement +import java.sql.ResultSet +import ratpack.hikari.HikariModule +import javax.sql.DataSource; + +ratpack { + serverConfig { port(5050) } + bindings { + module(HikariModule) { config -> + config.dataSourceClassName = 'org.h2.jdbcx.JdbcDataSource' + config.addDataSourceProperty('URL', "jdbc:h2:mem:devDB;INIT=RUNSCRIPT FROM 'classpath:/User.sql'") + } + } + + handlers { + + get { render 'Hello World from Ratpack with Groovy!!' } + + get("greet/:name") { Context ctx -> + render "Hello " + ctx.getPathTokens().get("name") + "!!!" + } + + get("data") { + render Jackson.json([title: "Mr", name: "Norman", country: "USA"]) + } + + post("user") { + Promise user = parse(Jackson.fromJson(User)) + user.then { u -> render u.name } + } + + get('fetchUserName/:id') { Context ctx -> + Connection connection = ctx.get(DataSource.class).getConnection() + PreparedStatement queryStatement = connection.prepareStatement("SELECT NAME FROM USER WHERE ID=?") + queryStatement.setInt(1, Integer.parseInt(ctx.getPathTokens().get("id"))) + ResultSet resultSet = queryStatement.executeQuery() + resultSet.next() + render resultSet.getString(1) + } + + get('fetchUsers') { + def db = [url:'jdbc:h2:mem:devDB'] + def sql = Sql.newInstance(db.url, db.user, db.password) + def users = sql.rows("SELECT * FROM USER"); + render(Jackson.json(users)) + } + + post('addUser') { + parse(Jackson.fromJson(User)) + .then { u -> + def db = [url:'jdbc:h2:mem:devDB'] + Sql sql = Sql.newInstance(db.url, db.user, db.password) + sql.executeInsert("INSERT INTO USER VALUES (?,?,?,?)", [ + u.id, + u.title, + u.name, + u.country + ]) + render "User $u.name inserted" + } + } + } +} + diff --git a/ratpack/src/main/groovy/com/baeldung/RatpackGroovyApp.groovy b/ratpack/src/main/groovy/com/baeldung/RatpackGroovyApp.groovy new file mode 100644 index 0000000000..95ada25e60 --- /dev/null +++ b/ratpack/src/main/groovy/com/baeldung/RatpackGroovyApp.groovy @@ -0,0 +1,12 @@ +package com.baeldung; + +public class RatpackGroovyApp { + + public static void main(String[] args) { + File file = new File("src/main/groovy/com/baeldung/Ratpack.groovy"); + def shell = new GroovyShell() + shell.evaluate(file) + } + +} + diff --git a/ratpack/src/main/groovy/com/baeldung/model/User.groovy b/ratpack/src/main/groovy/com/baeldung/model/User.groovy new file mode 100644 index 0000000000..0fe4c6c367 --- /dev/null +++ b/ratpack/src/main/groovy/com/baeldung/model/User.groovy @@ -0,0 +1,9 @@ +package com.baeldung.model + +class User { + + long id + String title + String name + String country +} diff --git a/ratpack/src/main/resources/User.sql b/ratpack/src/main/resources/User.sql new file mode 100644 index 0000000000..a3e2242283 --- /dev/null +++ b/ratpack/src/main/resources/User.sql @@ -0,0 +1,10 @@ +DROP TABLE IF EXISTS USER; +CREATE TABLE USER ( + ID BIGINT AUTO_INCREMENT PRIMARY KEY, + TITLE VARCHAR(255), + NAME VARCHAR(255), + COUNTRY VARCHAR(255) +); + +INSERT INTO USER VALUES(1,'Mr','Norman Potter', 'USA'); +INSERT INTO USER VALUES(2,'Miss','Ketty Smith', 'FRANCE'); \ No newline at end of file diff --git a/ratpack/src/test/groovy/com/baeldung/RatpackGroovySpec.groovy b/ratpack/src/test/groovy/com/baeldung/RatpackGroovySpec.groovy new file mode 100644 index 0000000000..726d703a06 --- /dev/null +++ b/ratpack/src/test/groovy/com/baeldung/RatpackGroovySpec.groovy @@ -0,0 +1,46 @@ +package com.baeldung; + +import ratpack.groovy.Groovy +import ratpack.groovy.test.GroovyRatpackMainApplicationUnderTest; +import ratpack.test.http.TestHttpClient; +import ratpack.test.ServerBackedApplicationUnderTest; +import org.junit.Test; +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +import ratpack.test.MainClassApplicationUnderTest + +class RatpackGroovySpec { + + ServerBackedApplicationUnderTest ratpackGroovyApp = new MainClassApplicationUnderTest(RatpackGroovyApp.class) + @Delegate TestHttpClient client = TestHttpClient.testHttpClient(ratpackGroovyApp) + + @Test + void "test if app is started"() { + when: + get("") + + then: + assert response.statusCode == 200 + assert response.body.text == "Hello World from Ratpack with Groovy!!" + } + + @Test + void "test greet with name"() { + when: + get("greet/Lewis") + + then: + assert response.statusCode == 200 + assert response.body.text == "Hello Lewis!!!" + } + + @Test + void "test fetchUsers"() { + when: + get("fetchUsers") + + then: + assert response.statusCode == 200 + assert response.body.text == '[{"ID":1,"TITLE":"Mr","NAME":"Norman Potter","COUNTRY":"USA"},{"ID":2,"TITLE":"Miss","NAME":"Ketty Smith","COUNTRY":"FRANCE"}]' + } +} diff --git a/rest-with-spark-java/README.md b/rest-with-spark-java/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/rest-with-spark-java/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/rest-with-spark-java/pom.xml b/rest-with-spark-java/pom.xml deleted file mode 100644 index fc78ac6b86..0000000000 --- a/rest-with-spark-java/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - com.baeldung - rest-with-spark-java - 1.0-SNAPSHOT - rest-with-spark-java - http://maven.apache.org - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - com.sparkjava - spark-core - ${spark-core.version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - - 2.5.4 - - - diff --git a/rest-with-spark-java/src/main/java/com/baeldung/Router.java b/rest-with-spark-java/src/main/java/com/baeldung/Router.java deleted file mode 100644 index 3482184e1e..0000000000 --- a/rest-with-spark-java/src/main/java/com/baeldung/Router.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung; - -import static spark.Spark.after; -import static spark.Spark.before; -import static spark.Spark.delete; -import static spark.Spark.get; -import static spark.Spark.post; -import static spark.Spark.port; - -import com.baeldung.domain.Book; -import com.baeldung.service.LibraryService; - -public class Router { - - public static void main( String[] args ){ - - port(8080); - - before((request, response) -> { - - //do some filtering stuff - - }); - - after((request, response) -> { - response.type("application/json"); - }); - - get("ListOfBooks", (request, response) -> { - return LibraryService.view(); - }); - - get("SearchBook/:title", (request, response) -> { - return LibraryService.view(request.params("title")); - }); - - post("AddBook/:title/:author/:publisher", (request, response) -> { - Book book = new Book(); - book.setTitle(request.params("title")); - book.setAuthor(request.params("author")); - book.setPublisher(request.params("publisher")); - return LibraryService.add(book); - }); - - delete("DeleteBook/:title", (request, response) -> { - return LibraryService.delete(request.params("title")); - }); - - } -} diff --git a/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java b/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java deleted file mode 100644 index 977d5d9f89..0000000000 --- a/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.domain; - -public class Book { - - private String title; - private String author; - private String publisher; - - public Book() {} - - public Book(String title, String author, String publisher) { - super(); - this.title = title; - this.author = author; - this.publisher = publisher; - } - - 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; - } - public String getPublisher() { - return publisher; - } - public void setPublisher(String publisher) { - this.publisher = publisher; - } - - protected boolean canEqual(Object other) { - return other instanceof Book; - } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof Book)) return false; - Book other = (Book) o; - if (!other.canEqual((Object)this)) return false; - if (this.getTitle() == null ? other.getTitle() != null : !this.getTitle().equals(other.getTitle())) return false; - return true; - } - -} diff --git a/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java b/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java deleted file mode 100644 index e4ca4c270c..0000000000 --- a/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.service; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.baeldung.domain.Book; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; - -public class LibraryService { - - private static ObjectWriter mapper = new ObjectMapper().writer().withDefaultPrettyPrinter(); - private static Map library = new HashMap(); - - public static String view() throws JsonProcessingException { - List books = new ArrayList(); - library.forEach((key, value) -> { - books.add(value); - }); - return mapper.writeValueAsString(books); - } - - public static String view(String title) throws JsonProcessingException { - return mapper.writeValueAsString(library.get(title)); - } - - public static String add(Book book) throws JsonProcessingException { - library.put(book.getTitle(), book); - return mapper.writeValueAsString(book); - } - - public static String delete(String title) throws JsonProcessingException { - Book deletedBook = library.remove(title); - return mapper.writeValueAsString(deletedBook); - } - -} diff --git a/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java b/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java deleted file mode 100644 index 9e24879767..0000000000 --- a/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.baeldung; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.domain.Book; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class AppLiveTest extends TestCase { - - ObjectMapper mapper = new ObjectMapper(); - - public AppLiveTest( String testName ) { - super( testName ); - } - - public static Test suite() { - return new TestSuite( AppLiveTest.class ); - } - - public void testApp() throws IOException, ClassNotFoundException { - - URL url; - HttpURLConnection conn; - BufferedReader br; - String output; - StringBuffer resp; - Book book; - Book temp; - - url = new URL("http://localhost:8080/AddBook/Odessy/YannMartel/GreenLeaves"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - conn.getContent(); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Odessy","YannMartel","GreenLeaves"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/AddBook/Twilight/StephenieMeyer/LittleBrown"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Twilight","StephenieMeyer","LittleBrown"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/ListOfBooks"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - List books = new ArrayList(); - - books.add(new Book("Odessy","YannMartel","GreenLeaves")); - books.add(new Book("Twilight","StephenieMeyer","LittleBrown")); - - List listOfBooks = mapper.readValue(resp.toString(), new TypeReference>(){}); - - assertEquals(books, listOfBooks); - - url = new URL("http://localhost:8080/SearchBook/Twilight"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Twilight","StephenieMeyer","LittleBrown"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/DeleteBook/Twilight"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("DELETE"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Twilight","StephenieMeyer","LittleBrown"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/ListOfBooks"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - books = new ArrayList(); - - books.add(new Book("Odessy","YannMartel","GreenLeaves")); - listOfBooks = mapper.readValue(resp.toString(), new TypeReference>(){}); - - assertEquals(books, listOfBooks); - - conn.disconnect(); - - } - -} diff --git a/resteasy/pom.xml b/resteasy/pom.xml index ca4124abca..8aea8077f9 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -143,7 +143,6 @@ 3.0.19.Final - 2.5 1.6.1 diff --git a/software-security/sql-injection-samples/pom.xml b/software-security/sql-injection-samples/pom.xml index b12b479614..5c3256319e 100644 --- a/software-security/sql-injection-samples/pom.xml +++ b/software-security/sql-injection-samples/pom.xml @@ -16,13 +16,10 @@ - - org.springframework.boot spring-boot-starter-jdbc - org.apache.derby derby @@ -43,18 +40,14 @@ lombok provided - org.springframework.boot spring-boot-starter-data-jpa - org.hibernate hibernate-jpamodelgen - - org.springframework.boot spring-boot-devtools diff --git a/spf4j/README.md b/spf4j/README.md new file mode 100644 index 0000000000..a39cd01b5e --- /dev/null +++ b/spf4j/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to SPF4J](https://www.baeldung.com/spf4j) diff --git a/spf4j/pom.xml b/spf4j/pom.xml new file mode 100644 index 0000000000..43a8028dc4 --- /dev/null +++ b/spf4j/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + com.baeldung.spf4j + spf4j + spf4j + pom + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + spf4j-core-app + spf4j-aspects-app + + + diff --git a/spf4j/spf4j-aspects-app/pom.xml b/spf4j/spf4j-aspects-app/pom.xml new file mode 100644 index 0000000000..1c707f4d87 --- /dev/null +++ b/spf4j/spf4j-aspects-app/pom.xml @@ -0,0 +1,87 @@ + + 4.0.0 + spf4j-aspects-app + 0.0.1-SNAPSHOT + jar + spf4j-aspects-app + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + ../../ + + + + + org.spf4j + spf4j-aspects + ${spf4j.version} + + + org.spf4j + spf4j-ui + ${spf4j.version} + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + + spf4j-aspects-app + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-dependency-plugin + 3.1.1 + + + copy-dependencies + package + + copy-dependencies + + + + ${project.build.directory}/dependency-jars/ + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.baeldung.spf4j.aspects.App + true + dependency-jars/ + + + + + + + + + UTF-8 + 8.6.10 + 1.7.21 + + diff --git a/spf4j/spf4j-aspects-app/src/main/java/com/baeldung/spf4j/aspects/App.java b/spf4j/spf4j-aspects-app/src/main/java/com/baeldung/spf4j/aspects/App.java new file mode 100644 index 0000000000..6d74292c75 --- /dev/null +++ b/spf4j/spf4j-aspects-app/src/main/java/com/baeldung/spf4j/aspects/App.java @@ -0,0 +1,28 @@ +package com.baeldung.spf4j.aspects; + +import java.util.Random; + +import org.spf4j.annotations.PerformanceMonitor; + +public class App { + + public static void main(String[] args) throws InterruptedException { + Spf4jConfig.initialize(); + Random random = new Random(); + for (int i = 0; i < 100; i++) { + long numberToCheck = random.nextInt(999_999_999 - 100_000_000 + 1) + 100_000_000; + isPrimeNumber(numberToCheck); + } + System.exit(0); + } + + @PerformanceMonitor(warnThresholdMillis = 1, errorThresholdMillis = 100, recorderSource = Spf4jConfig.RecorderSourceForIsPrimeNumber.class) + public static boolean isPrimeNumber(long number) { + for (long i = 2; i <= number / 2; i++) { + if (number % i == 0) + return false; + } + return true; + } + +} diff --git a/spf4j/spf4j-aspects-app/src/main/java/com/baeldung/spf4j/aspects/Spf4jConfig.java b/spf4j/spf4j-aspects-app/src/main/java/com/baeldung/spf4j/aspects/Spf4jConfig.java new file mode 100644 index 0000000000..a12213f0cd --- /dev/null +++ b/spf4j/spf4j-aspects-app/src/main/java/com/baeldung/spf4j/aspects/Spf4jConfig.java @@ -0,0 +1,37 @@ +package com.baeldung.spf4j.aspects; + +import java.io.File; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.spf4j.annotations.RecorderSourceInstance; +import org.spf4j.perf.MeasurementRecorderSource; +import org.spf4j.perf.impl.RecorderFactory; + +public class Spf4jConfig { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + public static void initialize() { + String tsDbFile = System.getProperty("user.dir") + File.separator + "spf4j-performance-monitoring.tsdb2"; + String tsTextFile = System.getProperty("user.dir") + File.separator + "spf4j-performance-monitoring.txt"; + + LOGGER.info("\nTime Series DB (TSDB) : {}\nTime Series text file : {}", tsDbFile, tsTextFile); + System.setProperty("spf4j.perf.ms.config", "TSDB@" + tsDbFile + "," + "TSDB_TXT@" + tsTextFile); + } + + public static final class RecorderSourceForIsPrimeNumber extends RecorderSourceInstance { + public static final MeasurementRecorderSource INSTANCE; + + static { + Object forWhat = App.class + " isPrimeNumber"; + String unitOfMeasurement = "ms"; + int sampleTimeMillis = 1_000; + int factor = 10; + int lowerMagnitude = 0; + int higherMagnitude = 4; + int quantasPerMagnitude = 10; + INSTANCE = RecorderFactory.createScalableQuantizedRecorderSource(forWhat, unitOfMeasurement, + sampleTimeMillis, factor, lowerMagnitude, higherMagnitude, quantasPerMagnitude); + } + } +} diff --git a/spf4j/spf4j-aspects-app/src/main/resources/META-INF/aop.xml b/spf4j/spf4j-aspects-app/src/main/resources/META-INF/aop.xml new file mode 100644 index 0000000000..1643f5fba9 --- /dev/null +++ b/spf4j/spf4j-aspects-app/src/main/resources/META-INF/aop.xml @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/spf4j/spf4j-aspects-app/src/main/resources/logback.xml b/spf4j/spf4j-aspects-app/src/main/resources/logback.xml new file mode 100644 index 0000000000..4677fac9bf --- /dev/null +++ b/spf4j/spf4j-aspects-app/src/main/resources/logback.xml @@ -0,0 +1,11 @@ + + + + [%level] %msg%n + + + + + + \ No newline at end of file diff --git a/spf4j/spf4j-core-app/pom.xml b/spf4j/spf4j-core-app/pom.xml new file mode 100644 index 0000000000..9f490d9f06 --- /dev/null +++ b/spf4j/spf4j-core-app/pom.xml @@ -0,0 +1,87 @@ + + 4.0.0 + spf4j-core-app + 0.0.1-SNAPSHOT + jar + spf4j-core-app + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + ../../ + + + + + org.spf4j + spf4j-core + ${spf4j.version} + + + org.spf4j + spf4j-ui + ${spf4j.version} + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + + spf4j-core-app + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-dependency-plugin + 3.1.1 + + + copy-dependencies + package + + copy-dependencies + + + + ${project.build.directory}/dependency-jars/ + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.baeldung.spf4j.core.App + true + dependency-jars/ + + + + + + + + + UTF-8 + 8.6.10 + 1.7.21 + + diff --git a/spf4j/spf4j-core-app/src/main/java/com/baeldung/spf4j/core/App.java b/spf4j/spf4j-core-app/src/main/java/com/baeldung/spf4j/core/App.java new file mode 100644 index 0000000000..fa107d8e4f --- /dev/null +++ b/spf4j/spf4j-core-app/src/main/java/com/baeldung/spf4j/core/App.java @@ -0,0 +1,34 @@ +package com.baeldung.spf4j.core; + +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.spf4j.perf.MeasurementRecorder; + +public class App { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + public static void main(String[] args) throws InterruptedException { + Spf4jConfig.initialize(); + MeasurementRecorder measurementRecorder = Spf4jConfig.getMeasurementRecorder(App.class + " isPrimeNumber"); + Random random = new Random(); + for (int i = 0; i < 100; i++) { + long numberToCheck = random.nextInt(999_999_999 - 100_000_000 + 1) + 100_000_000; + long startTime = System.currentTimeMillis(); + boolean isPrime = isPrimeNumber(numberToCheck); + measurementRecorder.record(System.currentTimeMillis() - startTime); + LOGGER.info("{}. {} is prime? {}", i + 1, numberToCheck, isPrime); + } + System.exit(0); + } + + private static boolean isPrimeNumber(long number) { + for (long i = 2; i <= number / 2; i++) { + if (number % i == 0) + return false; + } + return true; + } + +} diff --git a/spf4j/spf4j-core-app/src/main/java/com/baeldung/spf4j/core/Spf4jConfig.java b/spf4j/spf4j-core-app/src/main/java/com/baeldung/spf4j/core/Spf4jConfig.java new file mode 100644 index 0000000000..0f806e1576 --- /dev/null +++ b/spf4j/spf4j-core-app/src/main/java/com/baeldung/spf4j/core/Spf4jConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.spf4j.core; + +import java.io.File; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.spf4j.perf.MeasurementRecorder; +import org.spf4j.perf.impl.RecorderFactory; + +public class Spf4jConfig { + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + public static void initialize() { + String tsDbFile = System.getProperty("user.dir") + File.separator + "spf4j-performance-monitoring.tsdb2"; + String tsTextFile = System.getProperty("user.dir") + File.separator + "spf4j-performance-monitoring.txt"; + + LOGGER.info("\nTime Series DB (TSDB) : {}\nTime Series text file : {}", tsDbFile, tsTextFile); + System.setProperty("spf4j.perf.ms.config", "TSDB@" + tsDbFile + "," + "TSDB_TXT@" + tsTextFile); + } + + public static MeasurementRecorder getMeasurementRecorder(Object forWhat) { + String unitOfMeasurement = "ms"; + int sampleTimeMillis = 1_000; + int factor = 10; + int lowerMagnitude = 0; + int higherMagnitude = 4; + int quantasPerMagnitude = 10; + + return RecorderFactory.createScalableQuantizedRecorder(forWhat, unitOfMeasurement, sampleTimeMillis, factor, lowerMagnitude, higherMagnitude, quantasPerMagnitude); + } +} diff --git a/spf4j/spf4j-core-app/src/main/resources/logback.xml b/spf4j/spf4j-core-app/src/main/resources/logback.xml new file mode 100644 index 0000000000..4677fac9bf --- /dev/null +++ b/spf4j/spf4j-core-app/src/main/resources/logback.xml @@ -0,0 +1,11 @@ + + + + [%level] %msg%n + + + + + + \ No newline at end of file diff --git a/spring-4/src/test/java/org/baeldung/SpringContextTest.java b/spring-4/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..cccdaff0cd --- /dev/null +++ b/spring-4/src/test/java/org/baeldung/SpringContextTest.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.flips.ApplicationConfig; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ApplicationConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-data-reactive/README.md b/spring-5-data-reactive/README.md index f8886ac18b..f3205c23bc 100644 --- a/spring-5-data-reactive/README.md +++ b/spring-5-data-reactive/README.md @@ -6,3 +6,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles - [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) - [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) +- [Spring Data MongoDB Tailable Cursors](https://www.baeldung.com/spring-data-mongodb-tailable-cursors) diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index aa73cf11ae..5372803842 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -1,9 +1,9 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-5-data-reactive - spring-5-data-reactive + spring-5-data-reactive jar @@ -49,11 +49,11 @@ ${kotlin.version} test - + io.reactivex.rxjava2 rxjava - + org.springframework spring-test @@ -63,6 +63,49 @@ spring-boot-starter-test test + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + test + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework + spring-tx + ${spring-tx.version} + + + + org.springframework.data + spring-data-r2dbc + ${spring-data-r2dbc.version} + + + io.r2dbc + r2dbc-h2 + ${r2dbc-h2.version} + + + com.h2database + h2 + ${h2.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + @@ -74,7 +117,7 @@ kotlin-maven-plugin ${kotlin-maven-plugin.version} - + compile @@ -118,7 +161,7 @@ - + org.apache.maven.plugins maven-compiler-plugin @@ -126,13 +169,13 @@ ${java.version} - default-compile none - default-testCompile @@ -157,9 +200,30 @@ + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + 1.2.40 1.2.40 + 5.2.0.M2 + 1.0.0.M2 + 0.8.0.M8 + 4.5.2 + 1.4.199 diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/R2dbcApplication.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/R2dbcApplication.java new file mode 100644 index 0000000000..557b6ff42a --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/R2dbcApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.r2dbc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.r2dbc") +public class R2dbcApplication { + + public static void main(String[] args) { + SpringApplication.run(R2dbcApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java new file mode 100644 index 0000000000..17eac7fee2 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java @@ -0,0 +1,21 @@ +package com.baeldung.r2dbc.configuration; + +import io.r2dbc.h2.H2ConnectionConfiguration; +import io.r2dbc.h2.H2ConnectionFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration; +import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories; + +@Configuration +//@EnableR2dbcRepositories(basePackages = "com.baeldung.r2dbc.repository") +public class R2DBCConfiguration extends AbstractR2dbcConfiguration { + @Bean + public H2ConnectionFactory connectionFactory() { + return new H2ConnectionFactory( + H2ConnectionConfiguration.builder() + .url("mem:testdb;DB_CLOSE_DELAY=-1;TRACE_LEVEL_FILE=4") + .username("sa") + .build()); + } +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java new file mode 100644 index 0000000000..1926997e97 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java @@ -0,0 +1,16 @@ +package com.baeldung.r2dbc.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.Id; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Player { + @Id + Integer id; + String name; + Integer age; +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java new file mode 100644 index 0000000000..33b653140e --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.r2dbc.repository; + +import com.baeldung.r2dbc.model.Player; +import org.springframework.data.r2dbc.repository.query.Query; +import org.springframework.data.repository.reactive.ReactiveCrudRepository; +import reactor.core.publisher.Flux; + +public interface PlayerRepository extends ReactiveCrudRepository { + + @Query("select id, name, age from player where name = $1") + Flux findAllByName(String name); + + @Query("select * from player where age = $1") + Flux findByAge(int age); +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/LogsCounterApplication.java b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/LogsCounterApplication.java new file mode 100644 index 0000000000..8b2511a8f3 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/LogsCounterApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.tailablecursor; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class LogsCounterApplication { + public static void main(String[] args) { + SpringApplication.run(LogsCounterApplication.class, args); + } +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/domain/Log.java b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/domain/Log.java new file mode 100644 index 0000000000..717a367751 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/domain/Log.java @@ -0,0 +1,21 @@ +package com.baeldung.tailablecursor.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Data +@Document +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class Log { + @Id + private String id; + private String service; + private LogLevel level; + private String message; +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/domain/LogLevel.java b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/domain/LogLevel.java new file mode 100644 index 0000000000..6826fbffd3 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/domain/LogLevel.java @@ -0,0 +1,5 @@ +package com.baeldung.tailablecursor.domain; + +public enum LogLevel { + ERROR, WARN, INFO +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/repository/LogsRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/repository/LogsRepository.java new file mode 100644 index 0000000000..dce11c548c --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/repository/LogsRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.tailablecursor.repository; + +import com.baeldung.tailablecursor.domain.Log; +import com.baeldung.tailablecursor.domain.LogLevel; +import org.springframework.data.mongodb.repository.Tailable; +import org.springframework.data.repository.reactive.ReactiveCrudRepository; +import reactor.core.publisher.Flux; + +public interface LogsRepository extends ReactiveCrudRepository { + @Tailable + Flux findByLevel(LogLevel level); +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/ErrorLogsCounter.java b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/ErrorLogsCounter.java new file mode 100644 index 0000000000..c243e64f97 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/ErrorLogsCounter.java @@ -0,0 +1,62 @@ +package com.baeldung.tailablecursor.service; + +import com.baeldung.tailablecursor.domain.Log; +import com.baeldung.tailablecursor.domain.LogLevel; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.messaging.DefaultMessageListenerContainer; +import org.springframework.data.mongodb.core.messaging.MessageListener; +import org.springframework.data.mongodb.core.messaging.MessageListenerContainer; +import org.springframework.data.mongodb.core.messaging.TailableCursorRequest; + +import javax.annotation.PreDestroy; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.springframework.data.mongodb.core.query.Criteria.where; +import static org.springframework.data.mongodb.core.query.Query.query; + +@Slf4j +public class ErrorLogsCounter implements LogsCounter { + + private static final String LEVEL_FIELD_NAME = "level"; + + private final String collectionName; + private final MessageListenerContainer container; + + private final AtomicInteger counter = new AtomicInteger(); + + public ErrorLogsCounter(MongoTemplate mongoTemplate, + String collectionName) { + this.collectionName = collectionName; + this.container = new DefaultMessageListenerContainer(mongoTemplate); + + container.start(); + TailableCursorRequest request = getTailableCursorRequest(); + container.register(request, Log.class); + } + + @SuppressWarnings("unchecked") + private TailableCursorRequest getTailableCursorRequest() { + MessageListener listener = message -> { + log.info("ERROR log received: {}", message.getBody()); + counter.incrementAndGet(); + }; + + return TailableCursorRequest.builder() + .collection(collectionName) + .filter(query(where(LEVEL_FIELD_NAME).is(LogLevel.ERROR))) + .publishTo(listener) + .build(); + } + + @Override + public int count() { + return counter.get(); + } + + @PreDestroy + public void close() { + container.stop(); + } +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/InfoLogsCounter.java b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/InfoLogsCounter.java new file mode 100644 index 0000000000..29301bffec --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/InfoLogsCounter.java @@ -0,0 +1,36 @@ +package com.baeldung.tailablecursor.service; + +import com.baeldung.tailablecursor.domain.Log; +import com.baeldung.tailablecursor.domain.LogLevel; +import com.baeldung.tailablecursor.repository.LogsRepository; +import lombok.extern.slf4j.Slf4j; +import reactor.core.Disposable; +import reactor.core.publisher.Flux; + +import javax.annotation.PreDestroy; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +public class InfoLogsCounter implements LogsCounter { + + private final AtomicInteger counter = new AtomicInteger(); + private final Disposable subscription; + + public InfoLogsCounter(LogsRepository repository) { + Flux stream = repository.findByLevel(LogLevel.INFO); + this.subscription = stream.subscribe(logEntity -> { + log.info("INFO log received: " + logEntity); + counter.incrementAndGet(); + }); + } + + @Override + public int count() { + return this.counter.get(); + } + + @PreDestroy + public void close() { + this.subscription.dispose(); + } +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/LogsCounter.java b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/LogsCounter.java new file mode 100644 index 0000000000..e14a3eadd7 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/LogsCounter.java @@ -0,0 +1,5 @@ +package com.baeldung.tailablecursor.service; + +public interface LogsCounter { + int count(); +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/WarnLogsCounter.java b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/WarnLogsCounter.java new file mode 100644 index 0000000000..2dff8e8e40 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/WarnLogsCounter.java @@ -0,0 +1,41 @@ +package com.baeldung.tailablecursor.service; + +import com.baeldung.tailablecursor.domain.Log; +import com.baeldung.tailablecursor.domain.LogLevel; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.mongodb.core.ReactiveMongoOperations; +import reactor.core.Disposable; +import reactor.core.publisher.Flux; + +import javax.annotation.PreDestroy; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.springframework.data.mongodb.core.query.Criteria.where; +import static org.springframework.data.mongodb.core.query.Query.query; + +@Slf4j +public class WarnLogsCounter implements LogsCounter { + + private static final String LEVEL_FIELD_NAME = "level"; + + private final AtomicInteger counter = new AtomicInteger(); + private final Disposable subscription; + + public WarnLogsCounter(ReactiveMongoOperations template) { + Flux stream = template.tail(query(where(LEVEL_FIELD_NAME).is(LogLevel.WARN)), Log.class); + subscription = stream.subscribe(logEntity -> { + log.warn("WARN log received: " + logEntity); + counter.incrementAndGet(); + }); + } + + @Override + public int count() { + return counter.get(); + } + + @PreDestroy + public void close() { + subscription.dispose(); + } +} diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java new file mode 100644 index 0000000000..a31ef4458d --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java @@ -0,0 +1,125 @@ +package com.baeldung.r2dbc; + + +import com.baeldung.r2dbc.model.Player; +import com.baeldung.r2dbc.repository.PlayerRepository; +import io.r2dbc.h2.H2ConnectionFactory; +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.r2dbc.core.DatabaseClient; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Hooks; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.util.Arrays; +import java.util.List; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class R2dbcApplicationIntegrationTest { + + + @Autowired + PlayerRepository playerRepository; + + @Autowired + DatabaseClient client; + + @Autowired + H2ConnectionFactory factory; + + + @Before + public void setup() { + + Hooks.onOperatorDebug(); + + List statements = Arrays.asList(// + "DROP TABLE IF EXISTS player;", + "CREATE table player (id INT AUTO_INCREMENT NOT NULL, name VARCHAR2, age INT NOT NULL);"); + + statements.forEach(it -> client.execute() // + .sql(it) // + .fetch() // + .rowsUpdated() // + .as(StepVerifier::create) // + .expectNextCount(1) // + .verifyComplete()); + + } + + @Test + public void whenDeleteAll_then0IsExpected() { + + + playerRepository.deleteAll() + .as(StepVerifier::create) + .expectNextCount(0) + .verifyComplete(); + } + + @Test + public void whenInsert6_then6AreExpected() { + + insertPlayers(); + + playerRepository.findAll() + .as(StepVerifier::create) + .expectNextCount(6) + .verifyComplete(); + } + + @Test + public void whenSearchForCR7_then1IsExpected() { + + insertPlayers(); + + playerRepository.findAllByName("CR7") + .as(StepVerifier::create) + .expectNextCount(1) + .verifyComplete(); + } + + @Test + public void whenSearchFor32YearsOld_then2AreExpected() { + insertPlayers(); + + playerRepository.findByAge(32) + .as(StepVerifier::create) + .expectNextCount(2) + .verifyComplete(); + } + + @Test + public void whenBatchHas2Operations_then2AreExpected() { + Mono.from(factory.create()) + .flatMapMany(connection -> Flux.from(connection + .createBatch() + .add("select * from player") + .add("select * from player") + .execute())) + .as(StepVerifier::create) + .expectNextCount(2) + .verifyComplete(); + + } + + private void insertPlayers() { + List players = Arrays.asList( + new Player(1, "Kaka", 37), + new Player(2, "Messi", 32), + new Player(3, "Mbappé", 20), + new Player(4, "CR7", 34), + new Player(5, "Lewandowski", 30), + new Player(6, "Cavani", 32) + ); + + playerRepository.saveAll(players).subscribe(); + } +} + diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/tailablecursor/service/ErrorLogsCounterManualTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/tailablecursor/service/ErrorLogsCounterManualTest.java new file mode 100644 index 0000000000..5e20d3ec79 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/tailablecursor/service/ErrorLogsCounterManualTest.java @@ -0,0 +1,112 @@ +package com.baeldung.tailablecursor.service; + +import com.baeldung.tailablecursor.domain.Log; +import com.baeldung.tailablecursor.domain.LogLevel; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.CreateCollectionOptions; +import de.flapdoodle.embed.mongo.MongodExecutable; +import de.flapdoodle.embed.mongo.MongodProcess; +import de.flapdoodle.embed.mongo.MongodStarter; +import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; +import de.flapdoodle.embed.mongo.config.Net; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.process.runtime.Network; +import org.bson.Document; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.util.SocketUtils; + +import java.io.IOException; +import java.util.stream.IntStream; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +public class ErrorLogsCounterManualTest { + + private static final String SERVER = "localhost"; + private static final int PORT = SocketUtils.findAvailableTcpPort(10000); + private static final String DB_NAME = "test"; + private static final String COLLECTION_NAME = Log.class.getName().toLowerCase(); + + private static final MongodStarter starter = MongodStarter.getDefaultInstance(); + private static final int MAX_DOCUMENTS_IN_COLLECTION = 3; + + private ErrorLogsCounter errorLogsCounter; + private MongodExecutable mongodExecutable; + private MongodProcess mongoDaemon; + private MongoDatabase db; + + @Before + public void setup() throws Exception { + MongoTemplate mongoTemplate = initMongoTemplate(); + + MongoCollection collection = createCappedCollection(); + + persistDocument(collection, -1, LogLevel.ERROR, "my-service", "Initial log"); + + errorLogsCounter = new ErrorLogsCounter(mongoTemplate, COLLECTION_NAME); + Thread.sleep(1000L); // wait for initialization + } + + private MongoTemplate initMongoTemplate() throws IOException { + mongodExecutable = starter.prepare(new MongodConfigBuilder() + .version(Version.Main.PRODUCTION) + .net(new Net(SERVER, PORT, Network.localhostIsIPv6())) + .build()); + mongoDaemon = mongodExecutable.start(); + + MongoClient mongoClient = new MongoClient(SERVER, PORT); + db = mongoClient.getDatabase(DB_NAME); + + return new MongoTemplate(mongoClient, DB_NAME); + } + + private MongoCollection createCappedCollection() { + db.createCollection(COLLECTION_NAME, new CreateCollectionOptions() + .capped(true) + .sizeInBytes(100000) + .maxDocuments(MAX_DOCUMENTS_IN_COLLECTION)); + return db.getCollection(COLLECTION_NAME); + } + + private void persistDocument(MongoCollection collection, + int i, LogLevel level, String service, String message) { + Document logMessage = new Document(); + logMessage.append("_id", i); + logMessage.append("level", level.toString()); + logMessage.append("service", service); + logMessage.append("message", message); + collection.insertOne(logMessage); + } + + @After + public void tearDown() { + errorLogsCounter.close(); + mongoDaemon.stop(); + mongodExecutable.stop(); + } + + @Test + public void whenErrorLogsArePersisted_thenTheyAreReceivedByLogsCounter() throws Exception { + MongoCollection collection = db.getCollection(COLLECTION_NAME); + + IntStream.range(1, 10) + .forEach(i -> persistDocument(collection, + i, + i > 5 ? LogLevel.ERROR : LogLevel.INFO, + "service" + i, + "Message from service " + i) + ); + + Thread.sleep(1000L); // wait to receive all messages from the reactive mongodb driver + + assertThat(collection.countDocuments(), is((long) MAX_DOCUMENTS_IN_COLLECTION)); + assertThat(errorLogsCounter.count(), is(5)); + } + +} diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/tailablecursor/service/InfoLogsCounterManualTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/tailablecursor/service/InfoLogsCounterManualTest.java new file mode 100644 index 0000000000..cd8bd68257 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/tailablecursor/service/InfoLogsCounterManualTest.java @@ -0,0 +1,75 @@ +package com.baeldung.tailablecursor.service; + +import com.baeldung.tailablecursor.LogsCounterApplication; +import com.baeldung.tailablecursor.domain.Log; +import com.baeldung.tailablecursor.domain.LogLevel; +import com.baeldung.tailablecursor.repository.LogsRepository; +import lombok.extern.slf4j.Slf4j; +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.mongodb.core.CollectionOptions; +import org.springframework.data.mongodb.core.ReactiveMongoTemplate; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = LogsCounterApplication.class) +@Slf4j +public class InfoLogsCounterManualTest { + @Autowired + private LogsRepository repository; + + @Autowired + private ReactiveMongoTemplate template; + + @Before + public void setUp() { + createCappedCollectionUsingReactiveMongoTemplate(template); + + persistDocument(Log.builder() + .level(LogLevel.INFO) + .service("Service 2") + .message("Initial INFO message") + .build()); + } + + private void createCappedCollectionUsingReactiveMongoTemplate(ReactiveMongoTemplate reactiveMongoTemplate) { + reactiveMongoTemplate.dropCollection(Log.class).block(); + reactiveMongoTemplate.createCollection(Log.class, CollectionOptions.empty() + .maxDocuments(5) + .size(1024 * 1024L) + .capped()).block(); + } + + private void persistDocument(Log log) { + repository.save(log).block(); + } + + @Test + public void wheInfoLogsArePersisted_thenTheyAreReceivedByLogsCounter() throws Exception { + InfoLogsCounter infoLogsCounter = new InfoLogsCounter(repository); + + Thread.sleep(1000L); // wait for initialization + + Flux.range(0,10) + .map(i -> Log.builder() + .level(i > 5 ? LogLevel.WARN : LogLevel.INFO) + .service("some-service") + .message("some log message") + .build()) + .map(entity -> repository.save(entity).subscribe()) + .blockLast(); + + Thread.sleep(1000L); // wait to receive all messages from the reactive mongodb driver + + assertThat(infoLogsCounter.count(), is(7)); + infoLogsCounter.close(); + } +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/tailablecursor/service/WarnLogsCounterManualTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/tailablecursor/service/WarnLogsCounterManualTest.java new file mode 100644 index 0000000000..79d94b6784 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/tailablecursor/service/WarnLogsCounterManualTest.java @@ -0,0 +1,75 @@ +package com.baeldung.tailablecursor.service; + +import com.baeldung.tailablecursor.LogsCounterApplication; +import com.baeldung.tailablecursor.domain.Log; +import com.baeldung.tailablecursor.domain.LogLevel; +import com.baeldung.tailablecursor.repository.LogsRepository; +import lombok.extern.slf4j.Slf4j; +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.mongodb.core.CollectionOptions; +import org.springframework.data.mongodb.core.ReactiveMongoTemplate; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = LogsCounterApplication.class) +@Slf4j +public class WarnLogsCounterManualTest { + @Autowired + private LogsRepository repository; + + @Autowired + private ReactiveMongoTemplate template; + + @Before + public void setUp() { + createCappedCollectionUsingReactiveMongoTemplate(template); + + persistDocument(Log.builder() + .level(LogLevel.WARN) + .service("Service 1") + .message("Initial Warn message") + .build()); + } + + private void createCappedCollectionUsingReactiveMongoTemplate(ReactiveMongoTemplate reactiveMongoTemplate) { + reactiveMongoTemplate.dropCollection(Log.class).block(); + reactiveMongoTemplate.createCollection(Log.class, CollectionOptions.empty() + .maxDocuments(5) + .size(1024 * 1024L) + .capped()).block(); + } + + private void persistDocument(Log log) { + repository.save(log).block(); + } + + @Test + public void whenWarnLogsArePersisted_thenTheyAreReceivedByLogsCounter() throws Exception { + WarnLogsCounter warnLogsCounter = new WarnLogsCounter(template); + + Thread.sleep(1000L); // wait for initialization + + Flux.range(0,10) + .map(i -> Log.builder() + .level(i > 5 ? LogLevel.WARN : LogLevel.INFO) + .service("some-service") + .message("some log message") + .build()) + .map(entity -> repository.save(entity).subscribe()) + .blockLast(); + + Thread.sleep(1000L); // wait to receive all messages from the reactive mongodb driver + + assertThat(warnLogsCounter.count(), is(5)); + warnLogsCounter.close(); + } +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c3ea1d8435 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 5fb8f66f71..302080a8b4 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -1,5 +1,6 @@ - 4.0.0 com.baeldung @@ -51,12 +52,10 @@ org.jetbrains.kotlin kotlin-stdlib-jre8 - ${kotlin.version} org.jetbrains.kotlin kotlin-reflect - ${kotlin.version} com.fasterxml.jackson.module @@ -91,7 +90,6 @@ - ${project.basedir}/src/main/kotlin ${project.basedir}/src/test/kotlin @@ -132,11 +130,43 @@ + + org.codehaus.mojo + build-helper-maven-plugin + + + generate-sources + + add-source + + + + ${basedir}/src/main/java + ${basedir}/src/main/kotlin + + + + + test-compile + test-compile + + add-test-source + + + + ${basedir}/src/test/java + ${basedir}/src/test/kotlin + + + + + - + 2.9.0 1.1.2 + com.baeldung.Spring5Application diff --git a/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..678d04897b --- /dev/null +++ b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java similarity index 87% rename from spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java index 7360def71e..81e77d9c61 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java @@ -6,7 +6,7 @@ import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @Component -public class DownstreamServiceReactiveHealthIndicator implements ReactiveHealthIndicator { +public class DownstreamServiceHealthIndicator implements ReactiveHealthIndicator { @Override public Mono health() { diff --git a/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..479c35d986 --- /dev/null +++ b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java index 10cfaffce4..42da90ecd5 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java @@ -1,10 +1,13 @@ package com.baeldung.reactive.errorhandling; -import java.io.IOException; import static org.junit.Assert.assertEquals; + +import java.io.IOException; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.MediaType; @@ -15,6 +18,7 @@ import org.springframework.test.web.reactive.server.WebTestClient; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) @WithMockUser +@AutoConfigureWebTestClient(timeout = "10000") public class ErrorHandlingIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java index fbf46a93cc..c1523cb5ee 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java @@ -3,6 +3,7 @@ package com.baeldung.reactive.filters; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; @@ -14,6 +15,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @WithMockUser +@AutoConfigureWebTestClient(timeout = "10000") public class PlayerHandlerIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java index 17fea6b50b..4395e0b048 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java @@ -28,7 +28,7 @@ public class PostExecutionUnitTest { .expectComplete() .verifyThenAssertThat() .hasDropped(4) - .tookLessThan(Duration.ofMillis(1050)); + .tookLessThan(Duration.ofMillis(1500)); } } diff --git a/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c3ea1d8435 --- /dev/null +++ b/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-security-cognito/pom.xml b/spring-5-security-cognito/pom.xml index c7314d6f9f..431c9b8d9c 100644 --- a/spring-5-security-cognito/pom.xml +++ b/spring-5-security-cognito/pom.xml @@ -48,7 +48,6 @@ org.springframework.security spring-security-oauth2-jose - org.springframework spring-test diff --git a/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..729790bd14 --- /dev/null +++ b/spring-5-security/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-webflux/README.md b/spring-5-webflux/README.md index e84ee863bf..87d9ae0dd3 100644 --- a/spring-5-webflux/README.md +++ b/spring-5-webflux/README.md @@ -3,3 +3,4 @@ - [Spring Boot Reactor Netty Configuration](https://www.baeldung.com/spring-boot-reactor-netty) - [How to Return 404 with Spring WebFlux](https://www.baeldung.com/spring-webflux-404) - [Spring WebClient Requests with Parameters](https://www.baeldung.com/webflux-webclient-parameters) +- [RSocket Using Spring Boot](https://www.baeldung.com/spring-boot-rsocket) diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index c1f537d2fe..6887f01753 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -28,11 +28,6 @@ - - 1.8 - 2.2.0.M3 - - org.springframework.boot @@ -86,6 +81,7 @@ https://repo.spring.io/milestone + spring-snapshots @@ -101,4 +97,8 @@ https://repo.spring.io/milestone + + + 2.2.0.M3 + diff --git a/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/AccountService.java b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/AccountService.java new file mode 100644 index 0000000000..1997163954 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/AccountService.java @@ -0,0 +1,8 @@ +package com.baeldung.annotationconfigvscomponentscan.components; + +import org.springframework.stereotype.Component; + +@Component +public class AccountService { + +} diff --git a/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/UserService.java b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/UserService.java new file mode 100644 index 0000000000..8dd5ae2ef0 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/UserService.java @@ -0,0 +1,16 @@ +package com.baeldung.annotationconfigvscomponentscan.components; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class UserService { + + @Autowired + private AccountService accountService; + + public AccountService getAccountService() { + return accountService; + } + +} diff --git a/spring-5/src/main/resources/annotationconfigvscomponentscan-beans.xml b/spring-5/src/main/resources/annotationconfigvscomponentscan-beans.xml new file mode 100644 index 0000000000..ee4bbb6573 --- /dev/null +++ b/spring-5/src/main/resources/annotationconfigvscomponentscan-beans.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java new file mode 100644 index 0000000000..7cd7b81def --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.annotationconfigvscomponentscan.components.AccountService; +import com.baeldung.annotationconfigvscomponentscan.components.UserService; + +public class SpringXMLConfigurationIntegrationTest { + + @Test + public void givenContextAnnotationConfigOrContextComponentScan_whenDependenciesAndBeansAnnotated_thenNoXMLNeeded() { + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:annotationconfigvscomponentscan-beans.xml"); + UserService userService = context.getBean(UserService.class); + AccountService accountService = context.getBean(AccountService.class); + Assert.assertNotNull(userService); + Assert.assertNotNull(accountService); + Assert.assertNotNull(userService.getAccountService()); + } + +} diff --git a/spring-5/src/test/java/org/baeldung/SpringContextTest.java b/spring-5/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..56e8697f5c --- /dev/null +++ b/spring-5/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-activiti/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-activiti/src/test/java/com/baeldung/SpringContextIntegrationTest.java index ce48080753..89411df976 100644 --- a/spring-activiti/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/spring-activiti/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @@ -9,6 +10,7 @@ import com.baeldung.activitiwithspring.ActivitiWithSpringApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = ActivitiWithSpringApplication.class) +@AutoConfigureTestDatabase public class SpringContextIntegrationTest { @Test diff --git a/spring-activiti/src/test/java/com/baeldung/SpringContextTest.java b/spring-activiti/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..14df617b1f --- /dev/null +++ b/spring-activiti/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.activitiwithspring.ActivitiWithSpringApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ActivitiWithSpringApplication.class) +@AutoConfigureTestDatabase +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java b/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java index 53bdcee888..7f99483fcf 100644 --- a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java +++ b/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java @@ -4,6 +4,7 @@ import org.activiti.engine.IdentityService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.test.context.junit4.SpringRunner; @@ -14,6 +15,7 @@ import com.baeldung.activiti.security.withspring.ActivitiSpringSecurityApplicati @RunWith(SpringRunner.class) @SpringBootTest(classes = ActivitiSpringSecurityApplication.class) @WebAppConfiguration +@AutoConfigureTestDatabase public class ActivitiSpringSecurityIntegrationTest { @Autowired private IdentityService identityService; diff --git a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java b/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java index 8c1e400215..d289693a73 100644 --- a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java +++ b/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java @@ -2,11 +2,13 @@ package com.baeldung.activitiwithspring; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = ActivitiWithSpringApplication.class) +@AutoConfigureTestDatabase public class ActivitiWithSpringApplicationIntegrationTest { @Test diff --git a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ProcessEngineCreationIntegrationTest.java b/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ProcessEngineCreationIntegrationTest.java index 00538f8e6e..5052f84d6a 100644 --- a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ProcessEngineCreationIntegrationTest.java +++ b/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ProcessEngineCreationIntegrationTest.java @@ -4,7 +4,7 @@ import org.activiti.engine.ProcessEngine; import org.activiti.engine.ProcessEngineConfiguration; import org.activiti.engine.ProcessEngines; import org.junit.Test; - +import org.junit.After; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -62,4 +62,9 @@ public class ProcessEngineCreationIntegrationTest { assertNotNull(processEngine); assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); } + + @After + public void cleanup() { + ProcessEngines.destroy(); + } } diff --git a/spring-all/src/main/java/org/baeldung/primary/Config.java b/spring-all/src/main/java/org/baeldung/primary/Config.java index b39f2b9db3..bdcfe019e6 100644 --- a/spring-all/src/main/java/org/baeldung/primary/Config.java +++ b/spring-all/src/main/java/org/baeldung/primary/Config.java @@ -10,13 +10,13 @@ import org.springframework.context.annotation.Primary; public class Config { @Bean - public Employee JohnEmployee(){ + public Employee johnEmployee(){ return new Employee("John"); } @Bean @Primary - public Employee TonyEmployee(){ + public Employee tonyEmployee(){ return new Employee("Tony"); } } diff --git a/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java b/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java new file mode 100644 index 0000000000..41db539265 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java @@ -0,0 +1,18 @@ +package org.baeldung.startup; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class ProfileManager { + + @Autowired + private Environment environment; + + public void getActiveProfiles() { + for (final String profileName : environment.getActiveProfiles()) { + System.out.println("Currently active profile - " + profileName); + } + } +} diff --git a/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java b/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java index aa88a3775e..0ae99610f6 100644 --- a/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java @@ -12,7 +12,7 @@ public class ScopesIntegrationTest { private static final String NAME_OTHER = "Anna Jones"; @Test - public void testScopeSingleton() { + public void givenSingletonScope_whenSetName_thenEqualNames() { final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); final Person personSingletonA = (Person) applicationContext.getBean("personSingleton"); @@ -25,7 +25,7 @@ public class ScopesIntegrationTest { } @Test - public void testScopePrototype() { + public void givenPrototypeScope_whenSetNames_thenDifferentNames() { final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype"); diff --git a/spring-aop/src/test/java/org/baeldung/SpringContextTest.java b/spring-aop/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4d3ed953c4 --- /dev/null +++ b/spring-aop/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-apache-camel/.gitignore b/spring-apache-camel/.gitignore new file mode 100644 index 0000000000..eac473ac50 --- /dev/null +++ b/spring-apache-camel/.gitignore @@ -0,0 +1 @@ +/src/test/destination-folder/* \ No newline at end of file diff --git a/spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File2.txt b/spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File2.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1c098a56ab --- /dev/null +++ b/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.camel.main.App; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-batch/.gitignore b/spring-batch/.gitignore new file mode 100644 index 0000000000..0ef6d10b38 --- /dev/null +++ b/spring-batch/.gitignore @@ -0,0 +1 @@ +output.csv \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/SpringContextTest.java b/spring-batch/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0de9a07b0a --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.baeldung.batch.App; +import org.junit.Test; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-bom/src/test/java/org/baeldung/SpringContextTest.java b/spring-bom/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..783567cdfa --- /dev/null +++ b/spring-bom/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.spring.bom.HelloWorldApp; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + HelloWorldApp.main(null); + } +} diff --git a/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..834f26dacf --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c185456019 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..961d756a68 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-angular/pom.xml b/spring-boot-angular/pom.xml index 6ea98eb3d0..71c46cb7f5 100644 --- a/spring-boot-angular/pom.xml +++ b/spring-boot-angular/pom.xml @@ -6,15 +6,13 @@ spring-boot-angular 1.0 jar + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT ../../parent-boot-2 - - 1.8 - @@ -46,5 +44,4 @@ - diff --git a/spring-boot-autoconfiguration/README.MD b/spring-boot-autoconfiguration/README.MD index a71af54dff..dc9cad539a 100644 --- a/spring-boot-autoconfiguration/README.MD +++ b/spring-boot-autoconfiguration/README.MD @@ -3,4 +3,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Create a Custom Auto-Configuration with Spring Boot](http://www.baeldung.com/spring-boot-custom-auto-configuration) \ No newline at end of file +- [Create a Custom Auto-Configuration with Spring Boot](http://www.baeldung.com/spring-boot-custom-auto-configuration) +- [Guide to ApplicationContextRunner in Spring Boot](https://www.baeldung.com/spring-boot-context-runner) diff --git a/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4340e27fb4 --- /dev/null +++ b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.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 +public class SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8324fabfca --- /dev/null +++ b/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9c3b83ea79 --- /dev/null +++ b/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-crud/pom.xml b/spring-boot-crud/pom.xml index 15ff6c5d11..1d956bdba6 100644 --- a/spring-boot-crud/pom.xml +++ b/spring-boot-crud/pom.xml @@ -54,7 +54,28 @@ org.springframework.boot spring-boot-maven-plugin + + exec + + + org.apache.maven.plugins + maven-assembly-plugin + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + @@ -62,4 +83,4 @@ UTF-8 - \ No newline at end of file + diff --git a/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ff3e795778 --- /dev/null +++ b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.parent.App; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(new String[] {}); + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e6ce83fab5 --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b82b67df68 --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-data/pom.xml b/spring-boot-data/pom.xml index 8735a54e7b..9c11e09f4a 100644 --- a/spring-boot-data/pom.xml +++ b/spring-boot-data/pom.xml @@ -15,6 +15,30 @@ + + org.springframework.boot + spring-boot-starter-data-redis + 2.1.6.RELEASE + + + + org.springframework.boot + spring-boot-starter-data-mongodb + 2.1.6.RELEASE + + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.1.6.RELEASE + + + + com.h2database + h2 + 1.4.197 + + org.springframework.boot spring-boot-starter-web diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java new file mode 100644 index 0000000000..8e4ee76a25 --- /dev/null +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java @@ -0,0 +1,16 @@ +package com.baeldung.disableautoconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; + +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +public class SpringDataJPA { + + public static void main(String[] args) { + SpringApplication.run(SpringDataJPA.class, args); + } +} diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java new file mode 100644 index 0000000000..865c137a8d --- /dev/null +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java @@ -0,0 +1,14 @@ +package com.baeldung.disableautoconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; + +@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class}) +public class SpringDataMongoDB { + + public static void main(String[] args) { + SpringApplication.run(SpringDataMongoDB.class, args); + } +} diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java new file mode 100644 index 0000000000..9ec831c446 --- /dev/null +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java @@ -0,0 +1,14 @@ +package com.baeldung.disableautoconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; +import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration; + +@SpringBootApplication(exclude = {RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class}) +public class SpringDataRedis { + + public static void main(String[] args) { + SpringApplication.run(SpringDataRedis.class, args); + } +} diff --git a/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java new file mode 100644 index 0000000000..a465979b3c --- /dev/null +++ b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.disableautoconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.sql.DataSource; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataJPA.class) +public class SpringDataJPAIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test(expected = NoSuchBeanDefinitionException.class) + public void givenAutoconfigurationIsDisable_whenApplicationStarts_thenContextWillNotHaveTheAutoconfiguredClasses() { + context.getBean(DataSource.class); + } + +} diff --git a/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java new file mode 100644 index 0000000000..bdfadf76ce --- /dev/null +++ b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.disableautoconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.test.context.junit4.SpringRunner; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataMongoDB.class) +public class SpringDataMongoDBIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test(expected = NoSuchBeanDefinitionException.class) + public void givenAutoconfigurationIsDisable_whenApplicationStarts_thenContextWillNotHaveTheAutoconfiguredClasses() { + context.getBean(MongoTemplate.class); + } + +} diff --git a/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java new file mode 100644 index 0000000000..10133cace3 --- /dev/null +++ b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.disableautoconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.test.context.junit4.SpringRunner; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataRedis.class) +public class SpringDataRedisIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test(expected = NoSuchBeanDefinitionException.class) + public void givenAutoconfigurationIsDisable_whenApplicationStarts_thenContextWillNotHaveTheAutoconfiguredClasses() { + context.getBean(RedisTemplate.class); + } + +} diff --git a/spring-boot-di/README.MD b/spring-boot-di/README.MD new file mode 100644 index 0000000000..78cd163668 --- /dev/null +++ b/spring-boot-di/README.MD @@ -0,0 +1,6 @@ +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) diff --git a/spring-boot-di/pom.xml b/spring-boot-di/pom.xml new file mode 100644 index 0000000000..ec40c04566 --- /dev/null +++ b/spring-boot-di/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + spring-boot-mvc + spring-boot-mvc + jar + Module For Spring Boot DI + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.SpringBootDiApplication + JAR + + + + + + + com.baeldung.SpringBootDiApplication + + + diff --git a/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java b/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java new file mode 100644 index 0000000000..b9d2d7ecef --- /dev/null +++ b/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootDiApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootDiApplication.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/ExampleBean.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/ExampleBean.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java similarity index 88% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java index 2377ed7a56..83b91f7860 100644 --- a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java +++ b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java @@ -1,10 +1,6 @@ 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; diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java similarity index 88% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java index ba29a4e1f5..4362caefbb 100644 --- a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java +++ b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java @@ -1,14 +1,11 @@ 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") diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java diff --git a/spring-boot-flowable/pom.xml b/spring-boot-flowable/pom.xml index f9531a1e6a..f7fc943389 100644 --- a/spring-boot-flowable/pom.xml +++ b/spring-boot-flowable/pom.xml @@ -7,12 +7,14 @@ war spring-boot-flowable Spring Boot Flowable Module + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT ../parent-boot-2 + org.springframework.boot @@ -44,6 +46,7 @@ test + @@ -52,6 +55,7 @@ + 6.4.1 diff --git a/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ab6e4557d5 --- /dev/null +++ b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4effccc083 --- /dev/null +++ b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-kotlin/README.md b/spring-boot-kotlin/README.md new file mode 100644 index 0000000000..dc50c24aa0 --- /dev/null +++ b/spring-boot-kotlin/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Non-blocking Spring Boot with Kotlin Coroutines](http://www.baeldung.com/non-blocking-spring-boot-with-kotlin-coroutines) diff --git a/spring-boot-kotlin/pom.xml b/spring-boot-kotlin/pom.xml new file mode 100644 index 0000000000..25508c52b9 --- /dev/null +++ b/spring-boot-kotlin/pom.xml @@ -0,0 +1,166 @@ + + + 4.0.0 + spring-boot-kotlin + spring-boot-kotlin + jar + Demo project showing how to use non-blocking in Kotlin with Spring Boot + + + parent-kotlin + com.baeldung + 1.0.0-SNAPSHOT + ../parent-kotlin + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + + org.jetbrains.kotlin + kotlin-reflect + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + ${kotlinx-coroutines.version} + + + org.jetbrains.kotlinx + kotlinx-coroutines-reactor + ${kotlinx-coroutines.version} + + + org.springframework.boot + spring-boot-starter-webflux + ${spring-boot.version} + + + com.fasterxml.jackson.module + jackson-module-kotlin + + + org.springframework.data + spring-data-r2dbc + ${r2dbc.version} + + + io.r2dbc + r2dbc-h2 + ${h2-r2dbc.version} + + + io.r2dbc + r2dbc-spi + ${r2dbc-spi.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + junit + junit + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + io.projectreactor + reactor-test + test + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + + + -Xjsr305=strict + + + spring + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + 1.3.31 + 1.0.0.M1 + 1.0.0.M7 + 1.0.0.BUILD-SNAPSHOT + 1.2.1 + 2.2.0.M2 + + + diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt new file mode 100644 index 0000000000..23af4fe90b --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt @@ -0,0 +1,11 @@ +package com.baeldung.nonblockingcoroutines + +import org.springframework.boot.SpringApplication.run +import org.springframework.boot.autoconfigure.SpringBootApplication + +@SpringBootApplication +class SpringApplication + +fun main(args: Array) { + run(SpringApplication::class.java, *args) +} diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt new file mode 100644 index 0000000000..52ef8a708b --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt @@ -0,0 +1,32 @@ +package com.baeldung.nonblockingcoroutines.config + +import io.r2dbc.h2.H2ConnectionConfiguration +import io.r2dbc.h2.H2ConnectionFactory +import io.r2dbc.spi.ConnectionFactory +import org.springframework.beans.factory.annotation.Value +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration +import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories + +@Configuration +@EnableR2dbcRepositories +class DatastoreConfig : AbstractR2dbcConfiguration() { + @Value("\${spring.datasource.username}") + private val userName: String = "" + + @Value("\${spring.datasource.password}") + private val password: String = "" + + @Value("\${spring.datasource.dbname}") + private val dbName: String = "" + + @Bean + override fun connectionFactory(): ConnectionFactory { + return H2ConnectionFactory(H2ConnectionConfiguration.builder() + .inMemory(dbName) + .username(userName) + .password(password) + .build()) + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt new file mode 100644 index 0000000000..bda1d26278 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt @@ -0,0 +1,19 @@ +package com.baeldung.nonblockingcoroutines.config + +import com.baeldung.nonblockingcoroutines.handlers.ProductsHandler +import kotlinx.coroutines.FlowPreview +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.reactive.function.server.coRouter + +@Configuration +class RouterConfiguration { + + @FlowPreview + @Bean + fun productRoutes(productsHandler: ProductsHandler) = coRouter { + GET("/", productsHandler::findAll) + GET("/{id}", productsHandler::findOne) + GET("/{id}/stock", productsHandler::findOneInStock) + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt new file mode 100644 index 0000000000..85938b8be2 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt @@ -0,0 +1,12 @@ +package com.baeldung.nonblockingcoroutines.config + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.reactive.function.client.WebClient + +@Configuration +class WebClientConfiguration { + + @Bean + fun webClient() = WebClient.builder().baseUrl("http://localhost:8080").build() +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt new file mode 100644 index 0000000000..91b091859a --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt @@ -0,0 +1,49 @@ +package com.baeldung.nonblockingcoroutines.controller + +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepository +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.MediaType +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.reactive.function.client.WebClient +import org.springframework.web.reactive.function.client.bodyToMono +import reactor.core.publisher.Flux +import reactor.core.publisher.Mono + +class ProductController { + @Autowired + lateinit var webClient: WebClient + @Autowired + lateinit var productRepository: ProductRepository + + @GetMapping("/{id}") + fun findOne(@PathVariable id: Int): Mono { + return productRepository + .getProductById(id) + } + + @GetMapping("/{id}/stock") + fun findOneInStock(@PathVariable id: Int): Mono { + val product = productRepository.getProductById(id) + + val stockQuantity = webClient.get() + .uri("/stock-service/product/$id/quantity") + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono() + return product.zipWith(stockQuantity) { productInStock, stockQty -> + ProductStockView(productInStock, stockQty) + } + } + + @GetMapping("/stock-service/product/{id}/quantity") + fun getStockQuantity(): Mono { + return Mono.just(2) + } + + @GetMapping("/") + fun findAll(): Flux { + return productRepository.getAllProducts() + } +} diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt new file mode 100644 index 0000000000..d70d352cda --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt @@ -0,0 +1,49 @@ +package com.baeldung.nonblockingcoroutines.controller + +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.Flow +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.MediaType.APPLICATION_JSON +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.reactive.function.client.WebClient +import org.springframework.web.reactive.function.client.awaitBody +import org.springframework.web.reactive.function.client.awaitExchange + +class ProductControllerCoroutines { + @Autowired + lateinit var webClient: WebClient + + @Autowired + lateinit var productRepository: ProductRepositoryCoroutines + + @GetMapping("/{id}") + suspend fun findOne(@PathVariable id: Int): Product? { + return productRepository.getProductById(id) + } + + @GetMapping("/{id}/stock") + suspend fun findOneInStock(@PathVariable id: Int): ProductStockView { + val product: Deferred = GlobalScope.async { + productRepository.getProductById(id) + } + val quantity: Deferred = GlobalScope.async { + webClient.get() + .uri("/stock-service/product/$id/quantity") + .accept(APPLICATION_JSON) + .awaitExchange().awaitBody() + } + return ProductStockView(product.await()!!, quantity.await()) + } + + @FlowPreview + @GetMapping("/") + fun findAll(): Flow { + return productRepository.getAllProducts() + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt new file mode 100644 index 0000000000..44611fd1de --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt @@ -0,0 +1,15 @@ +package com.baeldung.nonblockingcoroutines.controller + +import com.baeldung.nonblockingcoroutines.model.Product + +class ProductStockView(product: Product, var stockQuantity: Int) { + var id: Int = 0 + var name: String = "" + var price: Float = 0.0f + + init { + this.id = product.id + this.name = product.name + this.price = product.price + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt new file mode 100644 index 0000000000..41c4510e0d --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt @@ -0,0 +1,49 @@ +package com.baeldung.nonblockingcoroutines.handlers + +import com.baeldung.nonblockingcoroutines.controller.ProductStockView +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.async +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.MediaType +import org.springframework.stereotype.Component +import org.springframework.web.reactive.function.client.WebClient +import org.springframework.web.reactive.function.client.awaitBody +import org.springframework.web.reactive.function.client.awaitExchange +import org.springframework.web.reactive.function.server.ServerRequest +import org.springframework.web.reactive.function.server.ServerResponse +import org.springframework.web.reactive.function.server.bodyAndAwait +import org.springframework.web.reactive.function.server.json + +@Component +class ProductsHandler( + @Autowired var webClient: WebClient, + @Autowired var productRepository: ProductRepositoryCoroutines) { + + @FlowPreview + suspend fun findAll(request: ServerRequest): ServerResponse = + ServerResponse.ok().json().bodyAndAwait(productRepository.getAllProducts()) + + suspend fun findOneInStock(request: ServerRequest): ServerResponse { + val id = request.pathVariable("id").toInt() + + val product: Deferred = GlobalScope.async { + productRepository.getProductById(id) + } + val quantity: Deferred = GlobalScope.async { + webClient.get() + .uri("/stock-service/product/$id/quantity") + .accept(MediaType.APPLICATION_JSON) + .awaitExchange().awaitBody() + } + return ServerResponse.ok().json().bodyAndAwait(ProductStockView(product.await()!!, quantity.await())) + } + + suspend fun findOne(request: ServerRequest): ServerResponse { + val id = request.pathVariable("id").toInt() + return ServerResponse.ok().json().bodyAndAwait(productRepository.getProductById(id)!!) + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt new file mode 100644 index 0000000000..c6dcbdc9c4 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt @@ -0,0 +1,7 @@ +package com.baeldung.nonblockingcoroutines.model + +data class Product( + var id: Int = 0, + var name: String = "", + var price: Float = 0.0f +) diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt new file mode 100644 index 0000000000..20c3827c26 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt @@ -0,0 +1,34 @@ +package com.baeldung.nonblockingcoroutines.repository + +import com.baeldung.nonblockingcoroutines.model.Product +import org.springframework.data.r2dbc.function.DatabaseClient +import org.springframework.stereotype.Repository +import reactor.core.publisher.Flux +import reactor.core.publisher.Mono + +@Repository +class ProductRepository(private val client: DatabaseClient) { + + fun getProductById(id: Int): Mono { + return client.execute().sql("SELECT * FROM products WHERE id = $1") + .bind(0, id) + .`as`(Product::class.java) + .fetch() + .one() + } + + fun addNewProduct(name: String, price: Float): Mono { + return client.execute() + .sql("INSERT INTO products (name, price) VALUES($1, $2)") + .bind(0, name) + .bind(1, price) + .then() + } + + fun getAllProducts(): Flux { + return client.select().from("products") + .`as`(Product::class.java) + .fetch() + .all() + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt new file mode 100644 index 0000000000..60a19d4d00 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt @@ -0,0 +1,40 @@ +package com.baeldung.nonblockingcoroutines.repository + + +import com.baeldung.nonblockingcoroutines.model.Product +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.reactive.awaitFirstOrNull +import kotlinx.coroutines.reactive.flow.asFlow +import org.springframework.data.r2dbc.function.DatabaseClient +import org.springframework.stereotype.Repository + +@Repository +class ProductRepositoryCoroutines(private val client: DatabaseClient) { + + suspend fun getProductById(id: Int): Product? = + client.execute().sql("SELECT * FROM products WHERE id = $1") + .bind(0, id) + .`as`(Product::class.java) + .fetch() + .one() + .awaitFirstOrNull() + + suspend fun addNewProduct(name: String, price: Float) = + client.execute() + .sql("INSERT INTO products (name, price) VALUES($1, $2)") + .bind(0, name) + .bind(1, price) + .then() + .awaitFirstOrNull() + + @FlowPreview + fun getAllProducts(): Flow = + client.select() + .from("products") + .`as`(Product::class.java) + .fetch() + .all() + .log() + .asFlow() +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/resources/application.properties b/spring-boot-kotlin/src/main/resources/application.properties new file mode 100644 index 0000000000..0f84ff2d75 --- /dev/null +++ b/spring-boot-kotlin/src/main/resources/application.properties @@ -0,0 +1,8 @@ +logging.level.org.springframework.data.r2dbc=DEBUG +logging.level.org.springframework.web.reactive.function.client.ExchangeFunctions=TRACE +spring.http.log-request-details=true +spring.h2.console.enabled=true +spring.datasource.username=sa +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.password= +spring.datasource.dbname=testdb \ No newline at end of file diff --git a/spring-userservice/src/main/resources/logback.xml b/spring-boot-kotlin/src/main/resources/logback.xml similarity index 100% rename from spring-userservice/src/main/resources/logback.xml rename to spring-boot-kotlin/src/main/resources/logback.xml diff --git a/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt b/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt new file mode 100644 index 0000000000..53b1d50f21 --- /dev/null +++ b/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt @@ -0,0 +1,58 @@ +package com.baeldung.nonblockingcoroutines + +import com.baeldung.nonblockingcoroutines.config.RouterConfiguration +import com.baeldung.nonblockingcoroutines.handlers.ProductsHandler +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.reactive.flow.asFlow +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.BDDMockito.given +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration +import org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest +import org.springframework.boot.test.mock.mockito.MockBean +import org.springframework.test.context.junit4.SpringRunner +import org.springframework.test.web.reactive.server.WebTestClient +import org.springframework.test.web.reactive.server.expectBodyList +import org.springframework.web.reactive.function.client.WebClient +import reactor.core.publisher.Flux +import org.springframework.test.context.ContextConfiguration + +@WebFluxTest( + excludeAutoConfiguration = [ReactiveUserDetailsServiceAutoConfiguration::class, ReactiveSecurityAutoConfiguration::class] +) +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [ProductsHandler::class, RouterConfiguration::class]) +class ProductHandlerTest { + + @Autowired + private lateinit var client: WebTestClient + + @MockBean + private lateinit var webClient: WebClient + + @MockBean + private lateinit var productsRepository: ProductRepositoryCoroutines + + + @FlowPreview + @Test + public fun `get all products`() { + val productsFlow = Flux.just( + Product(1, "product1", 1000.0F), + Product(2, "product2", 2000.0F), + Product(3, "product3", 3000.0F) + ).asFlow() + given(productsRepository.getAllProducts()).willReturn(productsFlow) + client.get() + .uri("/") + .exchange() + .expectStatus() + .isOk + .expectBodyList() + } + +} diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml index 6cc60da52c..64696969ca 100644 --- a/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/pom.xml @@ -34,6 +34,12 @@ org.springframework.boot spring-boot-starter-log4j2 + + org.projectlombok + lombok + 1.18.4 + provided + diff --git a/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java b/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java new file mode 100644 index 0000000000..5f75dbd5a1 --- /dev/null +++ b/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java @@ -0,0 +1,28 @@ +package com.baeldung.springbootlogging; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import lombok.extern.slf4j.Slf4j; + +//import lombok.extern.log4j.Log4j2; +//import lombok.extern.apachecommons.CommonsLog; + +@RestController("LombokLoggingController") +@Slf4j +// @CommonsLog (Comment any other Lombok logging annotation and uncomment this +// to work with Apache Commons Logging) +// @Log4j2 (Comment any other Lombok logging annotation and uncomment this to +// work directly with Log4j2) +public class LombokLoggingController { + + @GetMapping("/lombok") + public String index() { + log.trace("A TRACE Message"); + log.debug("A DEBUG Message"); + log.info("An INFO Message"); + log.warn("A WARN Message"); + log.error("An ERROR Message"); + return "Howdy! Check out the Logs to see the output..."; + } +} diff --git a/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9817522e68 --- /dev/null +++ b/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-mvc-birt/pom.xml b/spring-boot-mvc-birt/pom.xml index 8f41e8410a..bf6bbbf71d 100644 --- a/spring-boot-mvc-birt/pom.xml +++ b/spring-boot-mvc-birt/pom.xml @@ -9,10 +9,12 @@ 0.0.1-SNAPSHOT jar Module For Spring Boot Integration with BIRT + - org.springframework.boot - spring-boot-starter-parent - 2.1.1.RELEASE + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/spring-boot-mvc/README.md b/spring-boot-mvc/README.md index d5a39cdc9f..e3e3dbdb74 100644 --- a/spring-boot-mvc/README.md +++ b/spring-boot-mvc/README.md @@ -12,3 +12,5 @@ - [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) - [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js) +- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) +- [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index e17c1d39b9..fee725847f 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -40,7 +40,7 @@ org.glassfish javax.faces - 2.3.7 + ${javax.faces.version} @@ -108,6 +108,7 @@ 2.9.2 1.10.0 + 2.3.7 com.baeldung.springbootmvc.SpringBootMvcApplication diff --git a/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..16e0708fc9 --- /dev/null +++ b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-ops-2/README.MD b/spring-boot-ops-2/README.MD index 20b30515fb..b4218dc395 100644 --- a/spring-boot-ops-2/README.MD +++ b/spring-boot-ops-2/README.MD @@ -1,3 +1,4 @@ ### Relevant Articles -- [How to Configure Spring Boot Tomcat](https://www.baeldung.com/spring-boot-configure-tomcat) \ No newline at end of file +- [How to Configure Spring Boot Tomcat](https://www.baeldung.com/spring-boot-configure-tomcat) +- [Spring Boot Embedded Tomcat Logs](https://www.baeldung.com/spring-boot-embedded-tomcat-logs) diff --git a/spring-boot-ops-2/pom.xml b/spring-boot-ops-2/pom.xml index dc5280df48..74fcd79169 100644 --- a/spring-boot-ops-2/pom.xml +++ b/spring-boot-ops-2/pom.xml @@ -3,6 +3,10 @@ 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 + spring-boot-ops-2 + 0.0.1-SNAPSHOT + spring-boot-ops-2 parent-boot-2 @@ -11,11 +15,6 @@ ../parent-boot-2 - com.baeldung - spring-boot-ops-2 - 0.0.1-SNAPSHOT - spring-boot-ops-2 - org.springframework.boot diff --git a/spring-boot-ops-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java b/spring-boot-ops-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java new file mode 100644 index 0000000000..11bbad8bb2 --- /dev/null +++ b/spring-boot-ops-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.springbootconfiguration; + +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 SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot-parent/README.md b/spring-boot-parent/README.md new file mode 100644 index 0000000000..c3bb4c700d --- /dev/null +++ b/spring-boot-parent/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [The Spring Boot Starter Parent](https://www.baeldung.com/spring-boot-starter-parent) diff --git a/spring-boot-parent/pom.xml b/spring-boot-parent/pom.xml new file mode 100644 index 0000000000..0924917505 --- /dev/null +++ b/spring-boot-parent/pom.xml @@ -0,0 +1,26 @@ + + + + 4.0.0 + com.baeldung + spring-boot-parent + 1.0.0-SNAPSHOT + spring-boot-parent + spring-boot-parent + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + spring-boot-with-starter-parent + spring-boot-with-custom-parent + + + diff --git a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml new file mode 100644 index 0000000000..de2946fbb2 --- /dev/null +++ b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml @@ -0,0 +1,41 @@ + + + + 4.0.0 + spring-boot-with-custom-parent + 1.0.0-SNAPSHOT + spring-boot-with-custom-parent + + + com.baeldung + spring-boot-parent + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + 1.8 + 2.1.5.RELEASE + + + diff --git a/spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java b/spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java new file mode 100644 index 0000000000..169717d7bb --- /dev/null +++ b/spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.customparent; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootStarterCustomParentApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootStarterCustomParentApplication.class, args); + System.out.println("Spring boot application running without starter parent"); + } +} diff --git a/spring-boot-parent/spring-boot-with-starter-parent/pom.xml b/spring-boot-parent/spring-boot-with-starter-parent/pom.xml new file mode 100644 index 0000000000..1c6479ca60 --- /dev/null +++ b/spring-boot-parent/spring-boot-with-starter-parent/pom.xml @@ -0,0 +1,45 @@ + + + + 4.0.0 + com.baeldung + spring-boot-with-starter-parent + 1.0.0-SNAPSHOT + spring-boot-with-starter-parent + + + org.springframework.boot + spring-boot-starter-parent + 2.1.5.RELEASE + + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.1.1.RELEASE + + + + + + + org.springframework.boot + spring-boot-starter-web + + + junit + junit + + + + + 1.8 + 4.11 + + + diff --git a/spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java b/spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java new file mode 100644 index 0000000000..f987165ce0 --- /dev/null +++ b/spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.starterparent; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootStarterParentApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootStarterParentApplication.class, args); + System.out.println("Spring boot application running with starter parent"); + } + +} diff --git a/spring-boot-performance/README.md b/spring-boot-performance/README.md new file mode 100644 index 0000000000..015dd759a8 --- /dev/null +++ b/spring-boot-performance/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Lazy Initialization in Spring Boot 2](https://www.baeldung.com/spring-boot-lazy-initialization) diff --git a/spring-boot-performance/pom.xml b/spring-boot-performance/pom.xml new file mode 100644 index 0000000000..f51df8bc0c --- /dev/null +++ b/spring-boot-performance/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + spring-boot-performance + spring-boot-performance + war + This is a simple Spring Boot application taking advantage of the latest Spring Boot improvements/features. Current version: 2.2 + + + parent-boot-performance + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-performance + + + + + org.springframework.boot + spring-boot-starter + + + + + spring-boot-performance + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + + + + com.baeldung.lazyinitialization.Application + + \ No newline at end of file diff --git a/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java b/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java new file mode 100644 index 0000000000..195b260399 --- /dev/null +++ b/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java @@ -0,0 +1,32 @@ +package com.baeldung.lazyinitialization; + +import com.baeldung.lazyinitialization.services.Writer; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class Application { + + @Bean("writer1") + public Writer getWriter1() { + return new Writer("Writer 1"); + } + + @Bean("writer2") + public Writer getWriter2() { + return new Writer("Writer 2"); + } + + public static void main(String[] args) { + ApplicationContext ctx = SpringApplication.run(Application.class, args); + System.out.println("Application context initialized!!!"); + + Writer writer1 = ctx.getBean("writer1", Writer.class); + writer1.write("First message"); + + Writer writer2 = ctx.getBean("writer2", Writer.class); + writer2.write("Second message"); + } +} diff --git a/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/services/Writer.java b/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/services/Writer.java new file mode 100644 index 0000000000..7c67fb7ea4 --- /dev/null +++ b/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/services/Writer.java @@ -0,0 +1,16 @@ +package com.baeldung.lazyinitialization.services; + +public class Writer { + + private final String writerId; + + public Writer(String writerId) { + this.writerId = writerId; + System.out.println(writerId + " initialized!!!"); + } + + public void write(String message) { + System.out.println(writerId + ": " + message); + } + +} diff --git a/spring-boot-performance/src/main/resources/application.yml b/spring-boot-performance/src/main/resources/application.yml new file mode 100644 index 0000000000..25f03eed56 --- /dev/null +++ b/spring-boot-performance/src/main/resources/application.yml @@ -0,0 +1,3 @@ +spring: + main: + lazy-initialization: true \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..874c4f582f --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..874c4f582f --- /dev/null +++ b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java b/spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java new file mode 100644 index 0000000000..9ebf885d4b --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java @@ -0,0 +1,8 @@ +package com.baeldung.web.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.BAD_REQUEST) +public class BadRequestException extends RuntimeException { +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java b/spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java new file mode 100644 index 0000000000..a80802eadf --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java @@ -0,0 +1,8 @@ +package com.baeldung.web.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { +} diff --git a/spring-boot-rest/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-rest/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9cba7f8fc1 --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.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 = {SpringBootRestApplication.class}) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java similarity index 94% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java rename to spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java index 592ef5354d..3cfa45421c 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java @@ -10,7 +10,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity -public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter { +public class BasicConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java similarity index 90% rename from spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java rename to spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java index c091aa6d75..f221712513 100644 --- a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java +++ b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java @@ -1,27 +1,26 @@ package com.baeldung.springbootsecurity.basic_auth; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.boot.test.context.SpringBootTest; -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; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootSecurityApplication.class) -public class BasicAuthConfigurationIntegrationTest { +public class BasicConfigurationIntegrationTest { TestRestTemplate restTemplate; URL base; @@ -45,7 +44,7 @@ public class BasicAuthConfigurationIntegrationTest { } @Test - public void whenUserWithWrongCredentialsRequestsHomePage_ThenUnauthorizedPage() throws IllegalStateException, IOException { + public void whenUserWithWrongCredentials_thenUnauthorizedPage() throws IllegalStateException, IOException { restTemplate = new TestRestTemplate("user", "wrongpassword"); ResponseEntity response = restTemplate.getForEntity(base.toString(), String.class); diff --git a/spring-boot-testing/pom.xml b/spring-boot-testing/pom.xml index 84107070bd..12fb14b366 100644 --- a/spring-boot-testing/pom.xml +++ b/spring-boot-testing/pom.xml @@ -15,6 +15,10 @@ + + org.springframework.boot + spring-boot-starter-data-redis + org.springframework.boot spring-boot-starter-web @@ -33,6 +37,13 @@ test + + + it.ozimov + embedded-redis + 0.7.2 + test + org.spockframework diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java new file mode 100644 index 0000000000..6b5b20892f --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java @@ -0,0 +1,24 @@ +package com.baeldung.boot.embeddedRedis.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; + +@Configuration +@EnableRedisRepositories +public class RedisConfiguration { + + @Bean + public LettuceConnectionFactory redisConnectionFactory(final RedisProperties redisProperties) { + return new LettuceConnectionFactory(redisProperties.getRedisHost(), redisProperties.getRedisPort()); + } + + @Bean + public RedisTemplate redisTemplate(final LettuceConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(connectionFactory); + return template; + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java new file mode 100644 index 0000000000..76f2e1bbfe --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java @@ -0,0 +1,23 @@ +package com.baeldung.boot.embeddedRedis.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RedisProperties { + private final int redisPort; + private final String redisHost; + + public RedisProperties(@Value("${spring.redis.port}") final int redisPort, @Value("${spring.redis.host}") final String redisHost) { + this.redisPort = redisPort; + this.redisHost = redisHost; + } + + public int getRedisPort() { + return redisPort; + } + + public String getRedisHost() { + return redisHost; + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java new file mode 100644 index 0000000000..41657aaa66 --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java @@ -0,0 +1,25 @@ +package com.baeldung.boot.embeddedRedis.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.redis.core.RedisHash; + +import java.util.UUID; + +@RedisHash("user") +public class User { + @Id private UUID id; + private String name; + + public User(UUID id, String name) { + this.id = id; + this.name = name; + } + + public UUID getId() { + return id; + } + + public String getName() { + return name; + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java new file mode 100644 index 0000000000..0558bb8482 --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.boot.embeddedRedis.domain.repository; + +import com.baeldung.boot.embeddedRedis.domain.User; +import org.springframework.data.repository.CrudRepository; + +import java.util.UUID; + +public interface UserRepository extends CrudRepository { + +} diff --git a/spring-boot-testing/src/main/resources/application.properties b/spring-boot-testing/src/main/resources/application.properties index e378aacdd5..8dc7f6e3c3 100644 --- a/spring-boot-testing/src/main/resources/application.properties +++ b/spring-boot-testing/src/main/resources/application.properties @@ -1,3 +1,6 @@ +# embedded redis +spring.redis.host= localhost +spring.redis.port= 6379 # security spring.security.user.name=john diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java b/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java new file mode 100644 index 0000000000..f3c8b9a954 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.boot; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java new file mode 100644 index 0000000000..b4748bcd38 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java @@ -0,0 +1,28 @@ +package com.baeldung.boot.embeddedRedis; + +import com.baeldung.boot.embeddedRedis.configuration.RedisProperties; +import org.springframework.boot.test.context.TestConfiguration; +import redis.embedded.RedisServer; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +@TestConfiguration +public class TestRedisConfiguration { + + private final RedisServer redisServer; + + public TestRedisConfiguration(final RedisProperties redisProperties) { + this.redisServer = new RedisServer(redisProperties.getRedisPort()); + } + + @PostConstruct + public void postConstruct() { + redisServer.start(); + } + + @PreDestroy + public void preDestroy() { + redisServer.stop(); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9577ccf0e8 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.boot.embeddedRedis.domain.repository; + +import com.baeldung.boot.embeddedRedis.TestRedisConfiguration; +import com.baeldung.boot.embeddedRedis.domain.User; +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.util.UUID; + +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestRedisConfiguration.class) +public class UserRepositoryIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Test + public void shouldSaveUser_toRedis() { + final UUID id = UUID.randomUUID(); + final User user = new User(id, "name"); + + final User saved = userRepository.save(user); + + assertNotNull(saved); + } +} \ No newline at end of file diff --git a/spring-boot-testing/src/test/resources/application-test.properties b/spring-boot-testing/src/test/resources/application-test.properties new file mode 100644 index 0000000000..a2c9b6d480 --- /dev/null +++ b/spring-boot-testing/src/test/resources/application-test.properties @@ -0,0 +1,2 @@ +# test properties +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration \ No newline at end of file diff --git a/spring-boot-testing/src/test/resources/application.properties b/spring-boot-testing/src/test/resources/application.properties new file mode 100644 index 0000000000..0c5b0e13e6 --- /dev/null +++ b/spring-boot-testing/src/test/resources/application.properties @@ -0,0 +1,6 @@ +#embedded redis +spring.redis.host= localhost +spring.redis.port= 6370 +# security +spring.security.user.name=john +spring.security.user.password=123 \ No newline at end of file diff --git a/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..16e0708fc9 --- /dev/null +++ b/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot/.attach_pid12812 b/spring-boot/.attach_pid12812 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-boot/README.MD b/spring-boot/README.MD index d7af3f4614..e159220cbc 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -5,7 +5,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [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) - [How to Register a Servlet in Java](http://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](http://www.baeldung.com/spring-webutils-servletrequestutils) - [Using Custom Banners in Spring Boot](http://www.baeldung.com/spring-boot-custom-banners) @@ -30,10 +29,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Shutdown Callbacks](http://www.baeldung.com/spring-shutdown-callbacks) - [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) - [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report) - [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information) - [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) -- [Entity To DTO Conversion for a Spring REST API](https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application) +- [Guide to @EnableConfigurationProperties](https://www.baeldung.com/spring-enable-config-properties) diff --git a/spring-boot/src/main/java/com/baeldung/properties/conversion/Employee.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/Employee.java new file mode 100644 index 0000000000..52c7881dfc --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/Employee.java @@ -0,0 +1,30 @@ +package com.baeldung.properties.conversion; + +public class Employee { + + private String name; + private double salary; + + public Employee(String name, double salary) { + super(); + this.name = name; + this.salary = salary; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java new file mode 100644 index 0000000000..6ec19cae72 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java @@ -0,0 +1,16 @@ +package com.baeldung.properties.conversion; + +import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationPropertiesBinding +public class EmployeeConverter implements Converter { + + @Override + public Employee convert(String from) { + String[] data = from.split(","); + return new Employee(data[0], Double.parseDouble(data[1])); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java new file mode 100644 index 0000000000..f00a26e9c4 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.properties.conversion; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackageClasses = { PropertyConversion.class, EmployeeConverter.class }) +public class PropertiesConversionApplication { + public static void main(String[] args) { + SpringApplication.run(PropertiesConversionApplication.class, args); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java new file mode 100644 index 0000000000..b9c890306f --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java @@ -0,0 +1,92 @@ +package com.baeldung.properties.conversion; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.convert.DataSizeUnit; +import org.springframework.boot.convert.DurationUnit; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.util.unit.DataSize; +import org.springframework.util.unit.DataUnit; + +@Configuration +@PropertySource("classpath:conversion.properties") +@ConfigurationProperties(prefix = "conversion") +public class PropertyConversion { + private Duration timeInDefaultUnit; + + private Duration timeInNano; + + @DurationUnit(ChronoUnit.DAYS) + private Duration timeInDays; + + private DataSize sizeInDefaultUnit; + + private DataSize sizeInGB; + + @DataSizeUnit(DataUnit.TERABYTES) + private DataSize sizeInTB; + + private Employee employee; + + // Getters and setters + + public Duration getTimeInDefaultUnit() { + return timeInDefaultUnit; + } + + public void setTimeInDefaultUnit(Duration timeInDefaultUnit) { + this.timeInDefaultUnit = timeInDefaultUnit; + } + + public Duration getTimeInNano() { + return timeInNano; + } + + public void setTimeInNano(Duration timeInNano) { + this.timeInNano = timeInNano; + } + + public Duration getTimeInDays() { + return timeInDays; + } + + public void setTimeInDays(Duration timeInDays) { + this.timeInDays = timeInDays; + } + + public DataSize getSizeInDefaultUnit() { + return sizeInDefaultUnit; + } + + public void setSizeInDefaultUnit(DataSize sizeInDefaultUnit) { + this.sizeInDefaultUnit = sizeInDefaultUnit; + } + + public DataSize getSizeInGB() { + return sizeInGB; + } + + public void setSizeInGB(DataSize sizeInGB) { + this.sizeInGB = sizeInGB; + } + + public DataSize getSizeInTB() { + return sizeInTB; + } + + public void setSizeInTB(DataSize sizeInTB) { + this.sizeInTB = sizeInTB; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/properties/AdditionalConfiguration.java b/spring-boot/src/main/java/org/baeldung/properties/AdditionalConfiguration.java new file mode 100644 index 0000000000..499666c143 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/AdditionalConfiguration.java @@ -0,0 +1,14 @@ +package org.baeldung.properties; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties(AdditionalProperties.class) +public class AdditionalConfiguration { + + @Autowired + private AdditionalProperties additionalProperties; + +} diff --git a/spring-boot/src/main/java/org/baeldung/properties/AdditionalProperties.java b/spring-boot/src/main/java/org/baeldung/properties/AdditionalProperties.java new file mode 100644 index 0000000000..64e39b1475 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/AdditionalProperties.java @@ -0,0 +1,26 @@ +package org.baeldung.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "additional") +public class AdditionalProperties { + + private String unit; + private int max; + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + public int getMax() { + return max; + } + + public void setMax(int max) { + this.max = max; + } +} 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 395d68060b..7b8f2c3411 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -5,11 +5,14 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class }) +@ComponentScan(basePackageClasses = {ConfigProperties.class, + JsonProperties.class, + CustomJsonProperties.class, + AdditionalConfiguration.class}) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) - .run(); + .run(); } } diff --git a/spring-boot/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java index 3a4b6551b1..8f07b2da35 100644 --- a/spring-boot/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.properties; +import org.baeldung.properties.AdditionalProperties; import org.baeldung.properties.ConfigProperties; import org.baeldung.properties.ConfigPropertiesDemoApplication; import org.junit.Assert; @@ -18,6 +19,9 @@ public class ConfigPropertiesIntegrationTest { @Autowired private ConfigProperties properties; + @Autowired + private AdditionalProperties additionalProperties; + @Test public void whenSimplePropertyQueriedthenReturnsProperty() throws Exception { Assert.assertTrue("From address is read as null!", properties.getFrom() != null); @@ -42,4 +46,10 @@ public class ConfigPropertiesIntegrationTest { Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getUsername().equals("john")); Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getPassword().equals("password")); } + + @Test + public void whenAdditionalPropertyQueriedthenReturnsProperty() { + Assert.assertTrue(additionalProperties.getUnit().equals("km")); + Assert.assertTrue(additionalProperties.getMax() == 100); + } } diff --git a/spring-boot/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java new file mode 100644 index 0000000000..53bad329ea --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java @@ -0,0 +1,46 @@ +package com.baeldung.properties.conversion; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.Duration; + +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; +import org.springframework.util.unit.DataSize; + +import com.baeldung.properties.conversion.PropertiesConversionApplication; +import com.baeldung.properties.conversion.PropertyConversion; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PropertiesConversionApplication.class) +@TestPropertySource("classpath:conversion.properties") +public class PropertiesConversionIntegrationTest { + + @Autowired + private PropertyConversion properties; + + @Test + public void whenUseTimeUnitPropertyConversion_thenSuccess() throws Exception { + assertEquals(Duration.ofMillis(10), properties.getTimeInDefaultUnit()); + assertEquals(Duration.ofNanos(9), properties.getTimeInNano()); + assertEquals(Duration.ofDays(2), properties.getTimeInDays()); + } + + @Test + public void whenUseDataSizePropertyConversion_thenSuccess() throws Exception { + assertEquals(DataSize.ofBytes(300), properties.getSizeInDefaultUnit()); + assertEquals(DataSize.ofGigabytes(2), properties.getSizeInGB()); + assertEquals(DataSize.ofTerabytes(4), properties.getSizeInTB()); + } + + @Test + public void whenUseCustomPropertyConverter_thenSuccess() throws Exception { + assertEquals("john", properties.getEmployee().getName()); + assertEquals(2000.0, properties.getEmployee().getSalary()); + } + +} diff --git a/spring-boot/src/test/resources/configprops-test.properties b/spring-boot/src/test/resources/configprops-test.properties index ea11f2159e..5eed93a22b 100644 --- a/spring-boot/src/test/resources/configprops-test.properties +++ b/spring-boot/src/test/resources/configprops-test.properties @@ -20,3 +20,7 @@ mail.credentials.authMethod=SHA1 #Bean method properties item.name=Test item name item.size=21 + +#Additional properties +additional.unit=km +additional.max=100 diff --git a/spring-boot/src/test/resources/conversion.properties b/spring-boot/src/test/resources/conversion.properties new file mode 100644 index 0000000000..640442ec33 --- /dev/null +++ b/spring-boot/src/test/resources/conversion.properties @@ -0,0 +1,11 @@ +###### time unit +conversion.timeInDefaultUnit=10 +conversion.timeInNano=9ns +conversion.timeInDays=2 + +###### data size +conversion.sizeInDefaultUnit=300 +conversion.sizeInGB=2GB +conversion.sizeInTB=4 + +conversion.employee=john,2000 \ No newline at end of file diff --git a/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a5ab1342a1 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextTest.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.SpringCloudConfigClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudConfigClientApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..19ca53c4a7 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3ac11452d3 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..83cb8067cf --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c456f69979 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..42903189d3 --- /dev/null +++ b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d090e626d2 --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e19b88de90 --- /dev/null +++ b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java new file mode 100644 index 0000000000..7e38329f88 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.archaius.additionalsources; + +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 = AdditionalSourcesSimpleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..818e313c98 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.archaius.basic; + +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 SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java new file mode 100644 index 0000000000..e88ec436c6 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.archaius.basic; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7674713ff8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a03bd8c23b --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java new file mode 100644 index 0000000000..5d3bc8e741 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig; + +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 = JdbcSourcesApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-aws/.attach_pid23938 b/spring-cloud/spring-cloud-aws/.attach_pid23938 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..98ae3e4895 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml index 4f9c60a26a..6cbaa5ac2d 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml @@ -97,6 +97,7 @@ + Dalston.RELEASE diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..dc635cd003 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.bootstrap.gateway; + +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 SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextTest.java new file mode 100644 index 0000000000..a2d1cd1087 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.bootstrap.gateway; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..76b7539b6b --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @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 c55f9bc471..14b0d2f9b1 100644 --- a/spring-cloud/spring-cloud-config/client/pom.xml +++ b/spring-cloud/spring-cloud-config/client/pom.xml @@ -20,8 +20,7 @@ org.springframework.boot spring-boot-starter-web - - + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-config/server/pom.xml b/spring-cloud/spring-cloud-config/server/pom.xml index b4be7663e2..674749a48d 100644 --- a/spring-cloud/spring-cloud-config/server/pom.xml +++ b/spring-cloud/spring-cloud-config/server/pom.xml @@ -24,8 +24,7 @@ org.springframework.boot spring-boot-starter-web - - + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java b/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java new file mode 100644 index 0000000000..d879737553 --- /dev/null +++ b/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.config.server; + +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; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = ConfigServer.class) +@WebAppConfiguration +public class SpringContextTest { + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/test/java/com/baeldung/spring/cloud/connectors/heroku/SpringContextTest.java b/spring-cloud/spring-cloud-connectors-heroku/src/test/java/com/baeldung/spring/cloud/connectors/heroku/SpringContextTest.java new file mode 100644 index 0000000000..c6066027f5 --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/test/java/com/baeldung/spring/cloud/connectors/heroku/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.cloud.connectors.heroku; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/pom.xml b/spring-cloud/spring-cloud-contract/pom.xml index ea71891648..a7ee52e954 100644 --- a/spring-cloud/spring-cloud-contract/pom.xml +++ b/spring-cloud/spring-cloud-contract/pom.xml @@ -56,7 +56,6 @@ UTF-8 UTF-8 - 1.8 2.1.1.RELEASE 2.1.4.RELEASE diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e9098b1467 --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml index dffbd29206..7a0fa7db10 100644 --- a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml @@ -31,6 +31,7 @@ spring-boot-starter-data-rest + diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7d77cbbd7a --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-eureka/pom.xml b/spring-cloud/spring-cloud-eureka/pom.xml index e8e3d67805..5afb006d41 100644 --- a/spring-cloud/spring-cloud-eureka/pom.xml +++ b/spring-cloud/spring-cloud-eureka/pom.xml @@ -9,18 +9,18 @@ Spring Cloud Eureka Server and Sample Clients pom - - spring-cloud-eureka-server - spring-cloud-eureka-client - spring-cloud-eureka-feign-client - - com.baeldung.spring.cloud spring-cloud 1.0.0-SNAPSHOT .. + + + spring-cloud-eureka-server + spring-cloud-eureka-client + spring-cloud-eureka-feign-client + diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java new file mode 100644 index 0000000000..a3ed012abb --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.client; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/test/java/com/baeldung/spring/cloud/feign/client/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/test/java/com/baeldung/spring/cloud/feign/client/SpringContextTest.java new file mode 100644 index 0000000000..ac8150defa --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/test/java/com/baeldung/spring/cloud/feign/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.feign.client; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java new file mode 100644 index 0000000000..e7996bd316 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.server; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml index 7a44e4ae0f..82147cea28 100644 --- a/spring-cloud/spring-cloud-functions/pom.xml +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -29,7 +29,7 @@ org.springframework.cloud spring-cloud-starter-function-web - 1.0.1.RELEASE + ${spring-cloud-function.version} com.amazonaws @@ -40,7 +40,7 @@ com.amazonaws aws-lambda-java-core - 1.1.0 + ${aws-lambda-java-core.version} provided @@ -87,6 +87,7 @@ UTF-8 1.0.1.RELEASE 2.0.2 + 1.1.0 2.0.4.RELEASE diff --git a/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/SpringContextTest.java b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/SpringContextTest.java new file mode 100644 index 0000000000..67411ebd4a --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloudfunction.aws; + +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 = CloudFunctionAwsApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b7e2acf7a8 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java new file mode 100644 index 0000000000..d5f8180f20 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +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 = RestConsumerFeignApplication.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java new file mode 100644 index 0000000000..d3260a4517 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +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 = RestConsumerApplication.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/producer/SpringContextTest.java b/spring-cloud/spring-cloud-hystrix/rest-producer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/producer/SpringContextTest.java new file mode 100644 index 0000000000..bd871fc1da --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/producer/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.hystrix.rest.producer; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/client-service/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/client-service/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..af59614f7c --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/client-service/src/test/java/org/baeldung/SpringContextTest.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.kubernetes.client.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..af393cb697 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextTest.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.backend.KubernetesBackendApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KubernetesBackendApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..17cb5a5f39 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7c605567d8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.liveness.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 SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..59802d220a --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.readiness.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 SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/travel-agency-service/src/test/java/com/baeldung/spring/cloud/kubernetes/travelagency/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/travel-agency-service/src/test/java/com/baeldung/spring/cloud/kubernetes/travelagency/SpringContextTest.java new file mode 100644 index 0000000000..6e7f99fb0d --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/travel-agency-service/src/test/java/com/baeldung/spring/cloud/kubernetes/travelagency/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.kubernetes.travelagency; + + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml index 002a333749..92de33572b 100644 --- a/spring-cloud/spring-cloud-openfeign/pom.xml +++ b/spring-cloud/spring-cloud-openfeign/pom.xml @@ -9,7 +9,6 @@ openfeign OpenFeign project for Spring Boot - parent-boot-2 com.baeldung @@ -17,12 +16,6 @@ ../../parent-boot-2 - - 2.0.1.RELEASE - Finchley.SR2 - - - org.springframework.cloud @@ -58,4 +51,9 @@ + + 2.0.1.RELEASE + Finchley.SR2 + + diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java new file mode 100644 index 0000000000..4bf35f74f4 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.cloud.openfeign; + + +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 = ExampleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1b4083e7a6 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.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 = SpringCloudRestConfigApplication.class) +public class SpringContextTest { + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..23dbcf8ff6 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index 4f64f470f0..c414e584e5 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -13,6 +13,18 @@ 1.0.0-SNAPSHOT + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + org.springframework.boot @@ -24,7 +36,7 @@ org.springframework.cloud - spring-cloud-starter-zuul + spring-cloud-starter-netflix-zuul org.springframework.boot @@ -34,14 +46,16 @@ org.webjars jquery + ${jquery.version} org.webjars bootstrap + ${bootstrap.version} org.webjars - webjars-locator + webjars-locator-core org.springframework.boot @@ -62,8 +76,8 @@ spring-boot-starter-thymeleaf - org.springframework.security.oauth - spring-security-oauth2 + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure @@ -76,21 +90,11 @@ - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - 2.1.0 - Dalston.SR4 + 2.2.0 + Greenwich.SR1 + 3.4.1 + 4.3.1 diff --git a/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.properties b/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.properties deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml index 2a758faeae..69617555d9 100644 --- a/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml @@ -2,7 +2,8 @@ # These are default settings, but we add them for clarity. server: port: 8080 - contextPath: / + servlet: + context-path: / # Configure the Authorization Server and User Info Resource Server details security: @@ -21,6 +22,7 @@ person: # Proxies the calls to http://localhost:8080/api/* to our REST service at http://localhost:8081/* # and automatically includes our OAuth2 token in the request headers zuul: + sensitiveHeaders: Cookie,Set-Cookie routes: resource: path: /api/** diff --git a/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..02c429acf5 --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.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.CloudSite; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CloudSite.class) +public class SpringContextTest { + + @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 22ee0528c3..a60eca740c 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -19,8 +19,8 @@ spring-boot-starter-web - org.springframework.security.oauth - spring-security-oauth2 + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure org.springframework.boot @@ -30,6 +30,7 @@ org.springframework.security spring-security-jwt + ${spring-jwt.version} @@ -55,7 +56,8 @@ - Edgware.RELEASE + Greenwich.SR1 + 1.0.10.RELEASE diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/config/ResourceConfigurer.java b/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/config/ResourceConfigurer.java index 977d74093a..abe942325f 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/config/ResourceConfigurer.java +++ b/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/config/ResourceConfigurer.java @@ -3,7 +3,7 @@ package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; @@ -11,15 +11,18 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.R * REST API Resource Server. */ @Configuration -@EnableWebSecurity @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true) // Allow method annotations like @PreAuthorize public class ResourceConfigurer extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { - http.httpBasic().disable(); - http.authorizeRequests().anyRequest().authenticated(); + http.sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.NEVER) + .and() + .authorizeRequests() + .anyRequest().authenticated(); + } } diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml b/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml index 52e02ba41b..35063a7879 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml @@ -5,7 +5,6 @@ server: # Configure the public key to use for verifying the incoming JWT tokens security: - sessions: NEVER oauth2: resource: jwt: diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a061928bf5 --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @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 4b3f94b825..afd8dbef44 100644 --- a/spring-cloud/spring-cloud-security/auth-server/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-server/pom.xml @@ -38,7 +38,7 @@ - 1.1.2.RELEASE + 2.1.2.RELEASE \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/AuthServerConfigurer.java b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/AuthServerConfigurer.java index 32e445f998..7c9ee9ae18 100644 --- a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/AuthServerConfigurer.java +++ b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/AuthServerConfigurer.java @@ -9,6 +9,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.core.io.Resource; import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 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; @@ -19,9 +20,7 @@ import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFacto @Configuration @EnableAuthorizationServer @Order(6) -public class AuthServerConfigurer - extends - AuthorizationServerConfigurerAdapter { +public class AuthServerConfigurer extends AuthorizationServerConfigurerAdapter { @Value("${jwt.certificate.store.file}") private Resource keystore; @@ -37,6 +36,9 @@ public class AuthServerConfigurer @Autowired private UserDetailsService userDetailsService; + + @Autowired + private BCryptPasswordEncoder passwordEncoder; @Override public void configure( @@ -45,8 +47,8 @@ public class AuthServerConfigurer clients .inMemory() .withClient("authserver") - .secret("passwordforauthserver") - .redirectUris("http://localhost:8080/") + .secret(passwordEncoder.encode("passwordforauthserver")) + .redirectUris("http://localhost:8080/login") .authorizedGrantTypes("authorization_code", "refresh_token") .scopes("myscope") diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfigurer.java b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfig.java similarity index 83% rename from spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfigurer.java rename to spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfig.java index 23b56151e7..3cefd323b3 100644 --- a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfigurer.java +++ b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfig.java @@ -2,10 +2,10 @@ package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration -public class WebMvcConfigurer extends WebMvcConfigurerAdapter { +public class WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebSecurityConfigurer.java b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebSecurityConfigurer.java index 44406b8fa0..6a48c62097 100644 --- a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebSecurityConfigurer.java +++ b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebSecurityConfigurer.java @@ -6,8 +6,8 @@ import org.springframework.security.config.annotation.authentication.builders.Au import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; @Configuration @@ -34,7 +34,7 @@ public class WebSecurityConfigurer AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() - .withUser("user").password("user") + .withUser("user").password(passwordEncoder().encode("user")) .roles("USER") .and() .withUser("admin").password("admin") @@ -48,5 +48,9 @@ public class WebSecurityConfigurer return super.userDetailsServiceBean(); } + @Bean + public BCryptPasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/resources/application.yml b/spring-cloud/spring-cloud-security/auth-server/src/main/resources/application.yml index 1dc63d3f0e..b6e385e5c7 100644 --- a/spring-cloud/spring-cloud-security/auth-server/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-security/auth-server/src/main/resources/application.yml @@ -1,7 +1,8 @@ # Make the application available at http://localhost:7070/authserver server: port: 7070 - contextPath: /authserver + servlet: + context-path: /authserver # Our certificate settings for enabling JWT tokens jwt: @@ -11,11 +12,4 @@ jwt: password: abirkhan04 key: alias: myauthkey - password: abirkhan04 - - -security: - oauth2: - resource: - filter-order: 3 - \ No newline at end of file + password: abirkhan04 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..aec56a574c --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.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.AuthServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AuthServer.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-security/pom.xml b/spring-cloud/spring-cloud-security/pom.xml index 2eecf579a5..d65fd6520b 100644 --- a/spring-cloud/spring-cloud-security/pom.xml +++ b/spring-cloud/spring-cloud-security/pom.xml @@ -8,10 +8,10 @@ pom - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 diff --git a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/com/baeldung/twitterhdfs/aggregate/SpringContextTest.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/com/baeldung/twitterhdfs/aggregate/SpringContextTest.java new file mode 100644 index 0000000000..d78a18d557 --- /dev/null +++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/com/baeldung/twitterhdfs/aggregate/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.twitterhdfs.aggregate; + +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 = AggregateApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml new file mode 100644 index 0000000000..13ad18810e --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml @@ -0,0 +1,109 @@ + + 4.0.0 + + + spring-cloud-stream-kafka + spring-cloud-stream-kafka + Simple Spring Cloud Stream + jar + + + org.springframework.boot + spring-boot-starter-parent + 2.1.5.RELEASE + + + + 1.8 + Greenwich.SR1 + + + + + + org.springframework.cloud + spring-cloud-stream-binder-kafka + + + + org.springframework.cloud + spring-cloud-stream-schema + + + + org.springframework.cloud + spring-cloud-stream-test-support + test + + + + io.confluent + kafka-avro-serializer + 4.0.0 + + + + org.apache.avro + avro-compiler + 1.8.2 + + + + org.apache.avro + avro-maven-plugin + 1.8.2 + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.avro + avro-maven-plugin + 1.8.2 + + + schemas + generate-sources + + schema + protocol + idl-protocol + + + ${project.basedir}/src/main/resources/ + ${project.basedir}/src/main/java/ + + + + + + + + + + confluent + https://packages.confluent.io/maven/ + + + + diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/AvroKafkaApplication.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/AvroKafkaApplication.java new file mode 100644 index 0000000000..47c060c143 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/AvroKafkaApplication.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.cloud.stream.schema.client.EnableSchemaRegistryClient; + +@SpringBootApplication +@EnableBinding(Processor.class) +@EnableSchemaRegistryClient +public class AvroKafkaApplication { + + public static void main(String[] args) { + SpringApplication.run(AvroKafkaApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/config/SchemRegistryConfig.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/config/SchemRegistryConfig.java new file mode 100644 index 0000000000..38ac94d952 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/config/SchemRegistryConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.stream.schema.client.ConfluentSchemaRegistryClient; +import org.springframework.cloud.stream.schema.client.SchemaRegistryClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SchemRegistryConfig { + + @Bean + public SchemaRegistryClient schemaRegistryClient(@Value("${spring.cloud.stream.kafka.binder.producer-properties.schema.registry.url}") String endPoint) { + ConfluentSchemaRegistryClient client = new ConfluentSchemaRegistryClient(); + client.setEndpoint(endPoint); + return client; + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/consumer/AvroConsumer.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/consumer/AvroConsumer.java new file mode 100644 index 0000000000..477946dd73 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/consumer/AvroConsumer.java @@ -0,0 +1,21 @@ +package com.baeldung.consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.stream.annotation.StreamListener; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.stereotype.Service; + +import com.baeldung.schema.Employee; + +@Service +public class AvroConsumer { + + private static final Logger LOGGER = LoggerFactory.getLogger(AvroConsumer.class); + + @StreamListener(Processor.INPUT) + public void consumeEmployeeDetails(Employee employeeDetails) { + LOGGER.info("Let's process employee details: {}", employeeDetails); + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/controller/AvroController.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/controller/AvroController.java new file mode 100644 index 0000000000..b98b27c9fe --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/controller/AvroController.java @@ -0,0 +1,22 @@ +package com.baeldung.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.producer.AvroProducer; + +@RestController +public class AvroController { + + @Autowired + private AvroProducer avroProducer; + + @PostMapping("/employees/{id}/{firstName}/{lastName}") + public String producerAvroMessage(@PathVariable int id, @PathVariable String firstName, @PathVariable String lastName) { + avroProducer.produceEmployeeDetails(id, firstName, lastName); + return "Sent employee details to consumer"; + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/producer/AvroProducer.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/producer/AvroProducer.java new file mode 100644 index 0000000000..ff7729dd8c --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/producer/AvroProducer.java @@ -0,0 +1,42 @@ +package com.baeldung.producer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.stereotype.Service; + +import com.baeldung.schema.Employee; +import com.baeldung.schema.EmployeeKey; + +@Service +public class AvroProducer { + + @Autowired + private Processor processor; + + public void produceEmployeeDetails(int empId, String firstName, String lastName) { + + // creating employee details + Employee employee = new Employee(); + employee.setId(empId); + employee.setFirstName(firstName); + employee.setLastName(lastName); + employee.setDepartment("IT"); + employee.setDesignation("Engineer"); + + // creating partition key for kafka topic + EmployeeKey employeeKey = new EmployeeKey(); + employeeKey.setId(empId); + employeeKey.setDepartmentName("IT"); + + Message message = MessageBuilder.withPayload(employee) + .setHeader(KafkaHeaders.MESSAGE_KEY, employeeKey) + .build(); + + processor.output() + .send(message); + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/application.yaml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/application.yaml new file mode 100644 index 0000000000..2e30c07374 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/application.yaml @@ -0,0 +1,29 @@ +spring: + cloud: + stream: + default: + producer: + useNativeEncoding: true + consumer: + useNativeEncoding: true + bindings: + input: + destination: employee-details + content-type: application/*+avro + group: group-1 + concurrency: 3 + output: + destination: employee-details + content-type: application/*+avro + kafka: + binder: + producer-properties: + key.serializer: io.confluent.kafka.serializers.KafkaAvroSerializer + value.serializer: io.confluent.kafka.serializers.KafkaAvroSerializer + schema.registry.url: http://localhost:8081 + consumer-properties: + key.deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer + value.deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer + schema.registry.url: http://localhost:8081 + specific.avro.reader: true + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-key-schema.avsc b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-key-schema.avsc new file mode 100644 index 0000000000..d18d657e99 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-key-schema.avsc @@ -0,0 +1,14 @@ +{ + "type": "record", + "name": "EmployeeKey", + "namespace": "com.baeldung.schema", + "fields": [ + { + "name": "id", + "type": "int" + }, + { + "name": "departmentName", + "type": "string" + }] +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-schema.avsc b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-schema.avsc new file mode 100644 index 0000000000..2abf57e4a2 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-schema.avsc @@ -0,0 +1,29 @@ +{ + "type": "record", + "name": "Employee", + "namespace": "com.baeldung.schema", + "fields": [ + { + "name": "id", + "type": "int" + }, + { + "name": "firstName", + "type": "string" + }, + { + "name": "lastName", + "type": "string" + }, + { + "name": "department", + "type": "string", + "default": "IT " + }, + { + "name": "designation", + "type": "string", + "default": "Software Engineer" + } + ] +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0f3b8de901 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..51f0926429 --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextTest.java b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextTest.java new file mode 100644 index 0000000000..73fcbe55f0 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung.spring.cloud.vaultsample; + +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 = VaultSampleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b45e7b9889 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/test/java/com/baeldung/spring/cloud/helloworld/SpringContextTest.java b/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/test/java/com/baeldung/spring/cloud/helloworld/SpringContextTest.java new file mode 100644 index 0000000000..df7335dfa6 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/test/java/com/baeldung/spring/cloud/helloworld/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.helloworld; + + +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 = HelloWorldApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java new file mode 100644 index 0000000000..9e3680b244 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.client; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java new file mode 100644 index 0000000000..e7996bd316 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.server; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/test/java/com/baeldung/spring/cloud/zuul/config/SpringContextTest.java b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/test/java/com/baeldung/spring/cloud/zuul/config/SpringContextTest.java new file mode 100644 index 0000000000..a5350655fb --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/test/java/com/baeldung/spring/cloud/zuul/config/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.zuul.config; + +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul/src/test/java/com/baeldung/spring/cloud/zuulratelimitdemo/controller/SpringContextTest.java b/spring-cloud/spring-cloud-zuul/src/test/java/com/baeldung/spring/cloud/zuulratelimitdemo/controller/SpringContextTest.java new file mode 100644 index 0000000000..b5ddf6f65c --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/src/test/java/com/baeldung/spring/cloud/zuulratelimitdemo/controller/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.cloud.zuulratelimitdemo.controller; + +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.zuulratelimitdemo.ZuulRatelimitDemoApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ZuulRatelimitDemoApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml new file mode 100644 index 0000000000..20cd900e00 --- /dev/null +++ b/spring-core-2/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + spring-core-2 + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + + + + + 5.1.4.RELEASE + + + \ No newline at end of file diff --git a/spring-core-2/src/main/java/com/baeldung/getbean/AnnotationConfig.java b/spring-core-2/src/main/java/com/baeldung/getbean/AnnotationConfig.java new file mode 100644 index 0000000000..12e3ab55e3 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/getbean/AnnotationConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.getbean; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; + +@Configuration +class AnnotationConfig { + + @Bean(name = {"tiger", "kitty"}) + @Scope(value = "prototype") + Tiger getTiger(String name) { + return new Tiger(name); + } + + @Bean(name = "lion") + Lion getLion() { + return new Lion("Hardcoded lion name"); + } + + interface Animal {} +} diff --git a/spring-core-2/src/main/java/com/baeldung/getbean/Lion.java b/spring-core-2/src/main/java/com/baeldung/getbean/Lion.java new file mode 100644 index 0000000000..96c569aeb9 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/getbean/Lion.java @@ -0,0 +1,13 @@ +package com.baeldung.getbean; + +class Lion implements AnnotationConfig.Animal { + private String name; + + Lion(String name) { + this.name = name; + } + + String getName() { + return name; + } +} diff --git a/spring-core-2/src/main/java/com/baeldung/getbean/Tiger.java b/spring-core-2/src/main/java/com/baeldung/getbean/Tiger.java new file mode 100644 index 0000000000..85b9626c79 --- /dev/null +++ b/spring-core-2/src/main/java/com/baeldung/getbean/Tiger.java @@ -0,0 +1,13 @@ +package com.baeldung.getbean; + +class Tiger implements AnnotationConfig.Animal { + private String name; + + Tiger(String name) { + this.name = name; + } + + String getName() { + return name; + } +} diff --git a/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java new file mode 100644 index 0000000000..e06804c28e --- /dev/null +++ b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.getbean; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.BeanNotOfRequiredTypeException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class GetBeanByNameAndTypeUnitTest { + private ApplicationContext context; + + @BeforeAll + void setup() { + context = new AnnotationConfigApplicationContext(AnnotationConfig.class); + } + + @Test + void whenSpecifiedMatchingNameAndType_thenShouldReturnRelatedBean() { + Lion lion = context.getBean("lion", Lion.class); + + assertEquals("Hardcoded lion name", lion.getName()); + } + + @Test + void whenSpecifiedNotMatchingNameAndType_thenShouldThrowException() { + assertThrows(BeanNotOfRequiredTypeException.class, () -> context.getBean("lion", Tiger.class)); + } +} diff --git a/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java new file mode 100644 index 0000000000..4d6d77e39d --- /dev/null +++ b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.getbean; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class GetBeanByNameUnitTest { + private ApplicationContext context; + + @BeforeAll + void setup() { + context = new AnnotationConfigApplicationContext(AnnotationConfig.class); + } + + @Test + void whenGivenExistingBeanName_shouldReturnThatBean() { + Object lion = context.getBean("lion"); + + assertEquals(lion.getClass(), Lion.class); + } + + @Test + void whenGivenNonExistingBeanName_shouldThrowException() { + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean("non-existing")); + } + + @Test + void whenCastingToWrongType_thenShouldThrowException() { + assertThrows(ClassCastException.class, () -> { + Tiger tiger = (Tiger) context.getBean("lion"); + }); + } +} diff --git a/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java new file mode 100644 index 0000000000..32d37e4ff2 --- /dev/null +++ b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.getbean; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.UnsatisfiedDependencyException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class GetBeanByNameWithConstructorParametersUnitTest { + private ApplicationContext context; + + @BeforeAll + void setup() { + context = new AnnotationConfigApplicationContext(AnnotationConfig.class); + } + + @Test + void whenGivenCorrectName_thenShouldReturnBeanWithSpecifiedName() { + Tiger tiger = (Tiger) context.getBean("tiger", "Siberian"); + + assertEquals("Siberian", tiger.getName()); + } + + @Test + void whenGivenCorrectNameOrAlias_shouldReturnBeanWithSpecifiedName() { + Tiger tiger = (Tiger) context.getBean("tiger", "Siberian"); + Tiger secondTiger = (Tiger) context.getBean("tiger", "Striped"); + + assertEquals("Siberian", tiger.getName()); + assertEquals("Striped", secondTiger.getName()); + } + + @Test + void whenNoArgumentSpecifiedForPrototypeBean_thenShouldThrowException() { + assertThrows(UnsatisfiedDependencyException.class, () -> { + Tiger tiger = (Tiger) context.getBean("tiger"); + }); + } +} diff --git a/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java new file mode 100644 index 0000000000..a4d4ab732b --- /dev/null +++ b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.getbean; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.NoUniqueBeanDefinitionException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class GetBeanByTypeUnitTest { + private ApplicationContext context; + + @BeforeAll + void setup() { + context = new AnnotationConfigApplicationContext(AnnotationConfig.class); + } + + @Test + void whenGivenExistingUniqueType_thenShouldReturnRelatedBean() { + Lion lion = context.getBean(Lion.class); + + assertNotNull(lion); + } + + @Test + void whenGivenAmbiguousType_thenShouldThrowException() { + assertThrows(NoUniqueBeanDefinitionException.class, () -> context.getBean(AnnotationConfig.Animal.class)); + } +} diff --git a/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java new file mode 100644 index 0000000000..08bcb92145 --- /dev/null +++ b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.getbean; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class GetBeanByTypeWithConstructorParametersUnitTest { + private ApplicationContext context; + + @BeforeAll + void setup() { + context = new AnnotationConfigApplicationContext(AnnotationConfig.class); + } + + @Test + void whenGivenExistingTypeAndValidParameters_thenShouldReturnRelatedBean() { + Tiger tiger = context.getBean(Tiger.class, "Shere Khan"); + + assertEquals("Shere Khan", tiger.getName()); + } +} diff --git a/spring-core/README.md b/spring-core/README.md index d542fa8ed1..18d14b7ecf 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -8,7 +8,6 @@ - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) - [Introduction to Spring’s StreamUtils](http://www.baeldung.com/spring-stream-utils) - [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) -- [Groovy Bean Definitions](http://www.baeldung.com/spring-groovy-beans) - [XML-Based Injection in Spring](http://www.baeldung.com/spring-xml-injection) - [A Quick Guide to the Spring @Lazy Annotation](http://www.baeldung.com/spring-lazy-annotation) - [Injecting Prototype Beans into a Singleton Instance in Spring](http://www.baeldung.com/spring-inject-prototype-bean-into-singleton) @@ -24,3 +23,4 @@ - [What is a Spring Bean?](https://www.baeldung.com/spring-bean) - [Spring PostConstruct and PreDestroy Annotations](https://www.baeldung.com/spring-postconstruct-predestroy) - [Guice vs Spring – Dependency Injection](https://www.baeldung.com/guice-spring-dependency-injection) +- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 814addecdd..7e5a9b3feb 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -56,6 +56,12 @@ spring-boot-test ${mockito.spring.boot.version} test + + + org.assertj + assertj-core + ${assertj.version} + test commons-io @@ -81,10 +87,10 @@ 1.4.4.RELEASE 1 20.0 - 2.6 2.5 1.5.2.RELEASE 1.10.19 + 3.12.2 \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java b/spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java rename to spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java b/spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java rename to spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java diff --git a/spring-core/src/main/resources/constructordi.xml b/spring-core/src/main/resources/constructordi.xml index 231e72adcb..983a00a80f 100644 --- a/spring-core/src/main/resources/constructordi.xml +++ b/spring-core/src/main/resources/constructordi.xml @@ -1,19 +1,21 @@ + https://www.springframework.org/schema/beans/spring-beans.xsd"> - + - + diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java b/spring-core/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig.java b/spring-core/src/test/java/com/baeldung/circulardependency/TestConfig.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig.java rename to spring-core/src/test/java/com/baeldung/circulardependency/TestConfig.java diff --git a/spring-core/src/test/java/com/baeldung/constructordi/ConstructorDependencyInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/constructordi/ConstructorDependencyInjectionIntegrationTest.java new file mode 100644 index 0000000000..7bd0ad0c86 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/constructordi/ConstructorDependencyInjectionIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.constructordi; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.constructordi.domain.Car; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = Config.class) +public class ConstructorDependencyInjectionIntegrationTest { + + @Test + public void givenPrototypeInjection_WhenObjectFactory_ThenNewInstanceReturn() { + ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); + Car firstContextCar = context.getBean(Car.class); + + ApplicationContext xmlContext = new ClassPathXmlApplicationContext("constructordi.xml"); + Car secondContextCar = xmlContext.getBean(Car.class); + + assertThat(firstContextCar).isNotSameAs(secondContextCar); + assertThat(firstContextCar).hasToString("Engine: v8 5 Transmission: sliding"); + assertThat(secondContextCar).hasToString("Engine: v4 2 Transmission: sliding"); + } + +} diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java index a7a2a9032a..c7a2984045 100644 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.File; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -77,7 +78,7 @@ public class SpringResourceIntegrationTest { @Test public void whenResourceUtils_thenReadSuccessful() throws IOException { - final File employeeFile = ResourceUtils.getFile("classpath:data/employees.dat"); + final File employeeFile = loadEmployeesWithSpringInternalClass(); final String employees = new String(Files.readAllBytes(employeeFile.toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); } @@ -112,4 +113,8 @@ public class SpringResourceIntegrationTest { final String employees = new String(Files.readAllBytes(resource.toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); } + + public File loadEmployeesWithSpringInternalClass() throws FileNotFoundException { + return ResourceUtils.getFile("classpath:data/employees.dat"); + } } diff --git a/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java b/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7b8fa74fc9 --- /dev/null +++ b/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextTest.java b/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java b/spring-data-rest/src/main/java/com/baeldung/books/SpringDataRestApplication.java similarity index 91% rename from spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java rename to spring-data-rest/src/main/java/com/baeldung/books/SpringDataRestApplication.java index 702acb5b65..097a6aabd7 100644 --- a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/SpringDataRestApplication.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.books; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java b/spring-data-rest/src/main/java/com/baeldung/books/config/DbConfig.java similarity index 94% rename from spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java rename to spring-data-rest/src/main/java/com/baeldung/books/config/DbConfig.java index 3ca728ec94..20008eb583 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/config/DbConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.books.config; import java.util.Properties; @@ -16,7 +16,7 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; @Configuration -@EnableJpaRepositories(basePackages = "com.baeldung.repositories") +@EnableJpaRepositories(basePackages = "com.baeldung.books.repositories") // @PropertySource("persistence-h2.properties") // @PropertySource("persistence-hsqldb.properties") // @PropertySource("persistence-derby.properties") @@ -40,7 +40,7 @@ public class DbConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.models" }); + em.setPackagesToScan(new String[] { "com.baeldung.books.models" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java b/spring-data-rest/src/main/java/com/baeldung/books/config/MvcConfig.java similarity index 85% rename from spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java rename to spring-data-rest/src/main/java/com/baeldung/books/config/MvcConfig.java index 9d0d3a6687..69e984ad06 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/config/MvcConfig.java @@ -1,13 +1,14 @@ -package com.baeldung.config; +package com.baeldung.books.config; -import com.baeldung.events.AuthorEventHandler; -import com.baeldung.events.BookEventHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import com.baeldung.books.events.AuthorEventHandler; +import com.baeldung.books.events.BookEventHandler; + @Configuration @EnableWebMvc public class MvcConfig implements WebMvcConfigurer { diff --git a/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java b/spring-data-rest/src/main/java/com/baeldung/books/config/RestConfig.java similarity index 86% rename from spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java rename to spring-data-rest/src/main/java/com/baeldung/books/config/RestConfig.java index 47cb95693b..1c6f04331e 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/config/RestConfig.java @@ -1,7 +1,8 @@ -package com.baeldung.config; +package com.baeldung.books.config; + +import com.baeldung.books.models.WebsiteUser; +import com.baeldung.books.projections.CustomBook; -import com.baeldung.models.WebsiteUser; -import com.baeldung.projections.CustomBook; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.core.mapping.ExposureConfiguration; diff --git a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java b/spring-data-rest/src/main/java/com/baeldung/books/config/ValidatorEventRegister.java similarity index 94% rename from spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java rename to spring-data-rest/src/main/java/com/baeldung/books/config/ValidatorEventRegister.java index 632ad9183a..bbaf9a2771 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/config/ValidatorEventRegister.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.books.config; import java.util.Arrays; import java.util.List; diff --git a/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteDialect.java b/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java similarity index 98% rename from spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteDialect.java rename to spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java index 4512f7d34d..6e840eec43 100644 --- a/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteDialect.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java @@ -1,4 +1,4 @@ -package com.baeldung.dialect; +package com.baeldung.books.dialect; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.identity.IdentityColumnSupport; diff --git a/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteIdentityColumnSupport.java b/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java similarity index 94% rename from spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteIdentityColumnSupport.java rename to spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java index cf6e3a9a97..682d82c6f1 100644 --- a/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteIdentityColumnSupport.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java @@ -1,4 +1,4 @@ -package com.baeldung.dialect; +package com.baeldung.books.dialect; import org.hibernate.MappingException; import org.hibernate.dialect.identity.IdentityColumnSupportImpl; diff --git a/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java b/spring-data-rest/src/main/java/com/baeldung/books/events/AuthorEventHandler.java similarity index 89% rename from spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java rename to spring-data-rest/src/main/java/com/baeldung/books/events/AuthorEventHandler.java index 485dc8e221..b390a529ba 100644 --- a/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/events/AuthorEventHandler.java @@ -1,9 +1,10 @@ -package com.baeldung.events; +package com.baeldung.books.events; -import com.baeldung.models.Author; -import com.baeldung.models.Book; import org.springframework.data.rest.core.annotation.*; +import com.baeldung.books.models.Author; +import com.baeldung.books.models.Book; + import java.util.logging.Logger; @RepositoryEventHandler diff --git a/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java b/spring-data-rest/src/main/java/com/baeldung/books/events/BookEventHandler.java similarity index 86% rename from spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java rename to spring-data-rest/src/main/java/com/baeldung/books/events/BookEventHandler.java index 36ae62b926..0afb3a6279 100644 --- a/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/events/BookEventHandler.java @@ -1,13 +1,15 @@ -package com.baeldung.events; +package com.baeldung.books.events; import java.util.logging.Logger; -import com.baeldung.models.Author; -import com.baeldung.models.Book; + import org.apache.commons.logging.Log; import org.springframework.data.rest.core.annotation.HandleAfterDelete; import org.springframework.data.rest.core.annotation.HandleBeforeCreate; import org.springframework.data.rest.core.annotation.RepositoryEventHandler; +import com.baeldung.books.models.Author; +import com.baeldung.books.models.Book; + @RepositoryEventHandler public class BookEventHandler { Logger logger = Logger.getLogger("Class BookEventHandler"); diff --git a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java b/spring-data-rest/src/main/java/com/baeldung/books/exception/handlers/RestResponseEntityExceptionHandler.java similarity index 94% rename from spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java rename to spring-data-rest/src/main/java/com/baeldung/books/exception/handlers/RestResponseEntityExceptionHandler.java index a3ef91f6d6..4a961e5250 100644 --- a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/exception/handlers/RestResponseEntityExceptionHandler.java @@ -1,4 +1,4 @@ -package com.baeldung.exception.handlers; +package com.baeldung.books.exception.handlers; import org.springframework.data.rest.core.RepositoryConstraintViolationException; import org.springframework.http.HttpHeaders; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Address.java b/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java similarity index 96% rename from spring-data-rest/src/main/java/com/baeldung/models/Address.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/Address.java index 713af58ae6..3c36db0f3c 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Address.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Author.java b/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java similarity index 97% rename from spring-data-rest/src/main/java/com/baeldung/models/Author.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/Author.java index 3f43af9c47..aec2e62ebf 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Author.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import java.util.List; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Book.java b/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java similarity index 97% rename from spring-data-rest/src/main/java/com/baeldung/models/Book.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/Book.java index 07b0d08b84..7451b04b3b 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Book.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import java.util.List; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Library.java b/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java similarity index 97% rename from spring-data-rest/src/main/java/com/baeldung/models/Library.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/Library.java index 091975f5d0..5f95169a9b 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Library.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import java.util.List; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Subject.java b/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java similarity index 94% rename from spring-data-rest/src/main/java/com/baeldung/models/Subject.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java index 4e5fa82148..11a4425fdd 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Subject.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java b/spring-data-rest/src/main/java/com/baeldung/books/models/WebsiteUser.java similarity index 95% rename from spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/WebsiteUser.java index 4eb9773e36..e632623019 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/WebsiteUser.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java b/spring-data-rest/src/main/java/com/baeldung/books/projections/CustomBook.java similarity index 77% rename from spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java rename to spring-data-rest/src/main/java/com/baeldung/books/projections/CustomBook.java index 3dc6938f5c..5fe78c869d 100644 --- a/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/projections/CustomBook.java @@ -1,12 +1,12 @@ -package com.baeldung.projections; +package com.baeldung.books.projections; import java.util.List; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.rest.core.config.Projection; -import com.baeldung.models.Author; -import com.baeldung.models.Book; +import com.baeldung.books.models.Author; +import com.baeldung.books.models.Book; @Projection(name = "customBook", types = { Book.class }) public interface CustomBook { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/AddressRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/AddressRepository.java similarity index 62% rename from spring-data-rest/src/main/java/com/baeldung/repositories/AddressRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/AddressRepository.java index 1cc7527e80..5e3900f439 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/AddressRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/AddressRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.repository.CrudRepository; -import com.baeldung.models.Address; +import com.baeldung.books.models.Address; public interface AddressRepository extends CrudRepository { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/AuthorRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/AuthorRepository.java similarity index 62% rename from spring-data-rest/src/main/java/com/baeldung/repositories/AuthorRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/AuthorRepository.java index 2d470367ef..837e13b1d2 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/AuthorRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/AuthorRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.repository.CrudRepository; -import com.baeldung.models.Author; +import com.baeldung.books.models.Author; public interface AuthorRepository extends CrudRepository { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/BookRepository.java similarity index 67% rename from spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/BookRepository.java index eee44f35d4..5d7e277526 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/BookRepository.java @@ -1,10 +1,10 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; -import com.baeldung.models.Book; -import com.baeldung.projections.CustomBook; +import com.baeldung.books.models.Book; +import com.baeldung.books.projections.CustomBook; @RepositoryRestResource(excerptProjection = CustomBook.class) public interface BookRepository extends CrudRepository { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/LibraryRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/LibraryRepository.java similarity index 62% rename from spring-data-rest/src/main/java/com/baeldung/repositories/LibraryRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/LibraryRepository.java index c00787f03c..92518339a0 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/LibraryRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/LibraryRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.repository.CrudRepository; -import com.baeldung.models.Library; +import com.baeldung.books.models.Library; public interface LibraryRepository extends CrudRepository { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/SubjectRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/SubjectRepository.java similarity index 85% rename from spring-data-rest/src/main/java/com/baeldung/repositories/SubjectRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/SubjectRepository.java index 76e34b0799..187b01f222 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/SubjectRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/SubjectRepository.java @@ -1,11 +1,12 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RestResource; -import com.baeldung.models.Subject; + +import com.baeldung.books.models.Subject; public interface SubjectRepository extends PagingAndSortingRepository { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/UserRepository.java similarity index 91% rename from spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/UserRepository.java index a3fed1c318..f0823338bc 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/UserRepository.java @@ -1,11 +1,12 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.web.bind.annotation.CrossOrigin; -import com.baeldung.models.WebsiteUser; + +import com.baeldung.books.models.WebsiteUser; @CrossOrigin @RepositoryRestResource(collectionResourceRel = "users", path = "users") diff --git a/spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java b/spring-data-rest/src/main/java/com/baeldung/books/validators/WebsiteUserValidator.java similarity index 87% rename from spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java rename to spring-data-rest/src/main/java/com/baeldung/books/validators/WebsiteUserValidator.java index 0380332708..ad7511c2ba 100644 --- a/spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/validators/WebsiteUserValidator.java @@ -1,10 +1,10 @@ -package com.baeldung.validators; +package com.baeldung.books.validators; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; -import com.baeldung.models.WebsiteUser; +import com.baeldung.books.models.WebsiteUser; @Component("beforeCreateWebsiteUserValidator") public class WebsiteUserValidator implements Validator { diff --git a/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java b/spring-data-rest/src/test/java/com/baeldung/books/events/AuthorEventHandlerUnitTest.java similarity index 86% rename from spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java rename to spring-data-rest/src/test/java/com/baeldung/books/events/AuthorEventHandlerUnitTest.java index c01d5882a0..719c4d7c86 100644 --- a/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/books/events/AuthorEventHandlerUnitTest.java @@ -1,6 +1,8 @@ -package com.baeldung.events; +package com.baeldung.books.events; + +import com.baeldung.books.events.AuthorEventHandler; +import com.baeldung.books.models.Author; -import com.baeldung.models.Author; import org.junit.Test; import org.mockito.Mockito; import org.springframework.data.rest.core.annotation.RepositoryEventHandler; diff --git a/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java b/spring-data-rest/src/test/java/com/baeldung/books/events/BookEventHandlerUnitTest.java similarity index 81% rename from spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java rename to spring-data-rest/src/test/java/com/baeldung/books/events/BookEventHandlerUnitTest.java index d6b8b3b25e..4b9d77afa2 100644 --- a/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/books/events/BookEventHandlerUnitTest.java @@ -1,7 +1,9 @@ -package com.baeldung.events; +package com.baeldung.books.events; + +import com.baeldung.books.events.BookEventHandler; +import com.baeldung.books.models.Author; +import com.baeldung.books.models.Book; -import com.baeldung.models.Author; -import com.baeldung.models.Book; import org.junit.Test; import org.mockito.Mockito; diff --git a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java b/spring-data-rest/src/test/java/com/baeldung/books/projections/SpringDataProjectionLiveTest.java similarity index 91% rename from spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java rename to spring-data-rest/src/test/java/com/baeldung/books/projections/SpringDataProjectionLiveTest.java index 274ae3bc1d..98b5831b96 100644 --- a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/books/projections/SpringDataProjectionLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.projection; +package com.baeldung.books.projections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -16,11 +16,11 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.Author; -import com.baeldung.models.Book; -import com.baeldung.repositories.AuthorRepository; -import com.baeldung.repositories.BookRepository; +import com.baeldung.books.SpringDataRestApplication; +import com.baeldung.books.models.Author; +import com.baeldung.books.models.Book; +import com.baeldung.books.repositories.AuthorRepository; +import com.baeldung.books.repositories.BookRepository; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) diff --git a/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/books/validator/SpringDataRestValidatorIntegrationTest.java similarity index 97% rename from spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java rename to spring-data-rest/src/test/java/com/baeldung/books/validator/SpringDataRestValidatorIntegrationTest.java index 6da76d6a33..75733475e7 100644 --- a/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/books/validator/SpringDataRestValidatorIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.validator; +package com.baeldung.books.validator; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -19,8 +19,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.WebsiteUser; +import com.baeldung.books.SpringDataRestApplication; +import com.baeldung.books.models.WebsiteUser; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) diff --git a/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java index e1aff7e09d..d7ef361783 100644 --- a/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java @@ -42,7 +42,7 @@ public class UserControllerIntegrationTest { @Test public void whenGetRequestToUserEndPointWithNameRequestParameter_thenCorrectResponse() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/user").param("name", "John").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()) + mockMvc.perform(MockMvcRequestBuilders.get("/users").param("name", "John").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$['content'][0].['name']").value("John")); } diff --git a/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 0380e3dc2f..c2682855b8 100644 --- a/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.SpringDataRestApplication; +import com.baeldung.books.SpringDataRestApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringDataRestApplication.class) diff --git a/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java b/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7e7fccadef --- /dev/null +++ b/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.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.books.SpringDataRestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataRestApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml index eb0fdfea46..6f816986be 100644 --- a/spring-dispatcher-servlet/pom.xml +++ b/spring-dispatcher-servlet/pom.xml @@ -96,7 +96,6 @@ 3.0-r1655215 - 3.0.0 \ No newline at end of file diff --git a/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d1de77b1e6 --- /dev/null +++ b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-drools/src/test/java/org/baeldung/SpringContextTest.java b/spring-drools/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9a36a521f1 --- /dev/null +++ b/spring-drools/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3e9af8a336 --- /dev/null +++ b/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index ff28ac89bb..45c80f2c9f 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -192,7 +192,6 @@ 19.0 - 3.5 4.4.5 4.5.2 @@ -200,7 +199,6 @@ 2.9.0 - 2.6 2.7 1.6.1 diff --git a/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java b/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..49b8fe94d1 --- /dev/null +++ b/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-integration/src/test/java/org/baeldung/SpringContextTest.java b/spring-integration/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e45997b71e --- /dev/null +++ b/spring-integration/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..79ab2f48b8 --- /dev/null +++ b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.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.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringJenkinsPipelineApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringJenkinsPipelineApplication.class) +@DirtiesContext +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 5a12d27180..e053ee7b4b 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -38,7 +38,7 @@ javax.servlet javax.servlet-api - ${servlet-api-version} + ${javax.servlet-api.version} provided @@ -223,11 +223,10 @@ 2.27 - 3.2.0 1.6.1 4.4.9 4.5.5 - 4.0.0 + 4.0.0 1.58 3.10.0 1.5.10.RELEASE diff --git a/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java b/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f480e597b3 --- /dev/null +++ b/spring-jersey/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java b/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e0da75c7af --- /dev/null +++ b/spring-jinq/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index 2ed58c0c95..ea4af32216 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -64,7 +64,6 @@ 4.3.4.RELEASE 5.14.1 - 2.6 diff --git a/spring-jms/src/test/java/org/baeldung/SpringContextTest.java b/spring-jms/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e89faeebb7 --- /dev/null +++ b/spring-jms/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index 8bce500a86..8a1fa877da 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -102,7 +102,7 @@ com.h2database h2 - ${com.h2database.version} + ${h2.version} @@ -189,8 +189,6 @@ 3.11.7 - 1.4.193 - 1.0.0 1.5 1.0.0 diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 2fb4c776fe..3d08aaa928 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -33,7 +33,7 @@ - 2.2.2.RELEASE + 2.2.7.RELEASE \ No newline at end of file diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java index 9353e63ff6..933d2353aa 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java @@ -29,39 +29,36 @@ public class KafkaConsumerConfig { props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); return new DefaultKafkaConsumerFactory<>(props); } + + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory(String groupId) { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory(groupId)); + return factory; + } @Bean public ConcurrentKafkaListenerContainerFactory fooKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("foo")); - return factory; + return kafkaListenerContainerFactory("foo"); } @Bean public ConcurrentKafkaListenerContainerFactory barKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("bar")); - return factory; + return kafkaListenerContainerFactory("bar"); } @Bean public ConcurrentKafkaListenerContainerFactory headersKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("headers")); - return factory; + return kafkaListenerContainerFactory("headers"); } @Bean public ConcurrentKafkaListenerContainerFactory partitionsKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("partitions")); - return factory; + return kafkaListenerContainerFactory("partitions"); } @Bean public ConcurrentKafkaListenerContainerFactory filterKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("filter")); + ConcurrentKafkaListenerContainerFactory factory = kafkaListenerContainerFactory("filter"); factory.setRecordFilterStrategy(record -> record.value() .contains("World")); return factory; diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 74786e7926..18bf198948 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -137,7 +137,6 @@ 3.0.2 0.9.10 1.6.1 - 3.7 diff --git a/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java b/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..769a436778 --- /dev/null +++ b/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-ldap/src/test/java/org/baeldung/SpringContextTest.java b/spring-ldap/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8f0c3d4612 --- /dev/null +++ b/spring-ldap/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mobile/src/test/java/org/baeldung/SpringContextTest.java b/spring-mobile/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-mobile/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mockito/src/test/java/org/baeldung/SpringContextTest.java b/spring-mockito/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b6a4e8e389 --- /dev/null +++ b/spring-mockito/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-basics/.gitignore b/spring-mvc-basics/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-mvc-basics/.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-mvc-basics/README.md b/spring-mvc-basics/README.md new file mode 100644 index 0000000000..b257b3587b --- /dev/null +++ b/spring-mvc-basics/README.md @@ -0,0 +1,18 @@ +========= + +## Spring MVC Basics with Java Configuration Example Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: +- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) +- [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) +- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) +- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) +- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) +- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) +- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) +- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) +- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) +- [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) \ No newline at end of file diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml new file mode 100644 index 0000000000..8c52c60b65 --- /dev/null +++ b/spring-mvc-basics/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + com.baeldung + spring-mvc-basics + 0.1-SNAPSHOT + spring-mvc-basics + jar + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.Application + JAR + + + + + + diff --git a/spring-mvc-basics/src/main/java/com/baeldung/Application.java b/spring-mvc-basics/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..d58049fb35 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/Application.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java b/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java new file mode 100644 index 0000000000..a76d955e4f --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java @@ -0,0 +1,27 @@ +package com.baeldung.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class AppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + + context.scan("com.baeldung"); + + container.addListener(new ContextLoaderListener(context)); + + ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/"); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java similarity index 89% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java index dbd38c1122..42e441f8f9 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java @@ -1,24 +1,24 @@ -package com.baeldung.customvalidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -@Documented -@Constraint(validatedBy = ContactNumberValidator.class) -@Target({ElementType.METHOD, ElementType.FIELD}) -@Retention(RetentionPolicy.RUNTIME) -public @interface ContactNumberConstraint { - - String message() default "Invalid phone number"; - - Class[] groups() default {}; - - Class[] payload() default {}; - -} +package com.baeldung.customvalidator; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.validation.Constraint; +import javax.validation.Payload; + +@Documented +@Constraint(validatedBy = ContactNumberValidator.class) +@Target({ ElementType.METHOD, ElementType.FIELD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ContactNumberConstraint { + + String message() default "Invalid phone number"; + + Class[] groups() default {}; + + Class[] payload() default {}; + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java similarity index 97% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java index dea6b9099b..fe14f3ccf1 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java @@ -1,17 +1,17 @@ -package com.baeldung.customvalidator; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -public class ContactNumberValidator implements ConstraintValidator { - - @Override - public void initialize(ContactNumberConstraint contactNumber) { - } - - @Override - public boolean isValid(String contactField, ConstraintValidatorContext cxt) { - return contactField != null && contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14); - } - -} +package com.baeldung.customvalidator; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class ContactNumberValidator implements ConstraintValidator { + + @Override + public void initialize(ContactNumberConstraint contactNumber) { + } + + @Override + public boolean isValid(String contactField, ConstraintValidatorContext cxt) { + return contactField != null && contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java b/spring-mvc-basics/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java similarity index 92% rename from spring-mvc-java/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java rename to spring-mvc-basics/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java index 539a6032a6..1e3591b7aa 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java @@ -1,16 +1,18 @@ package com.baeldung.exception; +import java.util.Collections; +import java.util.Map; + import org.springframework.http.MediaType; import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; -import java.util.Collections; -import java.util.Map; - @RestController +@ControllerAdvice public class HttpMediaTypeNotAcceptableExceptionExampleController { @PostMapping(value = "/test", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) diff --git a/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java b/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java new file mode 100644 index 0000000000..bdfa1d835a --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java @@ -0,0 +1,42 @@ +package com.baeldung.model; + +public class Book { + + private int id; + private String author; + private String title; + + public Book() { + } + + public Book(int id, String author, String title) { + this.id = id; + this.author = author; + this.title = title; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java b/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java new file mode 100644 index 0000000000..fb0a452219 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java @@ -0,0 +1,61 @@ +package com.baeldung.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Employee { + + private long id; + private String name; + private String contactNumber; + private String workingArea; + + public Employee() { + super(); + } + + public Employee(final long id, final String name, final String contactNumber, final String workingArea) { + this.id = id; + this.name = name; + this.contactNumber = contactNumber; + this.workingArea = workingArea; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(final String contactNumber) { + this.contactNumber = contactNumber; + } + + public String getWorkingArea() { + return workingArea; + } + + public void setWorkingArea(final String workingArea) { + this.workingArea = workingArea; + } + + @Override + public String toString() { + return "Employee [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + ", workingArea=" + workingArea + "]"; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java b/spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java similarity index 82% rename from spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java rename to spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java index 12969b6002..b4fe82ab4a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java @@ -2,10 +2,7 @@ package com.baeldung.model; import com.baeldung.customvalidator.FieldsValueMatch; -@FieldsValueMatch.List({ - @FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"), - @FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!") -}) +@FieldsValueMatch.List({ @FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"), @FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!") }) public class NewUserForm { private String email; private String verifyEmail; diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java b/spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java similarity index 94% rename from spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java rename to spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java index be702a8517..8cea915e6e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java @@ -1,22 +1,22 @@ -package com.baeldung.model; - -import com.baeldung.customvalidator.ContactNumberConstraint; - -public class ValidatedPhone { - - @ContactNumberConstraint - private String phone; - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - @Override - public String toString() { - return phone; - } -} +package com.baeldung.model; + +import com.baeldung.customvalidator.ContactNumberConstraint; + +public class ValidatedPhone { + + @ContactNumberConstraint + private String phone; + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + @Override + public String toString() { + return phone; + } +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java new file mode 100644 index 0000000000..9a321f65a2 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -0,0 +1,67 @@ +package com.baeldung.spring.web.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +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.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.springframework.web.servlet.view.ResourceBundleViewResolver; +import org.springframework.web.servlet.view.XmlViewResolver; + +//@EnableWebMvc +//@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/") + .setViewName("index"); + } + + @Bean + public ViewResolver viewResolver() { + 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 resourceBundleViewResolver() { + final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); + bean.setBasename("views"); + bean.setOrder(0); + return bean; + } + + @Bean + public ViewResolver xmlViewResolver() { + final XmlViewResolver bean = new XmlViewResolver(); + bean.setLocation(new ClassPathResource("views.xml")); + bean.setOrder(1); + return bean; + } + + /** + * Spring Boot allows configuring Content Negotiation using properties + */ + @Override + public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { + configurer.favorPathExtension(true) + .favorParameter(true) + .parameterName("mediaType") + .ignoreAcceptHeader(false) + .useRegisteredExtensionsOnly(false) + .defaultContentType(MediaType.APPLICATION_JSON) + .mediaType("xml", MediaType.APPLICATION_XML) + .mediaType("json", MediaType.APPLICATION_JSON); + } +} \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java new file mode 100644 index 0000000000..cbea4c98c6 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -0,0 +1,60 @@ +package com.baeldung.web.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +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; +import org.springframework.web.servlet.ModelAndView; + +import com.baeldung.model.Employee; + +@Controller +public class EmployeeController { + + Map employeeMap = new HashMap<>(); + + @ModelAttribute("employees") + public void initEmployees() { + employeeMap.put(1L, new Employee(1L, "John", "223334411", "rh")); + employeeMap.put(2L, new Employee(2L, "Peter", "22001543", "informatics")); + employeeMap.put(3L, new Employee(3L, "Mike", "223334411", "admin")); + } + + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } + + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final Long Id) { + return employeeMap.get(Id); + } + + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("workingArea", employee.getWorkingArea()); + model.addAttribute("id", employee.getId()); + + employeeMap.put(employee.getId(), employee); + + return "employeeView"; + } + + @ModelAttribute + public void addAttributes(final Model model) { + model.addAttribute("msg", "Welcome to the Netherlands!"); + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/NewUserController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/NewUserController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/NewUserController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/NewUserController.java diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java new file mode 100644 index 0000000000..e91a914c6d --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java @@ -0,0 +1,47 @@ +package com.baeldung.web.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RequestMappingShortcutsController { + + @GetMapping("/get") + public @ResponseBody ResponseEntity get() { + return new ResponseEntity("GET Response", HttpStatus.OK); + } + + @GetMapping("/get/{id}") + public @ResponseBody ResponseEntity getById(@PathVariable String id) { + return new ResponseEntity("GET Response : " + id, HttpStatus.OK); + } + + @PostMapping("/post") + public @ResponseBody ResponseEntity post() { + return new ResponseEntity("POST Response", HttpStatus.OK); + } + + @PutMapping("/put") + public @ResponseBody ResponseEntity put() { + return new ResponseEntity("PUT Response", HttpStatus.OK); + } + + @DeleteMapping("/delete") + public @ResponseBody ResponseEntity delete() { + return new ResponseEntity("DELETE Response", HttpStatus.OK); + } + + @PatchMapping("/patch") + public @ResponseBody ResponseEntity patch() { + return new ResponseEntity("PATCH Response", HttpStatus.OK); + } + +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java new file mode 100644 index 0000000000..4cc7589bc8 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java @@ -0,0 +1,48 @@ +package com.baeldung.web.controller; + +import java.util.concurrent.ThreadLocalRandom; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.model.Book; + +@RestController +public class ResponseStatusRestController { + + @GetMapping("/teapot") + @ResponseStatus(HttpStatus.I_AM_A_TEAPOT) + public void teaPot() { + } + + @GetMapping("empty") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void emptyResponse() { + } + + @GetMapping("empty-no-responsestatus") + public void emptyResponseWithoutResponseStatus() { + } + + @PostMapping("create") + @ResponseStatus(HttpStatus.CREATED) + public Book createEntity() { + // here we would create and persist an entity + int randomInt = ThreadLocalRandom.current() + .nextInt(1, 100); + Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); + return entity; + } + + @PostMapping("create-no-responsestatus") + public Book createEntityWithoutResponseStatus() { + // here we would create and persist an entity + int randomInt = ThreadLocalRandom.current() + .nextInt(1, 100); + Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); + return entity; + } +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java new file mode 100644 index 0000000000..ce89669fde --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java @@ -0,0 +1,24 @@ +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"; + } + + @GetMapping("/sample2") + public String showForm2() { + return "sample2"; + } + + @GetMapping("/sample3") + public String showForm3() { + return "sample3"; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java similarity index 96% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java index 9b3a6b3a4c..73e1e4bb25 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java @@ -1,32 +1,32 @@ -package com.baeldung.web.controller; - -import com.baeldung.model.ValidatedPhone; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; - -import javax.validation.Valid; - -@Controller -public class ValidatedPhoneController { - - @GetMapping("/validatePhone") - public String loadFormPage(Model m) { - m.addAttribute("validatedPhone", new ValidatedPhone()); - return "phoneHome"; - } - - @PostMapping("/addValidatePhone") - public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) { - if (result.hasErrors()) { - return "phoneHome"; - } - - m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString()); - return "phoneHome"; - } - - -} +package com.baeldung.web.controller; + +import javax.validation.Valid; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; + +import com.baeldung.model.ValidatedPhone; + +@Controller +public class ValidatedPhoneController { + + @GetMapping("/validatePhone") + public String loadFormPage(Model m) { + m.addAttribute("validatedPhone", new ValidatedPhone()); + return "phoneHome"; + } + + @PostMapping("/addValidatePhone") + public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) { + if (result.hasErrors()) { + return "phoneHome"; + } + + m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString()); + return "phoneHome"; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java diff --git a/spring-mvc-basics/src/main/resources/application.properties b/spring-mvc-basics/src/main/resources/application.properties new file mode 100644 index 0000000000..b8a9be0b40 --- /dev/null +++ b/spring-mvc-basics/src/main/resources/application.properties @@ -0,0 +1,7 @@ +server.servlet.context-path=/spring-mvc-basics + +### Content Negotiation (already defined programatically) +spring.mvc.pathmatch.use-suffix-pattern=true +#spring.mvc.contentnegotiation.favor-path-extension=true +#spring.mvc.contentnegotiation.favor-parameter=true +#spring.mvc.contentnegotiation.parameter-name=mediaType diff --git a/spring-mvc-basics/src/main/resources/mvc-configuration.xml b/spring-mvc-basics/src/main/resources/mvc-configuration.xml new file mode 100644 index 0000000000..7505614c99 --- /dev/null +++ b/spring-mvc-basics/src/main/resources/mvc-configuration.xml @@ -0,0 +1,20 @@ + + + + + + + + + /WEB-INF/view/ + + + .jsp + + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/resources/views.properties b/spring-mvc-basics/src/main/resources/views.properties new file mode 100644 index 0000000000..06d042b446 --- /dev/null +++ b/spring-mvc-basics/src/main/resources/views.properties @@ -0,0 +1,3 @@ +sample2.(class)=org.springframework.web.servlet.view.JstlView +sample2.url=/WEB-INF/view2/sample2.jsp + diff --git a/spring-mvc-java/src/main/resources/views.xml b/spring-mvc-basics/src/main/resources/views.xml similarity index 65% rename from spring-mvc-java/src/main/resources/views.xml rename to spring-mvc-basics/src/main/resources/views.xml index 83bca5293d..a44d3deae4 100644 --- a/spring-mvc-java/src/main/resources/views.xml +++ b/spring-mvc-basics/src/main/resources/views.xml @@ -1,10 +1,10 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp new file mode 100644 index 0000000000..fa5812faea --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -0,0 +1,33 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Register an Employee + + +

Welcome, Enter The Employee Details

+ + + + + + + + + + + + + + + + + + +
Name
Id
Contact Number
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp new file mode 100644 index 0000000000..9a9b879a35 --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp @@ -0,0 +1,25 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Employee Information

+

${msg}

+ + + + + + + + + + + + + +
Name :${name}
ID :${id}
Contact Number :${contactNumber}
+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp new file mode 100644 index 0000000000..4f4eb0068d --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the index view

+ + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp similarity index 89% rename from spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp rename to spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp index b873e9bc5f..ebc9052639 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp @@ -1,38 +1,38 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> - - - - - Sample Form - - - - -
- -

Phone Number

-
${message}
- - - - - - -
- - -
-
- - +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> + + + + + Sample Form + + + + +
+ +

Phone Number

+
${message}
+ + + + + + +
+ + +
+
+ + diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp new file mode 100644 index 0000000000..7cc14b5dcd --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp new file mode 100644 index 0000000000..c826700a75 --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample2 view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp new file mode 100644 index 0000000000..b58a0973da --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample3 view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2feb9efce1 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java similarity index 76% rename from spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java index e3dcb15de8..577825d8c5 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java @@ -1,11 +1,10 @@ package com.baeldung.config; -import com.baeldung.web.controller.handlermapping.WelcomeController; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; -import org.springframework.web.servlet.view.InternalResourceViewResolver; + +import com.baeldung.web.controller.handlermapping.WelcomeController; @Configuration public class BeanNameUrlHandlerMappingConfig { @@ -16,7 +15,7 @@ public class BeanNameUrlHandlerMappingConfig { } @Bean("/beanNameUrl") - public WelcomeController welcome() { + public WelcomeController welcomeBeanNameMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java similarity index 90% rename from spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java index d3a329a387..4072278fee 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java @@ -16,7 +16,7 @@ public class HandlerMappingDefaultConfig { } @Bean - public WelcomeController welcome() { + public WelcomeController welcomeDefaultMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java similarity index 89% rename from spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java index 2d80dbfeaf..c5fec171a7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java @@ -16,14 +16,14 @@ import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; public class HandlerMappingPrioritiesConfig { @Bean - BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() { + BeanNameUrlHandlerMapping beanNameUrlHandlerMappingOrder1() { BeanNameUrlHandlerMapping beanNameUrlHandlerMapping = new BeanNameUrlHandlerMapping(); beanNameUrlHandlerMapping.setOrder(1); return beanNameUrlHandlerMapping; } @Bean - public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { + public SimpleUrlHandlerMapping simpleUrlHandlerMappingOrder0() { SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); simpleUrlHandlerMapping.setOrder(0); Map urlMap = new HashMap<>(); @@ -37,7 +37,7 @@ public class HandlerMappingPrioritiesConfig { return new SimpleUrlMappingController(); } - @Bean("/welcome") + @Bean("/welcome-priorities") public BeanNameHandlerMappingController beanNameHandlerMapping() { return new BeanNameHandlerMappingController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java similarity index 85% rename from spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java index c7921c2706..7a366ecbd7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java @@ -18,7 +18,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; public class SimpleUrlHandlerMappingConfig { @Bean - public ViewResolver viewResolver() { + public ViewResolver viewResolverSimpleMappingConfig() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/"); viewResolver.setSuffix(".jsp"); @@ -29,13 +29,13 @@ public class SimpleUrlHandlerMappingConfig { public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); Map urlMap = new HashMap<>(); - urlMap.put("/simpleUrlWelcome", welcome()); + urlMap.put("/simpleUrlWelcome", welcomeSimpleMappingConfig()); simpleUrlHandlerMapping.setUrlMap(urlMap); return simpleUrlHandlerMapping; } @Bean - public WelcomeController welcome() { + public WelcomeController welcomeSimpleMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-basics/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java new file mode 100644 index 0000000000..797e489080 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.exception; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +@AutoConfigureMockMvc +public class HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest { + + @Autowired + MockMvc mockMvc; + + @Test + public void whenHttpMediaTypeNotAcceptableExceptionTriggered_thenExceptionHandled() throws Exception { + mockMvc.perform(post("/test").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_PDF)) + .andExpect(content().string("acceptable MIME type:application/json")); + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java similarity index 51% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java index 2cd225a775..24182f492a 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java @@ -5,46 +5,47 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; public class ClassValidationMvcIntegrationTest { - private MockMvc mockMvc; - - @Before - public void setup(){ - this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController()).build(); + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController()) + .build(); } - + @Test public void givenMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/user") - .accept(MediaType.TEXT_HTML) - .param("email", "john@yahoo.com") - .param("verifyEmail", "john@yahoo.com") - .param("password", "pass") - .param("verifyPassword", "pass")) - .andExpect(model().attribute("message", "Valid form")) - .andExpect(view().name("userHome")) - .andExpect(status().isOk()) - .andDo(print()); + .accept(MediaType.TEXT_HTML) + .param("email", "john@yahoo.com") + .param("verifyEmail", "john@yahoo.com") + .param("password", "pass") + .param("verifyPassword", "pass")) + .andExpect(model().attribute("message", "Valid form")) + .andExpect(view().name("userHome")) + .andExpect(status().isOk()) + .andDo(print()); } - + @Test public void givenNotMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/user") - .accept(MediaType.TEXT_HTML) - .param("email", "john@yahoo.com") - .param("verifyEmail", "john@yahoo.commmm") - .param("password", "pass") - .param("verifyPassword", "passsss")) - .andExpect(model().errorCount(2)) - .andExpect(view().name("userHome")) - .andExpect(status().isOk()) - .andDo(print()); + .accept(MediaType.TEXT_HTML) + .param("email", "john@yahoo.com") + .param("verifyEmail", "john@yahoo.commmm") + .param("password", "pass") + .param("verifyPassword", "passsss")) + .andExpect(model().errorCount(2)) + .andExpect(view().name("userHome")) + .andExpect(status().isOk()) + .andDo(print()); } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java similarity index 63% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java index 013cf9c91d..11b72e1650 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java @@ -1,41 +1,43 @@ -package com.baeldung.web.controller; - -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.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -public class CustomMVCValidatorIntegrationTest { - - private MockMvc mockMvc; - - @Before - public void setup(){ - this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController()).build(); - } - - @Test - public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception{ - this.mockMvc.perform(get("/validatePhone")).andExpect(view().name("phoneHome")); - } - - @Test - public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone"). - accept(MediaType.TEXT_HTML). - param("phoneInput", "123")). - andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone","ContactNumberConstraint")). - andExpect(view().name("phoneHome")). - andExpect(status().isOk()). - andDo(print()); - } - -} +package com.baeldung.web.controller; + +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.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class CustomMVCValidatorIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController()) + .build(); + } + + @Test + public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception { + this.mockMvc.perform(get("/validatePhone")) + .andExpect(view().name("phoneHome")); + } + + @Test + public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone") + .accept(MediaType.TEXT_HTML) + .param("phoneInput", "123")) + .andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone", "ContactNumberConstraint")) + .andExpect(view().name("phoneHome")) + .andExpect(status().isOk()) + .andDo(print()); + } + +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java new file mode 100644 index 0000000000..6500955d23 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +public class EmployeeControllerContentNegotiationIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenEndpointUsingJsonSuffixCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1.json")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlSuffixCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1.xml")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } + + @Test + public void whenEndpointUsingJsonParameterCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1?mediaType=json")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlParameterCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1?mediaType=xml")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } + + @Test + public void whenEndpointUsingJsonAcceptHeaderCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlAcceptHeaderCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java new file mode 100644 index 0000000000..5195adabd5 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import java.util.Arrays; +import java.util.Collection; + +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +public class EmployeeControllerModelAttributeIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void givenUrlEncodedFormData_whenAddEmployeeEndpointCalled_thenModelContainsMsgAttribute() throws Exception { + Collection formData = Arrays.asList(new BasicNameValuePair("name", "employeeName"), new BasicNameValuePair("id", "99"), new BasicNameValuePair("contactNumber", "123456789")); + String urlEncodedFormData = EntityUtils.toString(new UrlEncodedFormEntity(formData)); + + mockMvc.perform(post("/addEmployee").contentType(MediaType.APPLICATION_FORM_URLENCODED) + .content(urlEncodedFormData)) + .andExpect(status().isOk()) + .andExpect(view().name("employeeView")) + .andExpect(model().attribute("msg", "Welcome to the Netherlands!")); + } +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java new file mode 100644 index 0000000000..3fbb5da75e --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java @@ -0,0 +1,97 @@ +package com.baeldung.web.controller; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class RequestMapingShortcutsIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new RequestMappingShortcutsController()) + .build(); + } + + @Test + public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("GET Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("POST Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("PUT Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("DELETE Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("PATCH Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java new file mode 100644 index 0000000000..1f37a3750c --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class ResponseStatusRestControllerIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new ResponseStatusRestController()) + .build(); + } + + @Test + public void whenTeapotEndpointCalled_thenTeapotResponseObtained() throws Exception { + this.mockMvc.perform(get("/teapot")) + .andExpect(status().isIAmATeapot()); + } + + @Test + public void whenEmptyNoContentEndpointCalled_thenNoContentResponseObtained() throws Exception { + this.mockMvc.perform(get("/empty")) + .andExpect(status().isNoContent()); + } + + @Test + public void whenEmptyWithoutResponseStatusEndpointCalled_then200ResponseObtained() throws Exception { + this.mockMvc.perform(get("/empty-no-responsestatus")) + .andExpect(status().isOk()); + } + + @Test + public void whenCreateWithCreatedEndpointCalled_thenCreatedResponseObtained() throws Exception { + this.mockMvc.perform(post("/create")) + .andExpect(status().isCreated()); + } + + @Test + public void whenCreateWithoutResponseStatusEndpointCalled_thenCreatedResponseObtained() throws Exception { + this.mockMvc.perform(post("/create-no-responsestatus")) + .andExpect(status().isOk()); + } + +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java new file mode 100644 index 0000000000..0b958996c9 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java @@ -0,0 +1,33 @@ +package com.baeldung.web.controller; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.RestAssured; + +public class SampleControllerLiveTest { + + private static final String SERVICE_BASE_URL = "/spring-mvc-basics"; + + @Test + public void whenSampleEndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample") + .then() + .statusCode(HttpStatus.OK.value()); + } + + @Test + public void whenSample2EndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample2") + .then() + .statusCode(HttpStatus.OK.value()); + } + + @Test + public void whenSample3EndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample3") + .then() + .statusCode(HttpStatus.OK.value()); + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java similarity index 90% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java index 23be3a1655..87d70c2d29 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java @@ -5,19 +5,17 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import com.baeldung.web.controller.SimpleBookController; - public class SimpleBookControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; - @Before + @BeforeEach public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java similarity index 85% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java index c5bd53f1a7..294943f2e2 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java @@ -5,27 +5,25 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import com.baeldung.web.controller.SimpleBookController; - public class SimpleBookRestControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; - @Before + @BeforeEach public void setup() { - this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); + this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookRestController()).build(); } @Test public void givenBookId_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc - .perform(get("/books/42")) + .perform(get("/books-rest/42")) .andExpect(status().isOk()) .andExpect(content().contentType(CONTENT_TYPE)) .andExpect(jsonPath("$.id").value(42)); diff --git a/spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/BeanNameUrlHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/BeanNameUrlHandlerMappingConfig.xml diff --git a/spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/ControllerClassNameHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/ControllerClassNameHandlerMappingConfig.xml diff --git a/spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml b/spring-mvc-basics/src/test/resources/HandlerMappingConfiguringPriorities.xml similarity index 100% rename from spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml rename to spring-mvc-basics/src/test/resources/HandlerMappingConfiguringPriorities.xml diff --git a/spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/SimpleUrlHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/SimpleUrlHandlerMappingConfig.xml diff --git a/spring-mvc-forms-jsp/pom.xml b/spring-mvc-forms-jsp/pom.xml index 20912e71e5..5ce2d19414 100644 --- a/spring-mvc-forms-jsp/pom.xml +++ b/spring-mvc-forms-jsp/pom.xml @@ -99,7 +99,6 @@ - 2.6 6.0.10.Final 1.3.3 5.2.5.Final diff --git a/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e35fc8c86c --- /dev/null +++ b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java new file mode 100644 index 0000000000..751df882f9 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java new file mode 100644 index 0000000000..0b308319b1 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 3deeb21afc..e67d4f30a1 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -6,29 +6,16 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) - [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial) - [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial) -- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) - [Integration Testing in Spring](http://www.baeldung.com/integration-testing-in-spring) - [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables) - [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring) - [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) -- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) -- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) -- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) -- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) -- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) -- [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) -- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) -- [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) -- [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) -- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 853d8db64c..cb16e91bc4 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -15,8 +15,8 @@ - - org.springframework + + org.springframework spring-webmvc ${spring.version} @@ -34,7 +34,6 @@ javax.servlet jstl ${jstl.version} - @@ -134,17 +133,22 @@ gson 2.8.5 - - org.springframework - spring-websocket - ${spring.version} - + + org.springframework + spring-websocket + ${spring.version} + - - org.springframework - spring-messaging - ${spring.version} - + + org.springframework + spring-messaging + ${spring.version} + + + org.glassfish + javax.el + ${javax.el.version} + @@ -291,7 +295,7 @@ 3.16-beta1 - 3.0.1-b06 + 3.0.1-b09 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 191d721dfb..44fef92917 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 @@ -12,13 +12,11 @@ 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; @@ -26,8 +24,6 @@ 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.springframework.web.servlet.view.ResourceBundleViewResolver; -import org.springframework.web.servlet.view.XmlViewResolver; import org.springframework.web.util.UrlPathHelper; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; @@ -97,11 +93,6 @@ public class WebConfig implements WebMvcConfigurer { 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() { @@ -110,22 +101,6 @@ public class WebConfig implements WebMvcConfigurer { return multipartResolver; } - - @Bean - public ViewResolver xmlViewResolver() { - final XmlViewResolver bean = new XmlViewResolver(); - bean.setLocation(new ClassPathResource("views.xml")); - bean.setOrder(1); - return bean; - } - - @Bean - public ViewResolver resourceBundleViewResolver() { - final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); - bean.setBasename("views"); - bean.setOrder(0); - return bean; - } @Override public void extendMessageConverters(final List> converters) { diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java index ef76059567..251287dff8 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -1,20 +1,29 @@ package com.baeldung.web.controller; -import com.baeldung.model.Employee; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.MatrixVariable; +import org.springframework.web.bind.annotation.ModelAttribute; +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; +import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; -import java.util.*; +import com.baeldung.model.Employee; @SessionAttributes("employees") @Controller -@ControllerAdvice public class EmployeeController { Map employeeMap = new HashMap<>(); @@ -35,7 +44,7 @@ public class EmployeeController { public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { return employeeMap.get(Id); } - + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { @@ -51,11 +60,6 @@ public class EmployeeController { return "employeeView"; } - @ModelAttribute - public void addAttributes(final Model model) { - model.addAttribute("msg", "Welcome to the Netherlands!"); - } - @RequestMapping(value = "/employees/{name}", method = RequestMethod.GET) @ResponseBody public ResponseEntity> getEmployeeByNameAndBeginContactNumber(@PathVariable final String name, @MatrixVariable final String beginContactNumber) { diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java deleted file mode 100644 index 5d4cbe9d78..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.web.controller; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PatchMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class RequestMappingShortcutsController { - - @GetMapping("/get") - public @ResponseBody ResponseEntity get() { - return new ResponseEntity("GET Response", HttpStatus.OK); - } - - @GetMapping("/get/{id}") - public @ResponseBody ResponseEntity getById(@PathVariable String id) { - return new ResponseEntity("GET Response : " + id, HttpStatus.OK); - } - - @PostMapping("/post") - public @ResponseBody ResponseEntity post() { - return new ResponseEntity("POST Response", HttpStatus.OK); - } - - @PutMapping("/put") - public @ResponseBody ResponseEntity put() { - return new ResponseEntity("PUT Response", HttpStatus.OK); - } - - @DeleteMapping("/delete") - public @ResponseBody ResponseEntity delete() { - return new ResponseEntity("DELETE Response", HttpStatus.OK); - } - - @PatchMapping("/patch") - public @ResponseBody ResponseEntity patch() { - return new ResponseEntity("PATCH Response", HttpStatus.OK); - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/message/MessageController.java similarity index 94% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java rename to spring-mvc-java/src/main/java/com/baeldung/web/controller/message/MessageController.java index 111bf023f7..fdb0d75530 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/message/MessageController.java @@ -1,4 +1,4 @@ -package com.baeldung.web.controller; +package com.baeldung.web.controller.message; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; diff --git a/spring-mvc-java/src/main/resources/views.properties b/spring-mvc-java/src/main/resources/views.properties deleted file mode 100644 index 95687cb62a..0000000000 --- a/spring-mvc-java/src/main/resources/views.properties +++ /dev/null @@ -1,3 +0,0 @@ -sample.(class)=org.springframework.web.servlet.view.JstlView -sample.url=/WEB-INF/view/sample.jsp - diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp index 8a32fd12b6..268f0a055a 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -8,7 +8,7 @@

Welcome, Enter The Employee Details

- + diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp index 627a9d9ddb..1457bc5fc8 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp @@ -6,7 +6,6 @@

Submitted Employee Information

-

${msg}

Name
@@ -20,10 +19,6 @@ - - - -
Name :Contact Number : ${contactNumber}
Working Area :${workingArea}
\ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9777addb61 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.config.AppInitializer; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppInitializer.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java index 529879fada..75efd57ae4 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -15,7 +15,7 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration @EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +@ComponentScan(basePackages = { "com.baeldung.web.controller.message" }) public class TestConfig implements WebMvcConfigurer { @Autowired @@ -44,5 +44,4 @@ public class TestConfig implements WebMvcConfigurer { templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } - } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java deleted file mode 100644 index 0c2aa3de1b..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.web.controller; - -import org.junit.Before; -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.web.WebAppConfiguration; - -import com.baeldung.model.Employee; -import com.baeldung.spring.web.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = WebConfig.class) -public class EmployeeIntegrationTest { - - @Autowired - private EmployeeController employeeController; - - @Before - public void setup() { - employeeController.initEmployees(); - } - - @Test - public void whenInitEmployees_thenVerifyValuesInitiation() { - - Employee employee1 = employeeController.employeeMap.get(1L); - Employee employee2 = employeeController.employeeMap.get(2L); - Employee employee3 = employeeController.employeeMap.get(3L); - - Assert.assertTrue(employee1.getId() == 1L); - Assert.assertTrue(employee1.getName().equals("John")); - Assert.assertTrue(employee1.getContactNumber().equals("223334411")); - Assert.assertTrue(employee1.getWorkingArea().equals("rh")); - - Assert.assertTrue(employee2.getId() == 2L); - Assert.assertTrue(employee2.getName().equals("Peter")); - Assert.assertTrue(employee2.getContactNumber().equals("22001543")); - Assert.assertTrue(employee2.getWorkingArea().equals("informatics")); - - Assert.assertTrue(employee3.getId() == 3L); - Assert.assertTrue(employee3.getName().equals("Mike")); - Assert.assertTrue(employee3.getContactNumber().equals("223334411")); - Assert.assertTrue(employee3.getWorkingArea().equals("admin")); - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java deleted file mode 100644 index fb21905027..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.baeldung.web.controller; - -import org.junit.Before; -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.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultMatcher; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.baeldung.spring.web.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = WebConfig.class) -public class RequestMapingShortcutsIntegrationTest { - - @Autowired - private WebApplicationContext ctx; - - private MockMvc mockMvc; - - @Before - public void setup () { - DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.ctx); - this.mockMvc = builder.build(); - } - - @Test - public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("GET Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("POST Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PUT Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("DELETE Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PATCH Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - -} diff --git a/spring-mvc-kotlin/.gitignore b/spring-mvc-kotlin/.gitignore new file mode 100644 index 0000000000..416395ffea --- /dev/null +++ b/spring-mvc-kotlin/.gitignore @@ -0,0 +1 @@ +transaction.log \ No newline at end of file diff --git a/spring-mvc-kotlin/README.md b/spring-mvc-kotlin/README.md index e5167f69fc..cc6827eb1b 100644 --- a/spring-mvc-kotlin/README.md +++ b/spring-mvc-kotlin/README.md @@ -2,3 +2,4 @@ - [Spring MVC Setup with Kotlin](http://www.baeldung.com/spring-mvc-kotlin) - [Working with Kotlin and JPA](http://www.baeldung.com/kotlin-jpa) - [Kotlin-allopen and Spring](http://www.baeldung.com/kotlin-allopen-spring) +- [MockMvc Kotlin DSL](https://www.baeldung.com/mockmvc-kotlin-dsl) diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml index fc76f58727..fb1f242644 100644 --- a/spring-mvc-kotlin/pom.xml +++ b/spring-mvc-kotlin/pom.xml @@ -15,12 +15,12 @@ - org.springframework - spring-web + org.springframework.boot + spring-boot-starter-web - org.springframework - spring-webmvc + org.springframework.boot + spring-boot-starter-json org.thymeleaf @@ -46,8 +46,8 @@ test - org.springframework - spring-test + org.springframework.boot + spring-boot-starter-test test diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt new file mode 100644 index 0000000000..68ab5f31a6 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt @@ -0,0 +1,26 @@ +package com.baeldung.kotlin.mockmvc + +import org.springframework.http.MediaType +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RestController + +@RestController +@RequestMapping("/mockmvc") +class MockMvcController { + + @RequestMapping(value = ["/validate"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE]) + fun validate(@RequestBody request: Request): Response { + val error = if (request.name.first == "admin") { + null + } else { + ERROR + } + return Response(error) + } + + companion object { + const val ERROR = "invalid user" + } +} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt new file mode 100644 index 0000000000..3231b6f186 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt @@ -0,0 +1,10 @@ +package com.baeldung.kotlin.mockmvc + +import com.fasterxml.jackson.annotation.JsonInclude + +data class Name(val first: String, val last: String) + +data class Request(val name: Name) + +@JsonInclude(JsonInclude.Include.NON_NULL) +data class Response(val error: String?) \ No newline at end of file diff --git a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt new file mode 100644 index 0000000000..802cd4c1e7 --- /dev/null +++ b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt @@ -0,0 +1,61 @@ +package com.baeldung.kotlin.mockmvc + +import com.fasterxml.jackson.databind.ObjectMapper +import org.junit.Test +import org.junit.runner.RunWith +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity.status +import org.springframework.test.context.junit4.SpringRunner +import org.springframework.test.web.servlet.MockMvc +import org.springframework.test.web.servlet.post +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders +import org.springframework.test.web.servlet.result.MockMvcResultHandlers +import org.springframework.test.web.servlet.result.MockMvcResultMatchers + +@RunWith(SpringRunner::class) +@WebMvcTest +class MockMvcControllerTest { + + @Autowired lateinit var mockMvc: MockMvc + @Autowired lateinit var mapper: ObjectMapper + + @Test + fun `when supported user is given then raw MockMvc-based validation is successful`() { + mockMvc.perform(MockMvcRequestBuilders + .post("/mockmvc/validate") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(mapper.writeValueAsString(Request(Name("admin", ""))))) + .andExpect(MockMvcResultMatchers.status().isOk) + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.content().string("{}")) + } + + @Test + fun `when supported user is given then kotlin DSL-based validation is successful`() { + doTest(Request(Name("admin", "")), Response(null)) + } + + @Test + fun `when unsupported user is given then validation is failed`() { + doTest(Request(Name("some-name", "some-surname")), Response(MockMvcController.ERROR)) + } + + private fun doTest(input: Request, expectation: Response) { + mockMvc.post("/mockmvc/validate") { + contentType = MediaType.APPLICATION_JSON + content = mapper.writeValueAsString(input) + accept = MediaType.APPLICATION_JSON + }.andExpect { + status { isOk } + content { contentType(MediaType.APPLICATION_JSON) } + content { json(mapper.writeValueAsString(expectation)) } + } + } +} + +@SpringBootApplication +class MockMvcApplication \ No newline at end of file diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index a767cf3c37..580a40e50b 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -47,7 +47,7 @@ commons-fileupload commons-fileupload - ${fileupload.version} + ${commons-fileupload.version} org.springframework @@ -162,18 +162,16 @@ 1.8 1.8 - 3.2.0 2.21.0 2.3.2-b02 4.0.0 6.0.10.Final enter-location-of-server - 1.3.2 + 1.3.2 3.0.7.RELEASE 2.4.12 2.3.27-incubating 1.2.5 - 1.0.2 1.9.0 1.4.9 5.1.0 diff --git a/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ab0b23c4a5 --- /dev/null +++ b/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.configuration.ApplicationConfiguration; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes={ApplicationConfiguration.class}) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} + diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index df19b67e8e..5954e48e8f 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -115,7 +115,6 @@ 2.9.0 - 2.6 2.7 1.6.1 diff --git a/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..22a4486aa7 --- /dev/null +++ b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-webflow/pom.xml b/spring-mvc-webflow/pom.xml index c8de990da0..219a2be689 100644 --- a/spring-mvc-webflow/pom.xml +++ b/spring-mvc-webflow/pom.xml @@ -94,7 +94,6 @@ 4.5.2 - 2.6 2.7 1.6.1 diff --git a/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..122dc18bad --- /dev/null +++ b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 46af321d1b..9f7a24b358 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -33,7 +33,7 @@ javax.servlet javax.servlet-api - ${javax.servlet.version} + ${javax.servlet-api.version} provided @@ -82,7 +82,7 @@ org.glassfish javax.el - 3.0.1-b08 + ${javax.el.version} @@ -129,18 +129,13 @@ 6.0.10.Final - 1.2 - 3.1.0 - 2.9.6 + 3.0.1-b08 19.0 - 3.5 - 2.5 2.8.0 - 2.6 1.6.1 diff --git a/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..27dcb83bd4 --- /dev/null +++ b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java b/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4f655277b7 --- /dev/null +++ b/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.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.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.protobuf.Application; + +@DirtiesContext +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index 58e72c1d51..4c7ac6eee9 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -32,6 +32,16 @@ quartz ${quartz.version} + + com.mchange + c3p0 + ${c3p0.version} + + + + com.h2database + h2 + @@ -44,7 +54,8 @@ - 2.2.3 + 2.3.0 + 0.9.5.2 \ No newline at end of file diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java index 6601df6c94..ccf9fca8c1 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java @@ -10,17 +10,20 @@ import javax.annotation.PostConstruct; import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; import org.quartz.*; -import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.scheduling.quartz.SpringBeanJobFactory; +import java.util.Properties; + @Configuration @ConditionalOnExpression("'${using.spring.schedulerFactory}'=='false'") public class QrtzScheduler { @@ -45,14 +48,9 @@ public class QrtzScheduler { } @Bean - public Scheduler scheduler(Trigger trigger, JobDetail job) throws SchedulerException, IOException { - - StdSchedulerFactory factory = new StdSchedulerFactory(); - factory.initialize(new ClassPathResource("quartz.properties").getInputStream()); - + public Scheduler scheduler(Trigger trigger, JobDetail job, SchedulerFactoryBean factory) throws SchedulerException { logger.debug("Getting a handle to the Scheduler"); Scheduler scheduler = factory.getScheduler(); - scheduler.setJobFactory(springBeanJobFactory()); scheduler.scheduleJob(job, trigger); logger.debug("Starting Scheduler threads"); @@ -60,6 +58,21 @@ public class QrtzScheduler { return scheduler; } + @Bean + public SchedulerFactoryBean schedulerFactoryBean() throws IOException { + SchedulerFactoryBean factory = new SchedulerFactoryBean(); + factory.setJobFactory(springBeanJobFactory()); + factory.setQuartzProperties(quartzProperties()); + return factory; + } + + public Properties quartzProperties() throws IOException { + PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); + propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); + propertiesFactoryBean.afterPropertiesSet(); + return propertiesFactoryBean.getObject(); + } + @Bean public JobDetail jobDetail() { diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java index 9978f61522..f824765efe 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java @@ -1,6 +1,7 @@ package org.baeldung.springquartz.basics.scheduler; import javax.annotation.PostConstruct; +import javax.sql.DataSource; import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; import org.quartz.JobDetail; @@ -9,7 +10,11 @@ import org.quartz.Trigger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.quartz.QuartzDataSource; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -20,6 +25,7 @@ import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean; import org.springframework.scheduling.quartz.SpringBeanJobFactory; @Configuration +@EnableAutoConfiguration @ConditionalOnExpression("'${using.spring.schedulerFactory}'=='true'") public class SpringQrtzScheduler { @@ -43,7 +49,7 @@ public class SpringQrtzScheduler { } @Bean - public SchedulerFactoryBean scheduler(Trigger trigger, JobDetail job) { + public SchedulerFactoryBean scheduler(Trigger trigger, JobDetail job, DataSource quartzDataSource) { SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean(); schedulerFactory.setConfigLocation(new ClassPathResource("quartz.properties")); @@ -53,6 +59,9 @@ public class SpringQrtzScheduler { schedulerFactory.setJobDetails(job); schedulerFactory.setTriggers(trigger); + // Comment the following line to use the default Quartz job store. + schedulerFactory.setDataSource(quartzDataSource); + return schedulerFactory; } @@ -81,4 +90,12 @@ public class SpringQrtzScheduler { trigger.setName("Qrtz_Trigger"); return trigger; } + + @Bean + @QuartzDataSource + @ConfigurationProperties(prefix = "spring.datasource") + public DataSource quartzDataSource() { + return DataSourceBuilder.create().build(); + } + } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java index ddf4efc2c5..6f66352616 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java @@ -4,20 +4,31 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import java.util.concurrent.atomic.AtomicInteger; + @Service public class SampleJobService { + public static final long EXECUTION_TIME = 5000L; + private Logger logger = LoggerFactory.getLogger(getClass()); + private AtomicInteger count = new AtomicInteger(); + public void executeSampleJob() { logger.info("The sample job has begun..."); try { - Thread.sleep(5000); + Thread.sleep(EXECUTION_TIME); } catch (InterruptedException e) { logger.error("Error while executing sample job", e); } finally { + count.incrementAndGet(); logger.info("Sample job has finished..."); } } + + public int getNumberOfInvocations() { + return count.get(); + } } diff --git a/spring-quartz/src/main/resources/application.properties b/spring-quartz/src/main/resources/application.properties index 7bdd647e25..557349af2e 100644 --- a/spring-quartz/src/main/resources/application.properties +++ b/spring-quartz/src/main/resources/application.properties @@ -1 +1,10 @@ -using.spring.schedulerFactory=true \ No newline at end of file +using.spring.schedulerFactory=true + +spring.quartz.job-store-type=jdbc +# Always create the Quartz database on startup +spring.quartz.jdbc.initialize-schema=always + +spring.datasource.jdbc-url=jdbc:h2:mem:spring-quartz;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= diff --git a/spring-quartz/src/main/resources/quartz.properties b/spring-quartz/src/main/resources/quartz.properties index cefaaef8e4..662bb83eb0 100644 --- a/spring-quartz/src/main/resources/quartz.properties +++ b/spring-quartz/src/main/resources/quartz.properties @@ -4,7 +4,19 @@ org.quartz.threadPool.threadCount=2 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true # job-store -org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore +# Enable this property for RAMJobStore +#org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore -# others -org.quartz.jobStore.misfireThreshold = 60000 \ No newline at end of file +# Enable these properties for a JDBCJobStore using JobStoreTX +org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX +org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate +org.quartz.jobStore.dataSource=quartzDataSource +# Enable this property for JobStoreCMT +#org.quartz.jobStore.nonManagedTXDataSource=quartzDataSource + +# H2 database +# use an in-memory database & initialise Quartz using their standard SQL script +org.quartz.dataSource.quartzDataSource.URL=jdbc:h2:mem:spring-quartz;INIT=RUNSCRIPT FROM 'classpath:/org/quartz/impl/jdbcjobstore/tables_h2.sql' +org.quartz.dataSource.quartzDataSource.driver=org.h2.Driver +org.quartz.dataSource.quartzDataSource.user=sa +org.quartz.dataSource.quartzDataSource.password= diff --git a/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 516cc587a7..fec47f045c 100644 --- a/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,16 +1,30 @@ package org.baeldung; import org.baeldung.springquartz.SpringQuartzApp; +import org.baeldung.springquartz.basics.service.SampleJobService; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringQuartzApp.class) public class SpringContextIntegrationTest { + @Autowired + private SampleJobService sampleJobService; + @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { } + + @Test + public void whenSchedulerStarts_thenJobsRun() throws InterruptedException { + assertThat(sampleJobService.getNumberOfInvocations()).isEqualTo(0); + Thread.sleep(SampleJobService.EXECUTION_TIME); + assertThat(sampleJobService.getNumberOfInvocations()).isEqualTo(1); + } } diff --git a/spring-quartz/src/test/java/org/baeldung/SpringContextTest.java b/spring-quartz/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a210e847c8 --- /dev/null +++ b/spring-quartz/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java b/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-reactor/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..fe20382ab4 --- /dev/null +++ b/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4325b0ddef --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e676bb0ff2 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e676bb0ff2 --- /dev/null +++ b/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..95721b6eaa --- /dev/null +++ b/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6cae1b66fc --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 5240ae24e7..69becfb4ae 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -74,7 +74,6 @@ 19.0 - 3.5 org.baeldung.web.main.Application diff --git a/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9136ce43eb --- /dev/null +++ b/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index a85393b7a8..5bc3a70ed5 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -287,7 +287,6 @@ 19.0 - 3.5 3.25.0-GA diff --git a/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8debddc40a --- /dev/null +++ b/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index 70fea91f31..7ee658d8ba 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -353,7 +353,6 @@ 19.0 - 3.5 1.7.0 diff --git a/spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.java b/spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..57886a232a --- /dev/null +++ b/spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.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.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-simple/README.md b/spring-rest-simple/README.md index 882d0ac301..c01f27bd98 100644 --- a/spring-rest-simple/README.md +++ b/spring-rest-simple/README.md @@ -5,3 +5,4 @@ - [Spring RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Spring and Apache FileUpload](http://www.baeldung.com/spring-apache-file-upload) - [Test a REST API with curl](http://www.baeldung.com/curl-rest) +- [CORS with Spring](https://www.baeldung.com/spring-cors) diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index d301957eb9..263e451c62 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -323,7 +323,6 @@ 4.0.0 1.4 3.1.0 - 3.5 1.4.9 diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/Application.java b/spring-rest-simple/src/main/java/com/baeldung/Application.java similarity index 90% rename from spring-rest-simple/src/main/java/org/baeldung/config/Application.java rename to spring-rest-simple/src/main/java/com/baeldung/Application.java index 5c9a186619..dc6bfcb970 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/Application.java +++ b/spring-rest-simple/src/main/java/com/baeldung/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -7,8 +7,8 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration -@ComponentScan("org.baeldung") @SpringBootApplication +@ComponentScan("com.baeldung.cors") public class Application extends SpringBootServletInitializer { public static void main(final String[] args) { diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java similarity index 86% rename from spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java rename to spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java index 191b87a8f2..d169f7e9d4 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java @@ -1,6 +1,5 @@ -package org.baeldung.config; +package com.baeldung.config; -import org.baeldung.config.converter.KryoHttpMessageConverter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; @@ -13,9 +12,12 @@ import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConve import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.oxm.xstream.XStreamMarshaller; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; +import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import com.baeldung.config.converter.KryoHttpMessageConverter; + import java.text.SimpleDateFormat; import java.util.List; @@ -24,10 +26,10 @@ import java.util.List; */ @Configuration @EnableWebMvc -@ComponentScan({ "org.baeldung.web" }) -public class WebConfig implements WebMvcConfigurer { +@ComponentScan({ "com.baeldung.web" }) +public class MvcConfig implements WebMvcConfigurer { - public WebConfig() { + public MvcConfig() { super(); } @@ -64,4 +66,10 @@ public class WebConfig implements WebMvcConfigurer { public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON); } + + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**"); + } } diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java b/spring-rest-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java similarity index 95% rename from spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java rename to spring-rest-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java index 6af54c379a..7ab8282350 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java +++ b/spring-rest-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java @@ -1,13 +1,13 @@ -package org.baeldung.config.converter; +package com.baeldung.config.converter; import java.io.IOException; -import org.baeldung.web.dto.Foo; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; +import com.baeldung.web.dto.Foo; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; diff --git a/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java b/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java new file mode 100644 index 0000000000..429b0c102e --- /dev/null +++ b/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java @@ -0,0 +1,18 @@ +package com.baeldung.cors; + +public class Account { + private Long id; + + public Account(Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +} diff --git a/spring-rest-simple/src/main/java/com/baeldung/cors/AccountController.java b/spring-rest-simple/src/main/java/com/baeldung/cors/AccountController.java new file mode 100644 index 0000000000..c387eb2121 --- /dev/null +++ b/spring-rest-simple/src/main/java/com/baeldung/cors/AccountController.java @@ -0,0 +1,24 @@ +package com.baeldung.cors; + +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@CrossOrigin(maxAge = 3600) +@RestController +@RequestMapping("/account") +public class AccountController { + + @CrossOrigin("http://example.com") + @RequestMapping("/{id}") + public Account retrieve(@PathVariable Long id) { + return new Account(id); + } + + @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") + public void remove(@PathVariable Long id) { + // ... + } +} \ No newline at end of file diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java similarity index 97% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java index 1c3a1086ca..3611a4e6cc 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java similarity index 96% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java index 4bcafc04fc..6c7da0296f 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java @@ -1,9 +1,8 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import java.util.Arrays; import java.util.List; -import org.baeldung.web.dto.Bazz; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; @@ -15,6 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.web.dto.Bazz; import com.fasterxml.jackson.core.JsonProcessingException; @RestController diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java similarity index 96% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java index c68d586667..bab315c027 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java @@ -1,11 +1,9 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import java.util.List; -import org.baeldung.web.dto.Foo; -import org.baeldung.web.dto.FooProtos; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -16,6 +14,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; +import com.baeldung.web.dto.Foo; +import com.baeldung.web.dto.FooProtos; import com.google.common.collect.Lists; @Controller diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java similarity index 98% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java index 5fb92d6d87..ec75e4c859 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ExampleController.java similarity index 94% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ExampleController.java index ceda138768..0cc657f0f2 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ExampleController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.status; +package com.baeldung.web.controller.status; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ForbiddenException.java similarity index 88% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ForbiddenException.java index 458bdaf170..301a25d070 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ForbiddenException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.status; +package com.baeldung.web.controller.status; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Bazz.java similarity index 91% rename from spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java rename to spring-rest-simple/src/main/java/com/baeldung/web/dto/Bazz.java index d9a495b726..861b4009b5 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Bazz.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.web.dto; public class Bazz { diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Foo.java similarity index 95% rename from spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java rename to spring-rest-simple/src/main/java/com/baeldung/web/dto/Foo.java index 240b368b50..5a54539927 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.web.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java b/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java similarity index 90% rename from spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java rename to spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java index 8ca96c38fc..db7cb66f87 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java @@ -1,7 +1,7 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: FooProtos.proto -package org.baeldung.web.dto; +package com.baeldung.web.dto; public final class FooProtos { private FooProtos() { @@ -115,11 +115,11 @@ public final class FooProtos { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.web.dto.FooProtos.Foo.class, com.baeldung.web.dto.FooProtos.Foo.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @@ -255,43 +255,43 @@ public final class FooProtos { return super.writeReplace(); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } @@ -303,7 +303,7 @@ public final class FooProtos { return newBuilder(); } - public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) { + public static Builder newBuilder(com.baeldung.web.dto.FooProtos.Foo prototype) { return newBuilder().mergeFrom(prototype); } @@ -322,13 +322,13 @@ public final class FooProtos { */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:baeldung.Foo) - org.baeldung.web.dto.FooProtos.FooOrBuilder { + com.baeldung.web.dto.FooProtos.FooOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.web.dto.FooProtos.Foo.class, com.baeldung.web.dto.FooProtos.Foo.Builder.class); } // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() @@ -364,23 +364,23 @@ public final class FooProtos { } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } - public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { - return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); + public com.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { + return com.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); } - public org.baeldung.web.dto.FooProtos.Foo build() { - org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); + public com.baeldung.web.dto.FooProtos.Foo build() { + com.baeldung.web.dto.FooProtos.Foo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } - public org.baeldung.web.dto.FooProtos.Foo buildPartial() { - org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); + public com.baeldung.web.dto.FooProtos.Foo buildPartial() { + com.baeldung.web.dto.FooProtos.Foo result = new com.baeldung.web.dto.FooProtos.Foo(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { @@ -397,16 +397,16 @@ public final class FooProtos { } public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { - return mergeFrom((org.baeldung.web.dto.FooProtos.Foo) other); + if (other instanceof com.baeldung.web.dto.FooProtos.Foo) { + return mergeFrom((com.baeldung.web.dto.FooProtos.Foo) other); } else { super.mergeFrom(other); return this; } } - public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { - if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) + public Builder mergeFrom(com.baeldung.web.dto.FooProtos.Foo other) { + if (other == com.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this; if (other.hasId()) { setId(other.getId()); @@ -433,11 +433,11 @@ public final class FooProtos { } public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; + com.baeldung.web.dto.FooProtos.Foo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); + parsedMessage = (com.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java b/spring-rest-simple/src/main/java/com/baeldung/web/util/LinkUtil.java similarity index 96% rename from spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java rename to spring-rest-simple/src/main/java/com/baeldung/web/util/LinkUtil.java index b2137aeeff..3ebba8ae1c 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/util/LinkUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.web.util; +package com.baeldung.web.util; import javax.servlet.http.HttpServletResponse; diff --git a/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml b/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml new file mode 100644 index 0000000000..e83e13be71 --- /dev/null +++ b/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..b66e642b80 --- /dev/null +++ b/spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package com.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-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java b/spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java similarity index 66% rename from spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java rename to spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java index 66ffe4947d..4bbfa2818e 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.web.controller.mediatypes; +package com.baeldung.web.controller.mediatypes; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan({ "org.baeldung.web" }) +@ComponentScan({ "com.baeldung.web" }) public class TestConfig { } diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/controller/status/ExampleControllerIntegrationTest.java similarity index 92% rename from spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/controller/status/ExampleControllerIntegrationTest.java index 7f78146b84..d1ae7f65c6 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/controller/status/ExampleControllerIntegrationTest.java @@ -1,9 +1,7 @@ -package org.baeldung.web.controller.status; +package com.baeldung.web.controller.status; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.baeldung.config.WebConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,8 +14,10 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import com.baeldung.config.MvcConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = WebConfig.class) +@ContextConfiguration(classes = MvcConfig.class) @WebAppConfiguration @AutoConfigureWebClient public class ExampleControllerIntegrationTest { diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java similarity index 96% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java index dfb3ff7a38..4f0395e914 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java @@ -1,5 +1,5 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; @@ -9,8 +9,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.baeldung.config.WebConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -23,9 +21,11 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import com.baeldung.config.MvcConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = WebConfig.class) +@ContextConfiguration(classes = MvcConfig.class) @WebAppConfiguration @AutoConfigureWebClient public class BazzNewMappingsExampleIntegrationTest { diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java similarity index 99% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java index 9dd6b13f18..f26f241beb 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java similarity index 99% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java index e213d0255f..51e3fb097e 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.apache.commons.codec.binary.Base64.encodeBase64; import static org.hamcrest.CoreMatchers.equalTo; @@ -13,7 +13,6 @@ import java.net.URI; import java.util.Arrays; import java.util.Set; -import org.baeldung.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpEntity; @@ -31,6 +30,7 @@ import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; +import com.baeldung.web.dto.Foo; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java similarity index 96% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java index 7f250653ab..c6929da818 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java @@ -1,13 +1,10 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import java.util.Arrays; -import org.baeldung.config.converter.KryoHttpMessageConverter; -import org.baeldung.web.dto.Foo; -import org.baeldung.web.dto.FooProtos; import org.junit.Assert; import org.junit.Test; import org.springframework.http.HttpEntity; @@ -18,6 +15,10 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; import org.springframework.web.client.RestTemplate; +import com.baeldung.config.converter.KryoHttpMessageConverter; +import com.baeldung.web.dto.Foo; +import com.baeldung.web.dto.FooProtos; + /** * Integration Test class. Tests methods hits the server's rest services. */ diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java similarity index 99% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java index b920ed38da..49ac651da2 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java b/spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java similarity index 98% rename from spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java rename to spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java index bb3919eacc..86b35d2b4e 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.web.util; +package com.baeldung.web.util; import java.util.List; diff --git a/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest/README.md b/spring-rest/README.md index 5d7894cdf8..54b47604d4 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -6,7 +6,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) -- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) - [Binary Data Formats in a Spring REST API](http://www.baeldung.com/spring-rest-api-with-binary-data-formats) - [Guide to UriComponentsBuilder in Spring](http://www.baeldung.com/spring-uricomponentsbuilder) - [Introduction to FindBugs](http://www.baeldung.com/intro-to-findbugs) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 36934af101..670bac9805 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -93,13 +93,6 @@ commons-lang3 - - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - - org.hamcrest @@ -270,7 +263,6 @@ 4.0.0 1.4 3.1.0 - 3.5 20.0 @@ -280,8 +272,6 @@ 3.0.4 3.0.0 false - - 3.4.1 2.2.0 3.5.11 diff --git a/spring-rest/src/test/java/com/baeldung/SpringContextTest.java b/spring-rest/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4b2024e207 --- /dev/null +++ b/spring-rest/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,24 @@ +package com.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.custom.CustomApplication; +import com.baeldung.produceimage.ImageApplication; +import com.baeldung.propertyeditor.PropertyEditorApplication; +import com.baeldung.responseheaders.ResponseHeadersApplication; +import com.baeldung.sampleapp.config.MainApplication; +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.UploadApplication.class, + MainApplication.class}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-resttemplate/README.md b/spring-resttemplate/README.md index c2c4965231..97a89ff7aa 100644 --- a/spring-resttemplate/README.md +++ b/spring-resttemplate/README.md @@ -10,3 +10,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) - [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template) - [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json) +- [Download a Large File Through a Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-download-large-file) diff --git a/spring-resttemplate/pom.xml b/spring-resttemplate/pom.xml index 06d4eed9fc..ae5cfed4c9 100644 --- a/spring-resttemplate/pom.xml +++ b/spring-resttemplate/pom.xml @@ -284,7 +284,6 @@ - 3.5 1.4.9 diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java b/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e52d249f0b --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.resttemplate.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java index a54c124d5f..ff3034a50d 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -188,7 +188,7 @@ public class RestTemplateBasicLiveTest { final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() .getId(); final HttpEntity requestUpdate = new HttpEntity<>(updatedResource, headers); - final ClientHttpRequestFactory requestFactory = getSimpleClientHttpRequestFactory(); + final ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); final RestTemplate template = new RestTemplate(requestFactory); template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); template.patchForObject(resourceUrl, requestUpdate, Void.class); @@ -262,7 +262,7 @@ public class RestTemplateBasicLiveTest { // Simply setting restTemplate timeout using ClientHttpRequestFactory - ClientHttpRequestFactory getSimpleClientHttpRequestFactory() { + ClientHttpRequestFactory getClientHttpRequestFactory() { final int timeout = 5; final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); clientHttpRequestFactory.setConnectTimeout(timeout * 1000); diff --git a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java b/spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java new file mode 100644 index 0000000000..21639818db --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java @@ -0,0 +1,109 @@ +package org.baeldung.resttemplate; + +import org.assertj.core.api.Assertions; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.util.StreamUtils; +import org.springframework.web.client.RestTemplate; + +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.List; + +public class LargeFileDownloadIntegrationTest { + + static String FILE_URL = "http://ovh.net/files/1Mio.dat"; + + RestTemplate restTemplate; + + @Before + public void setUp() { + restTemplate = new RestTemplate(); + } + + @Test + public void givenResumableUrl_whenUrlCalledByHeadOption_thenExpectHeadersAvailable() { + HttpHeaders headers = restTemplate.headForHeaders(FILE_URL); + Assertions + .assertThat(headers.get("Accept-Ranges")) + .contains("bytes"); + Assertions + .assertThat(headers.getContentLength()) + .isGreaterThan(0); + } + + @Test + public void givenResumableUrl_whenDownloadCompletely_thenExpectCorrectFileSize() { + HttpHeaders headers = restTemplate.headForHeaders(FILE_URL); + long contentLength = headers.getContentLength(); + File file = restTemplate.execute(FILE_URL, HttpMethod.GET, null, clientHttpResponse -> { + File ret = File.createTempFile("download", "tmp"); + StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret)); + return ret; + }); + + Assert.assertNotNull(file); + Assertions + .assertThat(file.length()) + .isEqualTo(contentLength); + } + + @Test + public void givenResumableUrl_whenDownloadRange_thenExpectFileSizeEqualOrLessThanRange() { + int range = 10; + File file = restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest + .getHeaders() + .set("Range", String.format("bytes=0-%d", range - 1)), clientHttpResponse -> { + File ret = File.createTempFile("download", "tmp"); + StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret)); + return ret; + }); + + Assert.assertNotNull(file); + Assertions + .assertThat(file.length()) + .isLessThanOrEqualTo(range); + } + + @Test + public void givenResumableUrl_whenPauseDownloadAndResume_thenExpectCorrectFileSize() { + + int range = 10; + + HttpHeaders headers = restTemplate.headForHeaders(FILE_URL); + long contentLength = headers.getContentLength(); + + File file = restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest + .getHeaders() + .set("Range", String.format("bytes=0-%d", range - 1)), clientHttpResponse -> { + File ret = File.createTempFile("download", "tmp"); + StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret)); + return ret; + }); + + Assert.assertNotNull(file); + + Assertions + .assertThat(file.length()) + .isLessThanOrEqualTo(range); + + restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest + .getHeaders() + .set("Range", String.format("bytes=%d-%d", file.length(), contentLength)), clientHttpResponse -> { + StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(file, true)); + return file; + }); + + Assertions + .assertThat(file.length()) + .isEqualTo(contentLength); + + } + +} diff --git a/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..74f26e2e5a --- /dev/null +++ b/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-angular/README.md b/spring-security-angular/README.md index 49cd8dd62d..80312c4bab 100644 --- a/spring-security-angular/README.md +++ b/spring-security-angular/README.md @@ -1,3 +1,2 @@ ### Relevant Articles: - [Spring Security Login Page with Angular](https://www.baeldung.com/spring-security-login-angular) -- [Fixing 401s with CORS Preflights and Spring Security](https://www.baeldung.com/spring-security-cors-preflight) diff --git a/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e61d512bca --- /dev/null +++ b/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8fbaa7169b --- /dev/null +++ b/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextTest.java similarity index 90% rename from spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextTest.java index 66243ef00d..0afb3899db 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) -public class SpringContextIntegrationTest { +public class SpringContextTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-core/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-core/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1707c706ae --- /dev/null +++ b/spring-security-core/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java index 309ee3076d..009d9af9fc 100644 --- a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java +++ b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java @@ -80,7 +80,7 @@ public class TestMethodSecurity { @Test @WithMockUser(username = "JOHN", authorities = { "SYS_ADMIN" }) - public void givenAuthoritySysAdmin_whenCallGetUsernameInLowerCase_thenReturnUsername() { + public void givenAuthoritySysAdmin_whenCallGetUsernameLC_thenReturnUsername() { String username = userRoleService.getUsernameLC(); assertEquals("john", username); } diff --git a/spring-security-kerberos/pom.xml b/spring-security-kerberos/pom.xml index 35c4ba4926..d98d0ff508 100644 --- a/spring-security-kerberos/pom.xml +++ b/spring-security-kerberos/pom.xml @@ -7,12 +7,14 @@ 0.1-SNAPSHOT spring-security-kerberos war + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT ../parent-boot-1 + org.springframework.boot @@ -50,6 +52,7 @@ test + diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java index f2da5af92c..739e4d3417 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java @@ -1,57 +1,12 @@ package org.baeldung.custom.config; -import org.baeldung.custom.security.MyUserDetailsService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -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.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration -@EnableWebSecurity -@ComponentScan("org.baeldung.security") -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private MyUserDetailsService userDetailsService; - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(authenticationProvider()); - } - - @Override - public void configure(WebSecurity web) throws Exception { - web.ignoring().antMatchers("/resources/**"); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http.authorizeRequests() - .antMatchers("/login").permitAll() - .antMatchers("/admin").hasRole("ADMIN") - .anyRequest().authenticated() - .and().formLogin().permitAll() - .and().csrf().disable(); - ; - // @formatter:on - } - - @Bean - public DaoAuthenticationProvider authenticationProvider() { - final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); - authProvider.setUserDetailsService(userDetailsService); - authProvider.setPasswordEncoder(encoder()); - return authProvider; - } +public class SecurityConfig { @Bean public PasswordEncoder encoder() { diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java index 6572954427..74de45d1a8 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java @@ -3,14 +3,16 @@ package org.baeldung.custom.web; import org.baeldung.custom.persistence.dao.OrganizationRepository; import org.baeldung.custom.persistence.model.Foo; import org.baeldung.custom.persistence.model.Organization; +import org.baeldung.custom.security.MyUserPrincipal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; +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.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @@ -23,14 +25,14 @@ public class MainController { // @PostAuthorize("hasPermission(returnObject, 'read')") @PreAuthorize("hasPermission(#id, 'Foo', 'read')") - @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @GetMapping("/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { return new Foo("Sample"); } @PreAuthorize("hasPermission(#foo, 'write')") - @RequestMapping(method = RequestMethod.POST, value = "/foos") + @PostMapping("/foos") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo create(@RequestBody final Foo foo) { @@ -40,7 +42,7 @@ public class MainController { // @PreAuthorize("hasAuthority('FOO_READ_PRIVILEGE')") - @RequestMapping(method = RequestMethod.GET, value = "/foos") + @GetMapping("/foos") @ResponseBody public Foo findFooByName(@RequestParam final String name) { return new Foo(name); @@ -49,10 +51,18 @@ public class MainController { // @PreAuthorize("isMember(#id)") - @RequestMapping(method = RequestMethod.GET, value = "/organizations/{id}") + @GetMapping("/organizations/{id}") @ResponseBody public Organization findOrgById(@PathVariable final long id) { - return organizationRepository.findById(id).orElse(null); + return organizationRepository.findById(id) + .orElse(null); + } + + @PreAuthorize("hasPermission(#id, 'Foo', 'read')") + @GetMapping("/user") + @ResponseBody + public MyUserPrincipal retrieveUserDetails(@AuthenticationPrincipal MyUserPrincipal principal) { + return principal; } } diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..2041249b71 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.custom.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java index fb25175902..d16acc729a 100644 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java @@ -1,76 +1,89 @@ package org.baeldung.web; -import static org.junit.Assert.assertEquals; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.apache.http.HttpHeaders; import org.baeldung.custom.Application; -import org.baeldung.custom.config.MvcConfig; -import org.baeldung.custom.config.SecurityConfig; -import org.baeldung.custom.persistence.dao.UserRepository; -import org.baeldung.custom.persistence.model.User; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.baeldung.custom.persistence.model.Foo; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -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.crypto.password.PasswordEncoder; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.security.test.context.support.WithUserDetails; +import org.springframework.test.web.servlet.MockMvc; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = {Application.class}) -@WebAppConfiguration +import com.fasterxml.jackson.databind.ObjectMapper; + +@SpringBootTest(classes = { Application.class }) +@AutoConfigureMockMvc public class CustomUserDetailsServiceIntegrationTest { - private static final String USERNAME = "user"; - private static final String PASSWORD = "pass"; - private static final String USERNAME2 = "user2"; - @Autowired - private UserRepository myUserRepository; - - @Autowired - private AuthenticationProvider authenticationProvider; - - @Autowired - private PasswordEncoder passwordEncoder; - - // + private MockMvc mvc; @Test - public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { - User user = new User(); - user.setUsername(USERNAME); - user.setPassword(passwordEncoder.encode(PASSWORD)); - - myUserRepository.save(user); - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); - - assertEquals(authentication.getName(), USERNAME); + @WithUserDetails("john") + public void givenUserWithReadPermissions_whenRequestUserInfo_thenRetrieveUserData() throws Exception { + this.mvc.perform(get("/user").with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.user.privileges[0].name").value("FOO_READ_PRIVILEGE")) + .andExpect(jsonPath("$.user.organization.name").value("FirstOrg")) + .andExpect(jsonPath("$.user.username").value("john")); } - @Test(expected = BadCredentialsException.class) - public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { - User user = new User(); - user.setUsername(USERNAME); - user.setPassword(passwordEncoder.encode(PASSWORD)); - - myUserRepository.save(user); - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); - authenticationProvider.authenticate(auth); + @Test + @WithUserDetails("tom") + public void givenUserWithWritePermissions_whenRequestUserInfo_thenRetrieveUserData() throws Exception { + this.mvc.perform(get("/user").with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.user.privileges").isArray()) + .andExpect(jsonPath("$.user.organization.name").value("SecondOrg")) + .andExpect(jsonPath("$.user.username").value("tom")); } - // + @Test + @WithUserDetails("john") + public void givenUserWithReadPermissions_whenRequestFoo_thenRetrieveSampleFoo() throws Exception { + this.mvc.perform(get("/foos/1").with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.name").value("Sample")); + } - @After - public void tearDown() { - myUserRepository.removeUserByUsername(USERNAME); + @Test + @WithAnonymousUser + public void givenAnonymous_whenRequestFoo_thenRetrieveUnauthorized() throws Exception { + this.mvc.perform(get("/foos/1").with(csrf())) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithUserDetails("john") + public void givenUserWithReadPermissions_whenCreateNewFoo_thenForbiddenStatusRetrieved() throws Exception { + this.mvc.perform(post("/foos").with(csrf()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .content(asJsonString(new Foo()))) + .andExpect(status().isForbidden()); + } + + @Test + @WithUserDetails("tom") + public void givenUserWithWritePermissions_whenCreateNewFoo_thenOkStatusRetrieved() throws Exception { + this.mvc.perform(post("/foos").with(csrf()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .content(asJsonString(new Foo()))) + .andExpect(status().isCreated()); + } + + private static String asJsonString(final Object obj) throws Exception { + final ObjectMapper mapper = new ObjectMapper(); + final String jsonContent = mapper.writeValueAsString(obj); + return jsonContent; } } diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index 4e932f3245..3bae514bc1 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -194,10 +194,8 @@ 19.0 - 3.5 - 2.6 1.6.1 diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5ee80d856a --- /dev/null +++ b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index cf1de1730d..0baaea15ef 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -196,13 +196,11 @@ 19.0 - 3.5 4.4.5 4.5.2 - 2.6 1.6.1 diff --git a/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..cd2b796308 --- /dev/null +++ b/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-jsonview/pom.xml b/spring-security-mvc-jsonview/pom.xml index 8fa7b4ffb5..a7f668ae8b 100644 --- a/spring-security-mvc-jsonview/pom.xml +++ b/spring-security-mvc-jsonview/pom.xml @@ -111,7 +111,7 @@ javax.servlet javax.servlet-api - ${javax.servlet.version} + ${javax.servlet-api.version} provided @@ -206,12 +206,6 @@ - - 3.1.0 - 1.2 - - - 2.6 1.6.1 2.4.0 diff --git a/spring-security-mvc-jsonview/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-mvc-jsonview/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b1a3de714e --- /dev/null +++ b/spring-security-mvc-jsonview/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.spring.AppConfig; +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 = AppConfig.class) +@WebAppConfiguration +public class SpringContextTest { + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..30ba7671d8 --- /dev/null +++ b/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index 02ed0e36f2..1ca11bc1ab 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -175,7 +175,6 @@ - 2.6 1.6.1 diff --git a/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4cf3b736ea --- /dev/null +++ b/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@WebAppConfiguration +public class SpringContextTest { + @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 5e987dcb77..2f7989d573 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -99,7 +99,7 @@ javax.servlet javax.servlet-api - ${javax.servlet.version} + ${javax.servlet-api.version} provided @@ -200,15 +200,10 @@ 9.4.1212 - - 3.1.0 - 1.2 - 19.0 - 2.6 1.6.1 1.5.10.RELEASE diff --git a/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8113ed0fbe --- /dev/null +++ b/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index c0e1527a24..b55ce70517 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -8,10 +8,10 @@ war - com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../parent-spring-4 + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -19,74 +19,26 @@ - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} + org.springframework.boot + spring-boot-starter-security org.springframework.security spring-security-taglibs - ${org.springframework.security.version} - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - + org.springframework.boot + spring-boot-starter-web - org.springframework - spring-context - ${spring.version} + org.apache.tomcat.embed + tomcat-embed-jasper - org.springframework - spring-jdbc - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-aop - ${spring.version} - - - org.springframework - spring-tx - ${spring.version} - - - org.springframework - spring-expression - ${spring.version} - - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} + org.springframework.boot + spring-boot-starter-tomcat @@ -94,14 +46,12 @@ javax.servlet javax.servlet-api - ${javax.servlet-api.version} provided javax.servlet jstl - ${jstl.version} runtime @@ -117,7 +67,6 @@ org.springframework.boot spring-boot-starter-test - 1.5.10.RELEASE test @@ -166,14 +115,10 @@ - - 4.2.6.RELEASE - 3.0.2 - 2.6 1.6.1 diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java b/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java new file mode 100644 index 0000000000..9e52f0430a --- /dev/null +++ b/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringSessionApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringSessionApplication.class, args); + } +} diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java index 9e9c240181..b9f50ded73 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java @@ -5,13 +5,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -21,7 +21,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/anonymous.html"); diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java index deeea78e4e..b7996ebf18 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -8,6 +8,8 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.session.HttpSessionEventPublisher; @@ -24,9 +26,9 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(final AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.inMemoryAuthentication() - .withUser("user1").password("user1Pass").roles("USER") + .withUser("user1").password(passwordEncoder().encode("user1Pass")).roles("USER") .and() - .withUser("admin1").password("admin1Pass").roles("ADMIN"); + .withUser("admin1").password(passwordEncoder().encode("admin1Pass")).roles("ADMIN"); // @formatter:on } @@ -68,5 +70,10 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml index e8aa2f76bc..42ff4c2186 100644 --- a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ diff --git a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5ee80d856a --- /dev/null +++ b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index f1d28355fd..f799a7fa9f 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -78,7 +78,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} @@ -186,7 +186,6 @@ 5.2.10.Final 4.2.3.RELEASE 1.11.3.RELEASE - 1.4.196 1.2.3 diff --git a/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7b9c738904 --- /dev/null +++ b/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-openid/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-openid/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..fa346b2b31 --- /dev/null +++ b/spring-security-openid/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-react/pom.xml b/spring-security-react/pom.xml index c7b7c85be8..40c284af7f 100644 --- a/spring-security-react/pom.xml +++ b/spring-security-react/pom.xml @@ -169,10 +169,8 @@ 19.0 - 3.5 - 2.6 2.7 1.6 9.4.11.v20180605 diff --git a/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9cc52b4726 --- /dev/null +++ b/spring-security-react/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 8a90247386..78bab83db5 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -279,7 +279,6 @@ 19.0 - 2.6 1.6.1 diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f54cbf3b7b --- /dev/null +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 2180b917e5..4bab9b9d95 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -206,7 +206,6 @@ 19.0 - 3.5 1.2 diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/child/MethodSecurityConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/child/MethodSecurityConfig.java new file mode 100644 index 0000000000..bc9a9f161b --- /dev/null +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/child/MethodSecurityConfig.java @@ -0,0 +1,37 @@ +package org.baeldung.config.child; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.intercept.RunAsImplAuthenticationProvider; +import org.springframework.security.access.intercept.RunAsManager; +import org.springframework.security.access.intercept.RunAsManagerImpl; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; + + +@Configuration +@EnableGlobalMethodSecurity(securedEnabled = true) +public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { + + @Override + protected RunAsManager runAsManager() { + RunAsManagerImpl runAsManager = new RunAsManagerImpl(); + runAsManager.setKey("MyRunAsKey"); + return runAsManager; + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(runAsAuthenticationProvider()); + } + + @Bean + public AuthenticationProvider runAsAuthenticationProvider() { + RunAsImplAuthenticationProvider authProvider = new RunAsImplAuthenticationProvider(); + authProvider.setKey("MyRunAsKey"); + return authProvider; + } +} \ No newline at end of file diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/service/RunAsService.java b/spring-security-rest-custom/src/main/java/org/baeldung/service/RunAsService.java new file mode 100644 index 0000000000..a6320f8b81 --- /dev/null +++ b/spring-security-rest-custom/src/main/java/org/baeldung/service/RunAsService.java @@ -0,0 +1,17 @@ +package org.baeldung.service; + +import org.springframework.security.access.annotation.Secured; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; + +@Service +public class RunAsService { + + @Secured({ "ROLE_RUN_AS_REPORTER" }) + public Authentication getCurrentUser() { + Authentication authentication = + SecurityContextHolder.getContext().getAuthentication(); + return authentication; + } +} \ No newline at end of file diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/RunAsController.java b/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/RunAsController.java new file mode 100644 index 0000000000..08f39aa5f2 --- /dev/null +++ b/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/RunAsController.java @@ -0,0 +1,23 @@ +package org.baeldung.web.controller; + +import org.springframework.security.access.annotation.Secured; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + + +@Controller +@RequestMapping("/runas") +public class RunAsController { + + @Secured({ "ROLE_USER", "RUN_AS_REPORTER" }) + @RequestMapping + @ResponseBody + public String tryRunAs() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + return "Current User Authorities inside this RunAS method only " + + auth.getAuthorities().toString(); + } +} diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java b/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java index 83c0292d98..fbcb9b979e 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java @@ -10,4 +10,9 @@ public class ViewController { public String index() { return "index"; } + + @RequestMapping({ "/runashome" }) + public String run() { + return "runas"; + } } diff --git a/spring-security-rest-custom/src/main/webapp/WEB-INF/templates/runas.html b/spring-security-rest-custom/src/main/webapp/WEB-INF/templates/runas.html new file mode 100644 index 0000000000..c7c3b2e0e4 --- /dev/null +++ b/spring-security-rest-custom/src/main/webapp/WEB-INF/templates/runas.html @@ -0,0 +1,23 @@ + + + + Current user authorities: + user +
+ + Generate Report As Super User + + + + + \ No newline at end of file diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index af38c1ffef..a66909a68e 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -271,7 +271,6 @@ 26.0-jre - 3.5 1.3.2 diff --git a/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java b/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java new file mode 100644 index 0000000000..7d40b9bb8d --- /dev/null +++ b/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java @@ -0,0 +1,14 @@ +package org.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class CustomController { + + @RequestMapping(value = "/custom", method = RequestMethod.POST) + public String custom() { + return "custom"; + } +} \ No newline at end of file diff --git a/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d984cf5c35 --- /dev/null +++ b/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f677f683b2 --- /dev/null +++ b/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.config.AuthorizationServerApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AuthorizationServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..61a2a022ed --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +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.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..61a2a022ed --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +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.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5c65dd3e8a --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5c65dd3e8a --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/README.md b/spring-session/README.md index 505d043e75..c9875beadf 100644 --- a/spring-session/README.md +++ b/spring-session/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Guide to Spring Session](https://www.baeldung.com/spring-session) - [Spring Session with JDBC](https://www.baeldung.com/spring-session-jdbc) +- [Spring Session with MongoDB](https://www.baeldung.com/spring-session-mongodb) diff --git a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b69855ba38 --- /dev/null +++ b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-mongodb/pom.xml b/spring-session/spring-session-mongodb/pom.xml index 16fbaccc84..dc055ff32d 100644 --- a/spring-session/spring-session-mongodb/pom.xml +++ b/spring-session/spring-session-mongodb/pom.xml @@ -42,11 +42,6 @@
- - 2.1.3.RELEASE - 2.1.5.RELEASE - - @@ -56,4 +51,9 @@ + + 2.1.3.RELEASE + 2.1.5.RELEASE + + \ No newline at end of file diff --git a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..307d31a809 --- /dev/null +++ b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import com.baeldung.springsessionmongodb.SpringSessionMongoDBApplication; +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 = SpringSessionMongoDBApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..994f93c24f --- /dev/null +++ b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java b/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ff22398ca4 --- /dev/null +++ b/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index ba05eddf5d..e155a0f6b2 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -13,11 +13,6 @@ ../parent-boot-2 - - 1.8 - 2.1.2.RELEASE - - @@ -66,4 +61,8 @@ + + 2.1.2.RELEASE + + diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index e948c908d4..655e885568 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -94,8 +94,4 @@ - - 3.3.2 - - \ No newline at end of file diff --git a/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java b/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..cfd8759c52 --- /dev/null +++ b/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +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.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-spel/src/test/java/org/baeldung/SpringContextTest.java b/spring-spel/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e25c1bf8e4 --- /dev/null +++ b/spring-spel/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java b/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1e847c0d65 --- /dev/null +++ b/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-static-resources/README.md b/spring-static-resources/README.md index c12e0272d4..64f017b5dd 100644 --- a/spring-static-resources/README.md +++ b/spring-static-resources/README.md @@ -2,3 +2,4 @@ - [Cachable Static Assets with Spring MVC](http://www.baeldung.com/cachable-static-assets-with-spring-mvc) - [Minification of JS and CSS Assets with Maven](http://www.baeldung.com/maven-minification-of-js-and-css-assets) - [Serve Static Resources with Spring](http://www.baeldung.com/spring-mvc-static-resources) +- [Load a Resource as a String in Spring](https://www.baeldung.com/spring-load-resource-as-string) diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml index f01e807919..b8068814ba 100644 --- a/spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -140,6 +140,13 @@ handlebars ${handlebars.version} + + + + commons-io + commons-io + ${commons-io.version} + org.springframework diff --git a/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/LoadResourceConfig.java b/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/LoadResourceConfig.java new file mode 100644 index 0000000000..32b9ba84d0 --- /dev/null +++ b/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/LoadResourceConfig.java @@ -0,0 +1,15 @@ +package com.baeldung.loadresourceasstring; + + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class LoadResourceConfig { + + @Bean + public String resourceString() { + return ResourceReader.readFileToString("resource.txt"); + } + +} diff --git a/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/ResourceReader.java b/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/ResourceReader.java new file mode 100644 index 0000000000..7bc1babe91 --- /dev/null +++ b/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/ResourceReader.java @@ -0,0 +1,30 @@ +package com.baeldung.loadresourceasstring; + +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.util.FileCopyUtils; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.UncheckedIOException; + +import static java.nio.charset.StandardCharsets.UTF_8; + + +public class ResourceReader { + + public static String readFileToString(String path) { + ResourceLoader resourceLoader = new DefaultResourceLoader(); + Resource resource = resourceLoader.getResource(path); + return asString(resource); + } + + public static String asString(Resource resource) { + try (Reader reader = new InputStreamReader(resource.getInputStream(), UTF_8)) { + return FileCopyUtils.copyToString(reader); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/spring-static-resources/src/main/resources/resource.txt b/spring-static-resources/src/main/resources/resource.txt new file mode 100644 index 0000000000..e78cfa90c2 --- /dev/null +++ b/spring-static-resources/src/main/resources/resource.txt @@ -0,0 +1 @@ +This is a resource text file. This file will be loaded as a resource and use its contents as a string. \ No newline at end of file diff --git a/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0dcbba3221 --- /dev/null +++ b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package com.baeldung; + +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.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SecSecurityConfig.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } +} diff --git a/spring-static-resources/src/test/java/com/baeldung/loadresourceasstring/LoadResourceAsStringIntegrationTest.java b/spring-static-resources/src/test/java/com/baeldung/loadresourceasstring/LoadResourceAsStringIntegrationTest.java new file mode 100644 index 0000000000..c16c1a9720 --- /dev/null +++ b/spring-static-resources/src/test/java/com/baeldung/loadresourceasstring/LoadResourceAsStringIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.loadresourceasstring; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.util.FileCopyUtils; + +import java.io.InputStreamReader; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = LoadResourceConfig.class) +public class LoadResourceAsStringIntegrationTest { + + private static final String EXPECTED_RESOURCE_VALUE = "This is a resource text file. This file will be loaded as a " + "resource and use its contents as a string."; + + @Value("#{T(com.baeldung.loadresourceasstring.ResourceReader).readFileToString('classpath:resource.txt')}") + private String resourceStringUsingSpel; + + @Autowired + @Qualifier("resourceString") + private String resourceString; + + @Autowired + private ResourceLoader resourceLoader; + + @Test + public void givenUsingResourceLoadAndFileCopyUtils_whenConvertingAResourceToAString_thenCorrect() { + Resource resource = resourceLoader.getResource("classpath:resource.txt"); + assertEquals(EXPECTED_RESOURCE_VALUE, ResourceReader.asString(resource)); + } + + @Test + public void givenUsingResourceStringBean_whenConvertingAResourceToAString_thenCorrect() { + assertEquals(EXPECTED_RESOURCE_VALUE, resourceString); + } + + @Test + public void givenUsingSpel_whenConvertingAResourceToAString_thenCorrect() { + assertEquals(EXPECTED_RESOURCE_VALUE, resourceStringUsingSpel); + } + + + + +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..79b2b7fa88 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-thymeleaf-2/pom.xml b/spring-thymeleaf-2/pom.xml new file mode 100644 index 0000000000..1b95cac43c --- /dev/null +++ b/spring-thymeleaf-2/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + spring-thymeleaf-2 + spring-thymeleaf-2 + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + spring-thymeleaf-2 + + + + 1.8 + 1.8 + + diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/Application.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/Application.java new file mode 100644 index 0000000000..2ccca82497 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/Color.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/Color.java new file mode 100644 index 0000000000..9e223d1323 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/Color.java @@ -0,0 +1,22 @@ +package com.baeldung.thymeleaf.enums; + +public enum Color { + BLACK("Black"), + BLUE("Blue"), + RED("Red"), + YELLOW("Yellow"), + GREEN("Green"), + ORANGE("Orange"), + PURPLE("Purple"), + WHITE("White"); + + private final String displayValue; + + private Color(String displayValue) { + this.displayValue = displayValue; + } + + public String getDisplayValue() { + return displayValue; + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/Widget.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/Widget.java new file mode 100644 index 0000000000..dc6504c3bc --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/Widget.java @@ -0,0 +1,27 @@ +package com.baeldung.thymeleaf.enums; + +public class Widget { + private String name; + private Color color; + + 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; + } + + @Override + public String toString() { + return "Widget [name=" + name + ", color=" + color + "]"; + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/WidgetController.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/WidgetController.java new file mode 100644 index 0000000000..c66464d75b --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/WidgetController.java @@ -0,0 +1,23 @@ +package com.baeldung.thymeleaf.enums; + +import javax.validation.Valid; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.ui.Model; + +@Controller +public class WidgetController { + @GetMapping("/widget/add") + public String addWidget(@ModelAttribute Widget widget) { + return "enums/new"; + } + + @PostMapping("/widget/add") + public String saveWidget(@Valid Widget widget, Model model) { + model.addAttribute("widget", widget); + return "enums/view"; + } +} diff --git a/spring-thymeleaf-2/src/main/resources/templates/enums/new.html b/spring-thymeleaf-2/src/main/resources/templates/enums/new.html new file mode 100644 index 0000000000..7ac4665171 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/enums/new.html @@ -0,0 +1,19 @@ + + + + +Enums in Thymeleaf + + +
+

Add New Widget

+ + + + + +
+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/enums/view.html b/spring-thymeleaf-2/src/main/resources/templates/enums/view.html new file mode 100644 index 0000000000..f766f66277 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/enums/view.html @@ -0,0 +1,30 @@ + + + + +Enums in Thymeleaf + + +

View Widget

+
+ + +
+
+ + +
+
+ This color screams danger. +
+
+ Green is for go. +
+
+ Alert + Warning + Caution + All Good +
+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java b/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1ff1c52c68 --- /dev/null +++ b/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-userservice/.springBeans b/spring-userservice/.springBeans deleted file mode 100644 index ff32b84d3b..0000000000 --- a/spring-userservice/.springBeans +++ /dev/null @@ -1,15 +0,0 @@ - - - 1 - - - - - - - - - - - - diff --git a/spring-userservice/README.md b/spring-userservice/README.md deleted file mode 100644 index 097afc5fc1..0000000000 --- a/spring-userservice/README.md +++ /dev/null @@ -1 +0,0 @@ -spring-userservice is using a in memory derby db. Right click -> run on server to run the project \ No newline at end of file diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml deleted file mode 100644 index e6e8553c80..0000000000 --- a/spring-userservice/pom.xml +++ /dev/null @@ -1,244 +0,0 @@ - - 4.0.0 - spring-userservice - spring-userservice - 0.0.1-SNAPSHOT - war - spring-userservice - - - com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../parent-spring-4 - - - - - - - - org.springframework - spring-orm - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - - - - org.hibernate - hibernate-entitymanager - ${hibernate.version} - - - org.hibernate - hibernate-ehcache - ${hibernate.version} - - - xml-apis - xml-apis - ${xml-apis.version} - - - org.javassist - javassist - ${javassist.version} - - - mysql - mysql-connector-java - ${mysql-connector-java.version} - runtime - - - org.springframework.data - spring-data-jpa - ${spring-data-jpa.version} - - - com.h2database - h2 - ${h2.version} - - - - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - - - - com.google.guava - guava - ${guava.version} - - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - test - - - - org.springframework - spring-test - ${spring.version} - test - - - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - - org.springframework.security - spring-security-core - ${org.springframework.security.version} - - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - - - - org.apache.derby - derby - ${derby.version} - - - org.apache.derby - derbyclient - ${derby.version} - - - org.apache.derby - derbynet - ${derby.version} - - - org.apache.derby - derbytools - ${derby.version} - - - taglibs - standard - ${taglibs-standard.version} - - - org.springframework.security - spring-security-taglibs - ${org.springframework.security.version} - - - javax.servlet.jsp.jstl - jstl-api - ${jstl.version} - - - org.springframework.boot - spring-boot-test - ${spring-boot.version} - - - org.springframework.boot - spring-boot - ${spring-boot.version} - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - - - spring-userservice - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - - - - - - - 4.2.6.RELEASE - 1.5.14.RELEASE - 3.21.0-GA - - - 5.2.10.Final - 5.1.40 - 1.10.5.RELEASE - 10.13.1.1 - - - 5.3.3.Final - 2.2.5 - 1.1.2 - - - 19.0 - 3.5 - 1.4.01 - - - 2.6 - - - \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java deleted file mode 100644 index 4a9e737a92..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.custom.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 = { "org.baeldung.security" }) -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - - registry.addViewController("/"); - registry.addViewController("/index"); - registry.addViewController("/login"); - registry.addViewController("/register"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - - return bean; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java deleted file mode 100644 index 6be7053b78..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.baeldung.custom.config; - -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.baeldung.user.dao.MyUserDAO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.google.common.base.Preconditions; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-derby.properties" }) -public class PersistenceDerbyJPAConfig { - - @Autowired - private Environment env; - - public PersistenceDerbyJPAConfig() { - super(); - } - - // beans - - @Bean - public LocalContainerEntityManagerFactoryBean myEmf() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - em.setJpaProperties(additionalProperties()); - - return em; - } - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(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 EntityManagerFactory emf) { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(emf); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); - return hibernateProperties; - } - - @Bean - public MyUserDAO myUserDAO() { - final MyUserDAO myUserDAO = new MyUserDAO(); - return myUserDAO; - } -} \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java deleted file mode 100644 index 44df02980f..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.baeldung.custom.config; - -import org.baeldung.security.MyUserDetailsService; -import org.baeldung.user.service.MyUserService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -@EnableWebSecurity -@Profile("!https") -public class SecSecurityConfig extends WebSecurityConfigurerAdapter { - - public SecSecurityConfig() { - super(); - } - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.authenticationProvider(authenticationProvider()); - // @formatter:on - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http - .csrf().disable() - .authorizeRequests() - .antMatchers("/*").permitAll() - .and() - .formLogin() - .loginPage("/login") - .loginProcessingUrl("/login") - .defaultSuccessUrl("/",true) - .failureUrl("/login?error=true") - .and() - .logout() - .logoutUrl("/logout") - .deleteCookies("JSESSIONID") - .logoutSuccessUrl("/"); - // @formatter:on - } - - @Bean - public DaoAuthenticationProvider authenticationProvider() { - final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); - authProvider.setUserDetailsService(myUserDetailsService()); - authProvider.setPasswordEncoder(encoder()); - return authProvider; - } - - @Bean - public PasswordEncoder encoder() { - return new BCryptPasswordEncoder(11); - } - - @Bean - public MyUserDetailsService myUserDetailsService() { - return new MyUserDetailsService(); - } - - @Bean - public MyUserService myUserService() { - return new MyUserService(); - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java deleted file mode 100644 index 804d391641..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.baeldung.persistence.model; - -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(schema = "spring_custom_user_service") -public class MyUser { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private int id; - - @Column(unique = true, nullable = false) - private String username; - - @Column(nullable = false) - private String password; - - public MyUser() { - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(final String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(final String password) { - this.password = password; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java deleted file mode 100644 index fe97984af8..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.security; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; - -import org.baeldung.persistence.model.MyUser; -import org.baeldung.user.dao.MyUserDAO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; - -@Service("userDetailsService") -public class MyUserDetailsService implements UserDetailsService { - - @Autowired - MyUserDAO myUserDAO; - - @Override - public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { - final MyUser user = myUserDAO.findByUsername(username); - - if (user == null) { - throw new UsernameNotFoundException("No user found with username: " + username); - } - return new User(user.getUsername(), user.getPassword(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); - - } - -} diff --git a/spring-userservice/src/main/java/org/baeldung/security/UserController.java b/spring-userservice/src/main/java/org/baeldung/security/UserController.java deleted file mode 100644 index a4c15f7942..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/security/UserController.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.baeldung.security; - -import javax.annotation.Resource; - -import org.baeldung.user.service.MyUserService; -import org.baeldung.web.MyUserDto; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@Controller -public class UserController { - - @Resource - MyUserService myUserService; - - @RequestMapping(value = "/register", method = RequestMethod.POST) - public String registerUserAccount(final MyUserDto accountDto, final Model model) { - final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - model.addAttribute("name", auth.getName()); - try { - myUserService.registerNewUserAccount(accountDto); - model.addAttribute("message", "Registration successful"); - return "index"; - } catch (final Exception exc) { - model.addAttribute("message", "Registration failed"); - - return "index"; - } - } - - @RequestMapping(value = "/", method = RequestMethod.GET) - public String getHomepage(final Model model) { - final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - model.addAttribute("name", auth.getName()); - return "index"; - } - - @RequestMapping(value = "/register", method = RequestMethod.GET) - public String getRegister() { - return "register"; - } - - @RequestMapping(value = "/login", method = RequestMethod.GET) - public String getLogin() { - return "login"; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java deleted file mode 100644 index 834941b68b..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.baeldung.user.dao; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - -import org.baeldung.persistence.model.MyUser; -import org.springframework.stereotype.Repository; - -@Repository -public class MyUserDAO { - - @PersistenceContext - private EntityManager entityManager; - - public MyUser findByUsername(final String username) { - final Query query = entityManager.createQuery("from MyUser where username=:username", MyUser.class); - query.setParameter("username", username); - final List result = query.getResultList(); - if (result != null && result.size() > 0) { - return result.get(0); - } else - return null; - } - - public MyUser save(final MyUser user) { - entityManager.persist(user); - return user; - } - - public void removeUserByUsername(String username) { - final Query query = entityManager.createQuery("delete from MyUser where username=:username"); - query.setParameter("username", username); - query.executeUpdate(); - } - - public EntityManager getEntityManager() { - return entityManager; - } - - public void setEntityManager(final EntityManager entityManager) { - this.entityManager = entityManager; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java deleted file mode 100644 index 2ab44752c0..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.baeldung.user.service; - -import org.baeldung.persistence.model.MyUser; -import org.baeldung.user.dao.MyUserDAO; -import org.baeldung.web.MyUserDto; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class MyUserService { - - @Autowired - private PasswordEncoder passwordEncoder; - - @Autowired - MyUserDAO myUserDAO; - - public MyUser registerNewUserAccount(final MyUserDto accountDto) throws Exception { - if (usernameExists(accountDto.getUsername())) { - throw new Exception("There is an account with that username: " + accountDto.getUsername()); - } - final MyUser user = new MyUser(); - - user.setUsername(accountDto.getUsername()); - user.setPassword(passwordEncoder.encode(accountDto.getPassword())); - return myUserDAO.save(user); - } - - public MyUser getUserByUsername(final String username) { - final MyUser user = myUserDAO.findByUsername(username); - return user; - } - - public void removeUserByUsername(String username) { - myUserDAO.removeUserByUsername(username); - } - - private boolean usernameExists(final String username) { - final MyUser user = myUserDAO.findByUsername(username); - if (user != null) { - return true; - } - return false; - } - -} diff --git a/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java deleted file mode 100644 index 60a6848ea4..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.web; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; - -public class MyUserDto { - @NotNull - @Size(min = 1) - private String username; - - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(final String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(final String password) { - this.password = password; - } - -} diff --git a/spring-userservice/src/main/resources/persistence-derby.properties b/spring-userservice/src/main/resources/persistence-derby.properties deleted file mode 100644 index b76c5de12f..0000000000 --- a/spring-userservice/src/main/resources/persistence-derby.properties +++ /dev/null @@ -1,12 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver -jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true -jdbc.user=tutorialuser -jdbc.pass=tutorialpass - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.DerbyDialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=update -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF deleted file mode 100644 index 254272e1c0..0000000000 --- a/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Class-Path: - diff --git a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml deleted file mode 100644 index 48ef8a8c43..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /WEB-INF/views/ - - - .jsp - - - - - - - - - - - - - - - ${hibernate.hbm2ddl.auto} - ${hibernate.dialect} - ${hibernate.cache.use_second_level_cache} - ${hibernate.cache.use_query_cache} - - - - - - - - - - - - - - - - - - - diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp deleted file mode 100644 index 0c89257cd2..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp +++ /dev/null @@ -1,35 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> - - - - - -Welcome! - - - - - - - -Register -

- -Login - -

-${message } -

- -Hello, ${name }! -
-
-Logout -
- - - \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp deleted file mode 100644 index 29431f426d..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp +++ /dev/null @@ -1,29 +0,0 @@ -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> - - - - - -

Login

- -
- - - - - - - - - - - - - -
User:
Password:
- -
- Username or password invalid! - - \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp deleted file mode 100644 index e6e9d373a0..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp +++ /dev/null @@ -1,23 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> - - - - -Welcome! - - - - - -Register here:

-
-Username:
-Password:
- -
- - - \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/web.xml b/spring-userservice/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b526774179..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - Spring MVC Application - - - - - - mvc-dispatcher - org.springframework.web.servlet.DispatcherServlet - 1 - - - mvc-dispatcher - / - - - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - - - - index.jsp - - - \ No newline at end of file diff --git a/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-userservice/src/test/java/org/baeldung/SpringContextTest.java similarity index 92% rename from spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-userservice/src/test/java/org/baeldung/SpringContextTest.java index 825b89eb10..2853a955fa 100644 --- a/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-userservice/src/test/java/org/baeldung/SpringContextTest.java @@ -10,7 +10,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) -public class SpringContextIntegrationTest { +public class SpringContextTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java deleted file mode 100644 index 1cd38228b8..0000000000 --- a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.baeldung.userservice; - -import static org.junit.Assert.assertEquals; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.baeldung.custom.config.MvcConfig; -import org.baeldung.custom.config.PersistenceDerbyJPAConfig; -import org.baeldung.custom.config.SecSecurityConfig; -import org.baeldung.user.service.MyUserService; -import org.baeldung.web.MyUserDto; -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.AuthenticationProvider; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) -@WebAppConfiguration -public class CustomUserDetailsServiceIntegrationTest { - - private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); - - public static final String USERNAME = "user"; - public static final String PASSWORD = "pass"; - public static final String USERNAME2 = "user2"; - - @Autowired - MyUserService myUserService; - - @Autowired - AuthenticationProvider authenticationProvider; - - @Test - public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { - try { - MyUserDto userDTO = new MyUserDto(); - userDTO.setUsername(USERNAME); - userDTO.setPassword(PASSWORD); - - myUserService.registerNewUserAccount(userDTO); - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); - - assertEquals(authentication.getName(), USERNAME); - - } catch (Exception exc) { - LOG.log(Level.SEVERE, "Error creating account"); - } finally { - myUserService.removeUserByUsername(USERNAME); - } - } - - @Test(expected = BadCredentialsException.class) - public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { - try { - MyUserDto userDTO = new MyUserDto(); - userDTO.setUsername(USERNAME); - userDTO.setPassword(PASSWORD); - - try { - myUserService.registerNewUserAccount(userDTO); - } catch (Exception exc) { - LOG.log(Level.SEVERE, "Error creating account"); - } - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); - } finally { - myUserService.removeUserByUsername(USERNAME); - } - } - -} diff --git a/spring-vault/src/test/java/org/baeldung/SpringContextTest.java b/spring-vault/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..95abe622fa --- /dev/null +++ b/spring-vault/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java b/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4ce94ec16a --- /dev/null +++ b/spring-vertx/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextTest.java b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..88d29d5ac0 --- /dev/null +++ b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index fbbbdddbf7..a613f51c3f 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -39,10 +39,6 @@ 2.1.0.RELEASE - - 3.5 - - 2.6 \ No newline at end of file diff --git a/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextTest.java b/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..2a57d7aa07 --- /dev/null +++ b/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextTest.java b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..fd35ec0841 --- /dev/null +++ b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextTest.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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/struts-2/pom.xml b/struts-2/pom.xml index 7de688ff2c..1f7d6876d5 100644 --- a/struts-2/pom.xml +++ b/struts-2/pom.xml @@ -70,7 +70,6 @@ 2.5.5 2.5.8 4.3.6.RELEASE - 3.0.0 \ No newline at end of file diff --git a/tensorflow-java/pom.xml b/tensorflow-java/pom.xml index f9abde737c..84d2f6cf21 100644 --- a/tensorflow-java/pom.xml +++ b/tensorflow-java/pom.xml @@ -24,13 +24,13 @@ org.junit.jupiter junit-jupiter-api - ${junit.jupiter.version} + ${junit-jupiter.version} test org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test
@@ -46,6 +46,5 @@ 1.12.0 - 5.4.0 \ No newline at end of file diff --git a/testing-modules/README.md b/testing-modules/README.md index d69f07215e..b269f547ec 100644 --- a/testing-modules/README.md +++ b/testing-modules/README.md @@ -13,5 +13,3 @@ - [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) -- [Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) diff --git a/testing-modules/easy-random/pom.xml b/testing-modules/easy-random/pom.xml new file mode 100644 index 0000000000..93c0027f8f --- /dev/null +++ b/testing-modules/easy-random/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + easy-random + easy-random + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + ../../ + + + + + org.jeasy + easy-random-core + 4.0.0 + + + + \ No newline at end of file diff --git a/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java new file mode 100644 index 0000000000..ee4dc82771 --- /dev/null +++ b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java @@ -0,0 +1,17 @@ +package org.baeldung.easy.random.model; + +import java.util.StringJoiner; + +public class Department { + private String depName; + + public Department(String depName) { + this.depName = depName; + } + + @Override + public String toString() { + return new StringJoiner(", ", Department.class.getSimpleName() + "[", "]").add("depName='" + depName + "'") + .toString(); + } +} diff --git a/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java new file mode 100644 index 0000000000..ef63642ca2 --- /dev/null +++ b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java @@ -0,0 +1,70 @@ +package org.baeldung.easy.random.model; + +import java.util.*; + +public class Employee { + + private long id; + private String firstName; + private String lastName; + private Department department; + private Collection coworkers; + private Map quarterGrades; + + public Employee(long id, String firstName, String lastName, Department department) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.department = department; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Employee employee = (Employee) o; + return id == employee.id; + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public long getId() { + return id; + } + + public Department getDepartment() { + return department; + } + + public Collection getCoworkers() { + return Collections.unmodifiableCollection(coworkers); + } + + public Map getQuarterGrades() { + return Collections.unmodifiableMap(quarterGrades); + } + + @Override + public String toString() { + return new StringJoiner(", ", Employee.class.getSimpleName() + "[", "]").add("id=" + id) + .add("firstName='" + firstName + "'") + .add("lastName='" + lastName + "'") + .add("department=" + department) + .add("coworkers size=" + ((coworkers == null) ? 0 : coworkers.size())) + .add("quarterGrades=" + quarterGrades) + .toString(); + } +} diff --git a/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java new file mode 100644 index 0000000000..cb979be3b8 --- /dev/null +++ b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java @@ -0,0 +1,22 @@ +package org.baeldung.easy.random.model; + +import java.util.StringJoiner; + +public class Grade { + + private int grade; + + public Grade(int grade) { + this.grade = grade; + } + + public int getGrade() { + return grade; + } + + @Override + public String toString() { + return new StringJoiner(", ", Grade.class.getSimpleName() + "[", "]").add("grade=" + grade) + .toString(); + } +} diff --git a/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java new file mode 100644 index 0000000000..c941499993 --- /dev/null +++ b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java @@ -0,0 +1,30 @@ +package org.baeldung.easy.random.model; + +import java.util.StringJoiner; + +public class Person { + + private String firstName; + private String lastName; + private Integer age; + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public Integer getAge() { + return age; + } + + @Override + public String toString() { + return new StringJoiner(", ", Person.class.getSimpleName() + "[", "]").add("firstName='" + firstName + "'") + .add("lastName='" + lastName + "'") + .add("age=" + age) + .toString(); + } +} diff --git a/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java new file mode 100644 index 0000000000..c2868f09b8 --- /dev/null +++ b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java @@ -0,0 +1,50 @@ +package org.baeldung.easy.random.model; + +import java.time.LocalDate; +import java.util.Objects; +import java.util.StringJoiner; + +public class YearQuarter { + + private LocalDate startDate; + private LocalDate endDate; + + public YearQuarter(LocalDate startDate) { + this.startDate = startDate; + autoAdjustEndDate(); + } + + private void autoAdjustEndDate() { + endDate = startDate.plusMonths(3L); + } + + public LocalDate getStartDate() { + return startDate; + } + + public LocalDate getEndDate() { + return endDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + YearQuarter quarter = (YearQuarter) o; + return Objects.equals(startDate, quarter.startDate) && Objects.equals(endDate, quarter.endDate); + } + + @Override + public int hashCode() { + return Objects.hash(startDate, endDate); + } + + @Override + public String toString() { + return new StringJoiner(", ", YearQuarter.class.getSimpleName() + "[", "]").add("startDate=" + startDate) + .add("endDate=" + endDate) + .toString(); + } +} diff --git a/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java new file mode 100644 index 0000000000..05232ffcbc --- /dev/null +++ b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java @@ -0,0 +1,18 @@ +package org.baeldung.easy.random.randomizer; + +import org.baeldung.easy.random.model.YearQuarter; +import org.jeasy.random.api.Randomizer; + +import java.time.LocalDate; +import java.time.Month; + +public class YearQuarterRandomizer implements Randomizer { + + private LocalDate date = LocalDate.of(1990, Month.SEPTEMBER, 25); + + @Override + public YearQuarter getRandomValue() { + date = date.plusMonths(3); + return new YearQuarter(date); + } +} diff --git a/testing-modules/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java b/testing-modules/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java new file mode 100644 index 0000000000..9f7a23db66 --- /dev/null +++ b/testing-modules/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java @@ -0,0 +1,63 @@ +package org.baeldung.easy.random; + +import org.baeldung.easy.random.model.Employee; +import org.baeldung.easy.random.model.Person; +import org.baeldung.easy.random.model.YearQuarter; +import org.baeldung.easy.random.randomizer.YearQuarterRandomizer; +import org.jeasy.random.EasyRandom; +import org.jeasy.random.EasyRandomParameters; +import org.jeasy.random.FieldPredicates; +import org.jeasy.random.TypePredicates; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.*; + +class EasyRandomUnitTest { + + @Test + void givenDefaultConfiguration_thenGenerateSingleObject() { + EasyRandom generator = new EasyRandom(); + Person person = generator.nextObject(Person.class); + + assertNotNull(person.getAge()); + assertNotNull(person.getFirstName()); + assertNotNull(person.getLastName()); + } + + @Test + void givenDefaultConfiguration_thenGenerateObjectsList() { + EasyRandom generator = new EasyRandom(); + List persons = generator.objects(Person.class, 5) + .collect(Collectors.toList()); + + assertEquals(5, persons.size()); + } + + @Test + void givenCustomConfiguration_thenGenerateSingleEmployee() { + EasyRandomParameters parameters = new EasyRandomParameters(); + parameters.stringLengthRange(3, 3); + parameters.collectionSizeRange(5, 5); + parameters.excludeField(FieldPredicates.named("lastName").and(FieldPredicates.inClass(Employee.class))); + parameters.excludeType(TypePredicates.inPackage("not.existing.pkg")); + parameters.randomize(YearQuarter.class, new YearQuarterRandomizer()); + + EasyRandom generator = new EasyRandom(parameters); + Employee employee = generator.nextObject(Employee.class); + + assertEquals(3, employee.getFirstName().length()); + assertEquals(5, employee.getCoworkers().size()); + assertEquals(5, employee.getQuarterGrades().size()); + assertNotNull(employee.getDepartment()); + + assertNull(employee.getLastName()); + + for (YearQuarter key : employee.getQuarterGrades().keySet()) { + assertEquals(key.getStartDate(), key.getEndDate().minusMonths(3L)); + } + } + +} diff --git a/testing-modules/easymock/pom.xml b/testing-modules/easymock/pom.xml new file mode 100644 index 0000000000..ed9a077f67 --- /dev/null +++ b/testing-modules/easymock/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + easymock + easymock + http://maven.apache.org + + + com.baeldung + testing-modules + 1.0.0-SNAPSHOT + + + + + org.easymock + easymock + ${easymock.version} + test + + + + + UTF-8 + 4.0.2 + + diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ForecastProcessor.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ForecastProcessor.java new file mode 100644 index 0000000000..482e985e5b --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ForecastProcessor.java @@ -0,0 +1,28 @@ +package com.baeldung.testing.easymock; + +import java.math.BigDecimal; + +public class ForecastProcessor { + private WeatherService weatherService; + + public BigDecimal getMaximumTemperature(String locationName) { + + Location location = new Location(locationName); + + try { + weatherService.populateTemperature(location); + } catch (ServiceUnavailableException e) { + return null; + } + + return location.getMaximumTemparature(); + } + + public WeatherService getWeatherService() { + return weatherService; + } + + public void setWeatherService(WeatherService weatherService) { + this.weatherService = weatherService; + } +} diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/Location.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/Location.java new file mode 100644 index 0000000000..5f318acd5c --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/Location.java @@ -0,0 +1,33 @@ +package com.baeldung.testing.easymock; + +import java.math.BigDecimal; + +public class Location { + private String name; + private BigDecimal minimumTemperature; + private BigDecimal maximumTemparature; + + public Location(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public BigDecimal getMinimumTemperature() { + return minimumTemperature; + } + + public void setMinimumTemperature(BigDecimal minimumTemperature) { + this.minimumTemperature = minimumTemperature; + } + + public BigDecimal getMaximumTemparature() { + return maximumTemparature; + } + + public void setMaximumTemparature(BigDecimal maximumTemparature) { + this.maximumTemparature = maximumTemparature; + } +} diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ServiceUnavailableException.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ServiceUnavailableException.java new file mode 100644 index 0000000000..abab4bdee8 --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ServiceUnavailableException.java @@ -0,0 +1,7 @@ +package com.baeldung.testing.easymock; + +public class ServiceUnavailableException extends Exception { + + private static final long serialVersionUID = 6961151537340723535L; + +} diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/WeatherService.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/WeatherService.java new file mode 100644 index 0000000000..1c6b11b17b --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/WeatherService.java @@ -0,0 +1,5 @@ +package com.baeldung.testing.easymock; + +public interface WeatherService { + void populateTemperature(Location location) throws ServiceUnavailableException; +} diff --git a/testing-modules/easymock/src/test/java/com/baeldung/testing/easymock/ForecastProcessorUnitTest.java b/testing-modules/easymock/src/test/java/com/baeldung/testing/easymock/ForecastProcessorUnitTest.java new file mode 100644 index 0000000000..fa8fa847ae --- /dev/null +++ b/testing-modules/easymock/src/test/java/com/baeldung/testing/easymock/ForecastProcessorUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.testing.easymock; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.math.BigDecimal; + +import org.easymock.EasyMock; +import org.easymock.EasyMockRule; +import org.easymock.Mock; +import org.easymock.TestSubject; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +public class ForecastProcessorUnitTest { + private static int MAX_TEMP = 90; + + @Rule + public EasyMockRule rule = new EasyMockRule(this); + + @TestSubject + private ForecastProcessor forecastProcessor = new ForecastProcessor(); + + @Mock + private WeatherService mockWeatherService; + + @Before + public void setUp() { + forecastProcessor.setWeatherService(mockWeatherService); + } + + @SuppressWarnings("unchecked") + @Test + public void givenLocationName_whenWeatherServicePopulatesTemperatures_thenMaxTempReturned() throws ServiceUnavailableException { + mockWeatherService.populateTemperature(EasyMock.anyObject(Location.class)); + EasyMock.expectLastCall() + .andAnswer(() -> { + Location passedLocation = (Location) EasyMock.getCurrentArguments()[0]; + passedLocation.setMaximumTemparature(new BigDecimal(MAX_TEMP)); + passedLocation.setMinimumTemperature(new BigDecimal(MAX_TEMP - 10)); + return null; + }); + EasyMock.replay(mockWeatherService); + BigDecimal maxTemperature = forecastProcessor.getMaximumTemperature("New York"); + EasyMock.verify(mockWeatherService); + assertThat(maxTemperature, equalTo(new BigDecimal(MAX_TEMP))); + } +} diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index 158da176c6..e708d939e4 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -14,6 +14,31 @@ 1.0.0-SNAPSHOT ../../ + + + + + io.gatling + gatling-app + ${gatling.version} + + + io.gatling + gatling-recorder + ${gatling.version} + + + io.gatling.highcharts + gatling-charts-highcharts + ${gatling.version} + + + org.scala-lang + scala-library + ${scala.version} + + + @@ -77,52 +102,27 @@ simulation - - io.gatling - gatling-maven-plugin - ${gatling-maven-plugin.version} - - - test - - execute - - - true - - - - - - + + io.gatling + gatling-maven-plugin + ${gatling-maven-plugin.version} + + + test + + execute + + + true + + + + + + - - - - io.gatling - gatling-app - ${gatling.version} - - - io.gatling - gatling-recorder - ${gatling.version} - - - io.gatling.highcharts - gatling-charts-highcharts - ${gatling.version} - - - org.scala-lang - scala-library - ${scala.version} - - - - 1.8 1.8 diff --git a/testing-modules/junit-5-advanced/README.md b/testing-modules/junit-5-advanced/README.md new file mode 100644 index 0000000000..7282a4efad --- /dev/null +++ b/testing-modules/junit-5-advanced/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [JUnit 5 TestWatcher API](https://www.baeldung.com/junit-testwatcher) diff --git a/testing-modules/junit-5-advanced/pom.xml b/testing-modules/junit-5-advanced/pom.xml new file mode 100644 index 0000000000..f65f7e2a2f --- /dev/null +++ b/testing-modules/junit-5-advanced/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + junit-5-advanced + 1.0-SNAPSHOT + junit-5-advanced + Advanced JUnit 5 Topics + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + + + + + 5.4.2 + 2.21.0 + + + diff --git a/testing-modules/junit-5-advanced/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java b/testing-modules/junit-5-advanced/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java new file mode 100644 index 0000000000..d018aa939f --- /dev/null +++ b/testing-modules/junit-5-advanced/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java @@ -0,0 +1,15 @@ +package com.baeldung.failure_vs_error; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +public class SimpleCalculator { + + public static double divideNumbers(double dividend, double divisor) { + if (divisor == 0) { + throw new ArithmeticException("Division by zero!"); + } + return dividend / divisor; + } +} diff --git a/xmlunit-2/src/main/resources/logback.xml b/testing-modules/junit-5-advanced/src/main/resources/logback.xml similarity index 100% rename from xmlunit-2/src/main/resources/logback.xml rename to testing-modules/junit-5-advanced/src/main/resources/logback.xml diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/DisplayNameGeneratorUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/DisplayNameGeneratorUnitTest.java new file mode 100644 index 0000000000..311539f760 --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/DisplayNameGeneratorUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.displayname; + +import org.junit.jupiter.api.DisplayNameGeneration; +import org.junit.jupiter.api.DisplayNameGenerator; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.lang.reflect.Method; + +@DisplayNameGeneration(DisplayNameGeneratorUnitTest.ReplaceCamelCase.class) +class DisplayNameGeneratorUnitTest { + + @Test + void camelCaseName() { + } + + @Nested + @DisplayNameGeneration(DisplayNameGeneratorUnitTest.IndicativeSentences.class) + class ANumberIsFizz { + @Test + void ifItIsDivisibleByThree() { + } + + @ParameterizedTest(name = "Number {0} is fizz.") + @ValueSource(ints = { 3, 12, 18 }) + void ifItIsOneOfTheFollowingNumbers(int number) { + } + } + + @Nested + @DisplayNameGeneration(DisplayNameGeneratorUnitTest.IndicativeSentences.class) + class ANumberIsBuzz { + @Test + void ifItIsDivisibleByFive() { + } + + @ParameterizedTest(name = "Number {0} is buzz.") + @ValueSource(ints = { 5, 10, 20 }) + void ifItIsOneOfTheFollowingNumbers(int number) { + } + } + + static class IndicativeSentences extends ReplaceCamelCase { + @Override + public String generateDisplayNameForNestedClass(Class nestedClass) { + return super.generateDisplayNameForNestedClass(nestedClass) + "..."; + } + + @Override + public String generateDisplayNameForMethod(Class testClass, Method testMethod) { + return replaceCamelCase(testClass.getSimpleName() + " " + testMethod.getName()) + "."; + } + } + + static class ReplaceCamelCase extends DisplayNameGenerator.Standard { + @Override + public String generateDisplayNameForClass(Class testClass) { + return replaceCamelCase(super.generateDisplayNameForClass(testClass)); + } + + @Override + public String generateDisplayNameForNestedClass(Class nestedClass) { + return replaceCamelCase(super.generateDisplayNameForNestedClass(nestedClass)); + } + + @Override + public String generateDisplayNameForMethod(Class testClass, Method testMethod) { + return this.replaceCamelCase(testMethod.getName()) + DisplayNameGenerator.parameterTypesAsString(testMethod); + } + + String replaceCamelCase(String camelCase) { + StringBuilder result = new StringBuilder(); + result.append(camelCase.charAt(0)); + for (int i=1; i testResultsStatus = new ArrayList<>(); + + private enum TestResultStatus { + SUCCESSFUL, ABORTED, FAILED, DISABLED; + } + + @Override + public void testDisabled(ExtensionContext context, Optional reason) { + LOG.info("Test Disabled for test {}: with reason :- {}", context.getDisplayName(), reason.orElse("No reason")); + + testResultsStatus.add(TestResultStatus.DISABLED); + } + + @Override + public void testSuccessful(ExtensionContext context) { + LOG.info("Test Successful for test {}: ", context.getDisplayName()); + + testResultsStatus.add(TestResultStatus.SUCCESSFUL); + } + + @Override + public void testAborted(ExtensionContext context, Throwable cause) { + LOG.info("Test Aborted for test {}: ", context.getDisplayName()); + + testResultsStatus.add(TestResultStatus.ABORTED); + } + + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + LOG.info("Test Aborted for test {}: ", context.getDisplayName()); + + testResultsStatus.add(TestResultStatus.FAILED); + } + + @Override + public void afterAll(ExtensionContext context) throws Exception { + Map summary = testResultsStatus.stream() + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + + LOG.info("Test result summary for {} {}", context.getDisplayName(), summary.toString()); + } + +} diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestWatcherAPIUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestWatcherAPIUnitTest.java new file mode 100644 index 0000000000..89666cf9b8 --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestWatcherAPIUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.extensions.testwatcher; + +import static org.junit.jupiter.api.Assertions.fail; + +import org.junit.Assert; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +@ExtendWith(TestResultLoggerExtension.class) +class TestWatcherAPIUnitTest { + + @Test + void givenFalseIsTrue_whenTestAbortedThenCaptureResult() { + Assumptions.assumeTrue(false); + } + + @Disabled + @Test + void givenTrueIsTrue_whenTestDisabledThenCaptureResult() { + Assert.assertTrue(true); + } + + @Test + void givenTrueIsTrue_whenTestAbortedThenCaptureResult() { + Assumptions.assumeTrue(true); + } + + @Disabled("This test is disabled") + @Test + void givenFailure_whenTestDisabledWithReason_ThenCaptureResult() { + fail("Not yet implemented"); + } + +} diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java new file mode 100644 index 0000000000..9b1777258c --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.failure_vs_error; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +class SimpleCalculatorUnitTest { + + @Test + void divideNumbers() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(2, result); + } + + @Test + @Disabled("test is expected to fail, disabled so that CI build still goes through") + void divideNumbers_failure() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(15, result); + } + + @Test + @Disabled("test is expected to raise an error, disabled so that CI build still goes through") + void divideNumbers_error() { + SimpleCalculator.divideNumbers(10, 0); + } +} diff --git a/testing-modules/junit-5-basics/README.md b/testing-modules/junit-5-basics/README.md index 6e44a9c071..dbe6803401 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -1,4 +1,10 @@ ### Relevant Articles: - +- [A Guide to JUnit 5](http://www.baeldung.com/junit-5) +- [JUnit5 @RunWith](http://www.baeldung.com/junit-5-runwith) - [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path) - [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junit-filtering-tests) +- [JUnit 5 Temporary Directory Support](https://www.baeldung.com/junit-5-temporary-directory) +- [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) +- [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) +- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) +- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) diff --git a/testing-modules/junit-5-basics/pom.xml b/testing-modules/junit-5-basics/pom.xml index 28afcd6aac..68a0ceeee7 100644 --- a/testing-modules/junit-5-basics/pom.xml +++ b/testing-modules/junit-5-basics/pom.xml @@ -16,20 +16,10 @@ - - org.junit.platform - junit-platform-engine - ${junit.platform.version} - - - org.junit.jupiter - junit-jupiter-params - ${junit.jupiter.version} - org.junit.platform junit-platform-runner - ${junit.platform.version} + ${junit-platform.version} test @@ -44,6 +34,24 @@ ${junit.vintage.version} test + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + com.h2database h2 @@ -92,13 +100,7 @@ maven-surefire-plugin ${maven-surefire-plugin.version} - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - - + **/*IntegrationTest.java @@ -148,10 +150,9 @@ - 5.4.2 - 1.2.0 - 5.2.0 - 1.4.196 + 5.4.2 + 1.2.0 + 5.4.2 5.0.6.RELEASE 2.21.0 diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/Greetings.java similarity index 100% rename from testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java rename to testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/Greetings.java diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/junit5/bean/NumbersBean.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/bean/NumbersBean.java similarity index 100% rename from testing-modules/junit-5/src/main/java/com/baeldung/junit5/bean/NumbersBean.java rename to testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/bean/NumbersBean.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/ExceptionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/ExceptionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/ExceptionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/ExceptionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/FirstUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/FirstUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/FirstUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/FirstUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/LiveTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/LiveTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/LiveTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/LiveTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/SharedTemporaryDirectoryUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/SharedTemporaryDirectoryUnitTest.java new file mode 100644 index 0000000000..9483a33143 --- /dev/null +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/SharedTemporaryDirectoryUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.extensions.tempdir; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertLinesMatch; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.io.TempDir; + +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; + +@TestMethodOrder(OrderAnnotation.class) +class SharedTemporaryDirectoryUnitTest { + + @TempDir + static Path sharedTempDir; + + @Test + @Order(1) + void givenFieldWithSharedTempDirectoryPath_whenWriteToFile_thenContentIsCorrect() throws IOException { + Path numbers = sharedTempDir.resolve("numbers.txt"); + + List lines = Arrays.asList("1", "2", "3"); + Files.write(numbers, lines); + + assertAll( + () -> assertTrue("File should exist", Files.exists(numbers)), + () -> assertLinesMatch(lines, Files.readAllLines(numbers))); + + Files.createTempDirectory("bpb"); + } + + @Test + @Order(2) + void givenAlreadyWrittenToSharedFile_whenCheckContents_thenContentIsCorrect() throws IOException { + Path numbers = sharedTempDir.resolve("numbers.txt"); + + assertLinesMatch(Arrays.asList("1", "2", "3"), Files.readAllLines(numbers)); + } + +} diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/TemporaryDirectoryUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/TemporaryDirectoryUnitTest.java new file mode 100644 index 0000000000..c6f1a7cd77 --- /dev/null +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/extensions/tempdir/TemporaryDirectoryUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.extensions.tempdir; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertLinesMatch; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class TemporaryDirectoryUnitTest { + + @Test + void givenTestMethodWithTempDirectoryPath_whenWriteToFile_thenContentIsCorrect(@TempDir Path tempDir) throws IOException { + Path numbers = tempDir.resolve("numbers.txt"); + + List lines = Arrays.asList("1", "2", "3"); + Files.write(numbers, lines); + + assertAll( + () -> assertTrue("File should exist", Files.exists(numbers)), + () -> assertLinesMatch(lines, Files.readAllLines(numbers))); + } + + @TempDir + File anotherTempDir; + + @Test + void givenFieldWithTempDirectoryFile_whenWriteToFile_thenContentIsCorrect() throws IOException { + assertTrue("Should be a directory ", this.anotherTempDir.isDirectory()); + + File letters = new File(anotherTempDir, "letters.txt"); + List lines = Arrays.asList("x", "y", "z"); + + Files.write(letters.toPath(), lines); + + assertAll( + () -> assertTrue("File should exist", Files.exists(letters.toPath())), + () -> assertLinesMatch(lines, Files.readAllLines(letters.toPath()))); + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java index 20fa372abd..eb8cab2462 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java @@ -17,7 +17,7 @@ public class ReadResourceDirectoryUnitTest { String absolutePath = file.getAbsolutePath(); System.out.println(absolutePath); - Assert.assertTrue(absolutePath.endsWith("src/test/resources")); + Assert.assertTrue(absolutePath.endsWith("src" + File.separator + "test" + File.separator + "resources")); } @Test @@ -27,7 +27,7 @@ public class ReadResourceDirectoryUnitTest { String absolutePath = resourceDirectory.toFile().getAbsolutePath(); System.out.println(absolutePath); - Assert.assertTrue(absolutePath.endsWith("src/test/resources")); + Assert.assertTrue(absolutePath.endsWith("src" + File.separator + "test" + File.separator + "resources")); } @Test @@ -39,7 +39,7 @@ public class ReadResourceDirectoryUnitTest { String absolutePath = file.getAbsolutePath(); System.out.println(absolutePath); - Assert.assertTrue(absolutePath.endsWith("/example_resource.txt")); + Assert.assertTrue(absolutePath.endsWith(File.separator + "example_resource.txt")); } } diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 47db6587b4..d543b9b09b 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -1,16 +1,9 @@ ### 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) - [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 Guide to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) - [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters) - [Mockito and JUnit 5 – Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension) -- [JUnit5 @RunWith](http://www.baeldung.com/junit-5-runwith) -- [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) -- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) -- [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) -- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) - [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) diff --git a/testing-modules/junit5-migration/README.md b/testing-modules/junit5-migration/README.md new file mode 100644 index 0000000000..b97ff8255c --- /dev/null +++ b/testing-modules/junit5-migration/README.md @@ -0,0 +1,2 @@ + +This is the code for the Junit 4 - Junit 5 Migration E-book. diff --git a/testing-modules/load-testing-comparison/pom.xml b/testing-modules/load-testing-comparison/pom.xml index 44014e96ab..2c53657481 100644 --- a/testing-modules/load-testing-comparison/pom.xml +++ b/testing-modules/load-testing-comparison/pom.xml @@ -145,7 +145,6 @@ 5.0 3.11 2.0.5.RELEASE - 1.4.197 \ No newline at end of file diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index acdd7eb2ac..7b6d6e7735 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -33,7 +33,7 @@ org.eclipse.persistence javax.persistence - 2.1.1 + ${javax.persistence.version} @@ -94,11 +94,11 @@ 2.0.9.RELEASE 19.0 - 3.5 1.7.0 2.0.0.0 + 2.1.1 \ No newline at end of file diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java index 4f5ceb04e7..568492ca10 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java @@ -30,7 +30,7 @@ public class MockitoInjectIntoSpyUnitTest { private MyDictionary spyDic; @Test - public void whenUseInjectMocksAnnotation_thenCorrect2() { + public void whenUseInjectMocksAnnotation_thenCorrect() { Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning"); assertEquals("aMeaning", spyDic.getMeaning("aWord")); diff --git a/testing-modules/mocks/mock-comparisons/pom.xml b/testing-modules/mocks/mock-comparisons/pom.xml index ae36280300..e454f124ce 100644 --- a/testing-modules/mocks/mock-comparisons/pom.xml +++ b/testing-modules/mocks/mock-comparisons/pom.xml @@ -49,7 +49,6 @@ 2.21.0 3.5.1 1.41 - diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index 90ec857b7f..8d40c668c0 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -14,6 +14,7 @@ + easy-random gatling groovy-spock junit-5 @@ -33,5 +34,8 @@ testing testng junit-5-basics + easymock + junit-5-advanced + xmlunit-2 diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 4ed10f0641..eb85c6c8be 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -194,14 +194,12 @@ 18.0 - 2.9.7 1.8 19.0 2.5 1.4.7 9.4.0.v20161208 - 3.5 3.2.2 4.4.5 diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index 6dad3be117..a1995ce9ff 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -151,7 +151,6 @@ 19.0 - 3.5 2.9.0 @@ -163,9 +162,6 @@ 4.5.2 4.1 - - - 2.6 \ No newline at end of file diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index 8eb282643a..0970eabeff 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -4,3 +4,5 @@ - [A Quick Guide to @TestPropertySource](https://www.baeldung.com/spring-test-property-source) - [Guide to ReflectionTestUtils for Unit Testing](https://www.baeldung.com/spring-reflection-test-utils) - [How to Test the @Scheduled Annotation](https://www.baeldung.com/spring-testing-scheduled-annotation) +- [Using SpringJUnit4ClassRunner with Parameterized](https://www.baeldung.com/springjunit4classrunner-parameterized) +- [Override properties in Spring]() diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index 10d34f169b..6f2700e2df 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -26,7 +26,6 @@ org.springframework.boot spring-boot-starter LATEST - test org.springframework.boot @@ -52,7 +51,7 @@ org.eclipse.persistence javax.persistence - 2.1.1 + ${javax.persistence.version} org.springframework.data @@ -74,7 +73,7 @@ javax.servlet javax.servlet-api - ${servlet.api.version} + ${javax.servlet-api.version} @@ -95,7 +94,8 @@ 3.1.6 5.4.0 5.1.4.RELEASE - 4.0.1 + 4.0.1 + 2.1.1 \ No newline at end of file diff --git a/testing-modules/spring-testing/src/main/java/com/baeldung/overrideproperties/Application.java b/testing-modules/spring-testing/src/main/java/com/baeldung/overrideproperties/Application.java new file mode 100644 index 0000000000..ac215bf78e --- /dev/null +++ b/testing-modules/spring-testing/src/main/java/com/baeldung/overrideproperties/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.overrideproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/testing-modules/spring-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java b/testing-modules/spring-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java new file mode 100644 index 0000000000..074092b7df --- /dev/null +++ b/testing-modules/spring-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java @@ -0,0 +1,24 @@ +package com.baeldung.overrideproperties.resolver; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class PropertySourceResolver { + + private final String firstProperty; + private final String secondProperty; + + public PropertySourceResolver(@Value("${example.firstProperty}") String firstProperty, @Value("${example.secondProperty}") String secondProperty) { + this.firstProperty = firstProperty; + this.secondProperty = secondProperty; + } + + public String getFirstProperty() { + return firstProperty; + } + + public String getSecondProperty() { + return secondProperty; + } +} diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java new file mode 100644 index 0000000000..9b692edd7b --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.overrideproperties; + +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +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; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@ContextConfiguration(initializers = PropertyOverrideContextInitializer.class, classes = Application.class) +public class ContextPropertySourceResolverIntegrationTest { + + @Autowired private PropertySourceResolver propertySourceResolver; + + @Test + public void shouldContext_overridePropertyValues() { + final String firstProperty = propertySourceResolver.getFirstProperty(); + final String secondProperty = propertySourceResolver.getSecondProperty(); + + assertEquals(PropertyOverrideContextInitializer.PROPERTY_FIRST_VALUE, firstProperty); + assertEquals("contextFile", secondProperty); + } + +} \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java new file mode 100644 index 0000000000..95d83420b7 --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java @@ -0,0 +1,29 @@ +package com.baeldung.overrideproperties; + +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +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.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ActiveProfiles("test") +public class ProfilePropertySourceResolverIntegrationTest { + + @Autowired private PropertySourceResolver propertySourceResolver; + + @Test + public void shouldProfiledProperty_overridePropertyValues() { + final String firstProperty = propertySourceResolver.getFirstProperty(); + final String secondProperty = propertySourceResolver.getSecondProperty(); + + assertEquals("profile", firstProperty); + assertEquals("file", secondProperty); + } + +} \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java new file mode 100644 index 0000000000..a8c4267c5c --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java @@ -0,0 +1,17 @@ +package com.baeldung.overrideproperties; + +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.support.TestPropertySourceUtils; + +public class PropertyOverrideContextInitializer implements ApplicationContextInitializer { + + static final String PROPERTY_FIRST_VALUE = "contextClass"; + + @Override + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(configurableApplicationContext, "example.firstProperty=" + PROPERTY_FIRST_VALUE); + + TestPropertySourceUtils.addPropertiesFilesToEnvironment(configurableApplicationContext, "context-override-application.properties"); + } +} diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java new file mode 100644 index 0000000000..573a46dd5f --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.overrideproperties; + +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +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.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(properties = { "example.firstProperty=annotation" }) +public class SpringBootPropertySourceResolverIntegrationTest { + + @Autowired private PropertySourceResolver propertySourceResolver; + + @Test + public void shouldSpringBootTestAnnotation_overridePropertyValues() { + final String firstProperty = propertySourceResolver.getFirstProperty(); + final String secondProperty = propertySourceResolver.getSecondProperty(); + + Assert.assertEquals("annotation", firstProperty); + Assert.assertEquals("file", secondProperty); + } + +} \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java new file mode 100644 index 0000000000..c724713854 --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.overrideproperties; + +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class TestResourcePropertySourceResolverIntegrationTest { + + @Autowired private PropertySourceResolver propertySourceResolver; + + @Test + public void shouldTestResourceFile_overridePropertyValues() { + final String firstProperty = propertySourceResolver.getFirstProperty(); + final String secondProperty = propertySourceResolver.getSecondProperty(); + + assertEquals("file", firstProperty); + assertEquals("file", secondProperty); + } + +} \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/resources/application-test.properties b/testing-modules/spring-testing/src/test/resources/application-test.properties new file mode 100644 index 0000000000..54c5bda7e8 --- /dev/null +++ b/testing-modules/spring-testing/src/test/resources/application-test.properties @@ -0,0 +1,2 @@ +# override properties +example.firstProperty=profile \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/resources/application.properties b/testing-modules/spring-testing/src/test/resources/application.properties new file mode 100644 index 0000000000..6c74aa2995 --- /dev/null +++ b/testing-modules/spring-testing/src/test/resources/application.properties @@ -0,0 +1,3 @@ +# override properties +example.firstProperty=file +example.secondProperty=file \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/resources/context-override-application.properties b/testing-modules/spring-testing/src/test/resources/context-override-application.properties new file mode 100644 index 0000000000..c39e5d3966 --- /dev/null +++ b/testing-modules/spring-testing/src/test/resources/context-override-application.properties @@ -0,0 +1 @@ +example.secondProperty=contextFile \ No newline at end of file diff --git a/testing-modules/test-containers/pom.xml b/testing-modules/test-containers/pom.xml index 7ee002ea8b..bd87cb5b22 100644 --- a/testing-modules/test-containers/pom.xml +++ b/testing-modules/test-containers/pom.xml @@ -23,6 +23,12 @@ ${junit.platform.version} test + + org.junit.platform + junit-platform-commons + ${junit.platform.version} + test + org.junit.vintage junit-vintage-engine @@ -59,6 +65,11 @@ selenium-remote-driver ${selenium-remote-driver.version} + + org.seleniumhq.selenium + selenium-chrome-driver + ${selenium-remote-driver.version} + @@ -76,7 +87,7 @@ org.junit.platform junit-platform-surefire-provider - ${junit.platform.version} + ${junit-platform-surefire-provider.version} @@ -99,16 +110,14 @@ - 5.1.0 - 1.0.1 - 4.12.1 - 2.8.2 - 2.21.0 - 5.0.1.RELEASE - 1.7.2 - 42.2.2 - 3.12.0 - 2.21.0 + 1.5.0 + 5.5.0 + 2.12.0 + 1.11.4 + 42.2.6 + 3.141.59 + 2.22.2 + 1.3.2 diff --git a/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java index 0e52c4e9f7..0fdf0ede79 100644 --- a/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java +++ b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java @@ -2,29 +2,26 @@ package com.baeldung.testconainers; import static org.junit.Assert.assertEquals; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.openqa.selenium.By; -import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.RemoteWebDriver; -import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.BrowserWebDriverContainer; -import org.testcontainers.containers.GenericContainer; public class WebDriverContainerLiveTest { @Rule public BrowserWebDriverContainer chrome = new BrowserWebDriverContainer() - .withDesiredCapabilities(DesiredCapabilities.chrome()); + .withCapabilities(new ChromeOptions()); @Test public void whenNavigatedToPage_thenHeadingIsInThePage() { RemoteWebDriver driver = chrome.getWebDriver(); - driver.get("https://saucelabs.com/test/guinea-pig"); - String heading = driver.findElement(By.xpath("/html/body/h1")) + driver.get("http://example.com"); + String heading = driver.findElement(By.xpath("/html/body/div/h1")) .getText(); - assertEquals("This page is a Selenium sandbox", heading); + assertEquals("Example Domain", heading); } } diff --git a/xmlunit-2/README.md b/testing-modules/xmlunit-2/README.md similarity index 100% rename from xmlunit-2/README.md rename to testing-modules/xmlunit-2/README.md diff --git a/xmlunit-2/pom.xml b/testing-modules/xmlunit-2/pom.xml similarity index 94% rename from xmlunit-2/pom.xml rename to testing-modules/xmlunit-2/pom.xml index faefeca7a1..aa516bfcc5 100644 --- a/xmlunit-2/pom.xml +++ b/testing-modules/xmlunit-2/pom.xml @@ -1,15 +1,14 @@ 4.0.0 - com.baeldung xmlunit-2 - 1.0 xmlunit-2 com.baeldung parent-modules 1.0.0-SNAPSHOT + ../../ @@ -23,7 +22,6 @@ xmlunit-core ${xmlunit.version} - diff --git a/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java b/testing-modules/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java similarity index 100% rename from xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java rename to testing-modules/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java diff --git a/testing-modules/xmlunit-2/src/main/resources/logback.xml b/testing-modules/xmlunit-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/xmlunit-2/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/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/testing-modules/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java similarity index 100% rename from xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java rename to testing-modules/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java diff --git a/xmlunit-2/src/test/resources/control.xml b/testing-modules/xmlunit-2/src/test/resources/control.xml similarity index 100% rename from xmlunit-2/src/test/resources/control.xml rename to testing-modules/xmlunit-2/src/test/resources/control.xml diff --git a/xmlunit-2/src/test/resources/students.xml b/testing-modules/xmlunit-2/src/test/resources/students.xml similarity index 100% rename from xmlunit-2/src/test/resources/students.xml rename to testing-modules/xmlunit-2/src/test/resources/students.xml diff --git a/xmlunit-2/src/test/resources/students.xsd b/testing-modules/xmlunit-2/src/test/resources/students.xsd similarity index 100% rename from xmlunit-2/src/test/resources/students.xsd rename to testing-modules/xmlunit-2/src/test/resources/students.xsd diff --git a/xmlunit-2/src/test/resources/students_with_error.xml b/testing-modules/xmlunit-2/src/test/resources/students_with_error.xml similarity index 100% rename from xmlunit-2/src/test/resources/students_with_error.xml rename to testing-modules/xmlunit-2/src/test/resources/students_with_error.xml diff --git a/xmlunit-2/src/test/resources/teachers.xml b/testing-modules/xmlunit-2/src/test/resources/teachers.xml similarity index 100% rename from xmlunit-2/src/test/resources/teachers.xml rename to testing-modules/xmlunit-2/src/test/resources/teachers.xml diff --git a/xmlunit-2/src/test/resources/test.xml b/testing-modules/xmlunit-2/src/test/resources/test.xml similarity index 100% rename from xmlunit-2/src/test/resources/test.xml rename to testing-modules/xmlunit-2/src/test/resources/test.xml diff --git a/vaadin/pom.xml b/vaadin/pom.xml index 648343fcd8..e3d882bbda 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -33,7 +33,26 @@ javax.servlet-api provided - + + com.vaadin + vaadin-server + ${vaadin-server.version} + + + com.vaadin + vaadin-push + ${vaadin-push.version} + + + com.vaadin + vaadin-client-compiled + ${vaadin-client-compiled.version} + + + com.vaadin + vaadin-themes + ${vaadin-themes.version} + org.springframework.boot spring-boot-starter-data-jpa @@ -155,16 +174,19 @@ - 10.0.11 - 10.0.11 - 10.0.11 + 13.0.9 + 13.0.9 + 13.0.9 + 8.8.5 + 8.8.5 + 8.8.5 + 8.8.5 9.3.9.v20160517 UTF-8 1.8 1.8 local mytheme - 3.0.0 3.0.0 diff --git a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java new file mode 100644 index 0000000000..68be53b1b3 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java @@ -0,0 +1,278 @@ +package com.baeldung.introduction; + +import java.time.Instant; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.servlet.annotation.WebServlet; + +import com.vaadin.annotations.Push; +import com.vaadin.annotations.Theme; +import com.vaadin.annotations.VaadinServletConfiguration; +import com.vaadin.data.Binder; +import com.vaadin.data.validator.StringLengthValidator; +import com.vaadin.icons.VaadinIcons; +import com.vaadin.server.ExternalResource; +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinServlet; +import com.vaadin.ui.Button; +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.ComboBox; +import com.vaadin.ui.DateField; +import com.vaadin.ui.FormLayout; +import com.vaadin.ui.Grid; +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.InlineDateField; +import com.vaadin.ui.Label; +import com.vaadin.ui.Link; +import com.vaadin.ui.ListSelect; +import com.vaadin.ui.NativeButton; +import com.vaadin.ui.NativeSelect; +import com.vaadin.ui.Panel; +import com.vaadin.ui.PasswordField; +import com.vaadin.ui.RichTextArea; +import com.vaadin.ui.TextArea; +import com.vaadin.ui.TextField; +import com.vaadin.ui.TwinColSelect; +import com.vaadin.ui.UI; +import com.vaadin.ui.VerticalLayout; + +@SuppressWarnings("serial") +@Push +@Theme("mytheme") +public class VaadinUI extends UI { + + private Label currentTime; + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + protected void init(VaadinRequest vaadinRequest) { + final VerticalLayout verticalLayout = new VerticalLayout(); + verticalLayout.setSpacing(true); + verticalLayout.setMargin(true); + final GridLayout gridLayout = new GridLayout(3, 2); + gridLayout.setSpacing(true); + gridLayout.setMargin(true); + final HorizontalLayout horizontalLayout = new HorizontalLayout(); + horizontalLayout.setSpacing(true); + horizontalLayout.setMargin(true); + final FormLayout formLayout = new FormLayout(); + formLayout.setSpacing(true); + formLayout.setMargin(true); + final GridLayout buttonLayout = new GridLayout(3, 5); + buttonLayout.setMargin(true); + buttonLayout.setSpacing(true); + + final Label label = new Label(); + label.setId("Label"); + label.setValue("Label Value"); + label.setCaption("Label"); + gridLayout.addComponent(label); + + final Link link = new Link("Baeldung", new ExternalResource("http://www.baeldung.com/")); + link.setId("Link"); + link.setTargetName("_blank"); + gridLayout.addComponent(link); + + final TextField textField = new TextField(); + textField.setId("TextField"); + textField.setCaption("TextField:"); + textField.setValue("TextField Value"); + textField.setIcon(VaadinIcons.USER); + gridLayout.addComponent(textField); + + final TextArea textArea = new TextArea(); + textArea.setCaption("TextArea"); + textArea.setId("TextArea"); + textArea.setValue("TextArea Value"); + gridLayout.addComponent(textArea); + + final DateField dateField = new DateField("DateField", LocalDate.ofEpochDay(0)); + dateField.setId("DateField"); + gridLayout.addComponent(dateField); + + final PasswordField passwordField = new PasswordField(); + passwordField.setId("PasswordField"); + passwordField.setCaption("PasswordField:"); + passwordField.setValue("password"); + gridLayout.addComponent(passwordField); + + final RichTextArea richTextArea = new RichTextArea(); + richTextArea.setCaption("Rich Text Area"); + richTextArea.setValue("

RichTextArea

"); + richTextArea.setSizeFull(); + + Panel richTextPanel = new Panel(); + richTextPanel.setContent(richTextArea); + + final InlineDateField inlineDateField = new InlineDateField(); + inlineDateField.setValue(LocalDate.ofEpochDay(0)); + inlineDateField.setCaption("Inline Date Field"); + horizontalLayout.addComponent(inlineDateField); + + Button normalButton = new Button("Normal Button"); + normalButton.setId("NormalButton"); + normalButton.addClickListener(e -> { + label.setValue("CLICK"); + }); + buttonLayout.addComponent(normalButton); + + Button tinyButton = new Button("Tiny Button"); + tinyButton.addStyleName("tiny"); + buttonLayout.addComponent(tinyButton); + + Button smallButton = new Button("Small Button"); + smallButton.addStyleName("small"); + buttonLayout.addComponent(smallButton); + + Button largeButton = new Button("Large Button"); + largeButton.addStyleName("large"); + buttonLayout.addComponent(largeButton); + + Button hugeButton = new Button("Huge Button"); + hugeButton.addStyleName("huge"); + buttonLayout.addComponent(hugeButton); + + Button disabledButton = new Button("Disabled Button"); + disabledButton.setDescription("This button cannot be clicked"); + disabledButton.setEnabled(false); + buttonLayout.addComponent(disabledButton); + + Button dangerButton = new Button("Danger Button"); + dangerButton.addStyleName("danger"); + buttonLayout.addComponent(dangerButton); + + Button friendlyButton = new Button("Friendly Button"); + friendlyButton.addStyleName("friendly"); + buttonLayout.addComponent(friendlyButton); + + Button primaryButton = new Button("Primary Button"); + primaryButton.addStyleName("primary"); + buttonLayout.addComponent(primaryButton); + + NativeButton nativeButton = new NativeButton("Native Button"); + buttonLayout.addComponent(nativeButton); + + Button iconButton = new Button("Icon Button"); + iconButton.setIcon(VaadinIcons.ALIGN_LEFT); + buttonLayout.addComponent(iconButton); + + Button borderlessButton = new Button("BorderLess Button"); + borderlessButton.addStyleName("borderless"); + buttonLayout.addComponent(borderlessButton); + + Button linkButton = new Button("Link Button"); + linkButton.addStyleName("link"); + buttonLayout.addComponent(linkButton); + + Button quietButton = new Button("Quiet Button"); + quietButton.addStyleName("quiet"); + buttonLayout.addComponent(quietButton); + + horizontalLayout.addComponent(buttonLayout); + + final CheckBox checkbox = new CheckBox("CheckBox"); + checkbox.setValue(true); + checkbox.addValueChangeListener(e -> checkbox.setValue(!checkbox.getValue())); + formLayout.addComponent(checkbox); + + List numbers = new ArrayList(); + numbers.add("One"); + numbers.add("Ten"); + numbers.add("Eleven"); + ComboBox comboBox = new ComboBox("ComboBox"); + comboBox.setItems(numbers); + formLayout.addComponent(comboBox); + + ListSelect listSelect = new ListSelect("ListSelect"); + listSelect.setItems(numbers); + listSelect.setRows(2); + formLayout.addComponent(listSelect); + + NativeSelect nativeSelect = new NativeSelect("NativeSelect"); + nativeSelect.setItems(numbers); + formLayout.addComponent(nativeSelect); + + TwinColSelect twinColSelect = new TwinColSelect("TwinColSelect"); + twinColSelect.setItems(numbers); + + Grid grid = new Grid("Grid"); + grid.setColumns("Column1", "Column2", "Column3"); + grid.setItems("Item1", "Item2", "Item3"); + grid.setItems("Item4", "Item5", "Item6"); + + Panel panel = new Panel("Panel"); + panel.setContent(grid); + panel.setSizeUndefined(); + + Panel serverPushPanel = new Panel("Server Push"); + FormLayout timeLayout = new FormLayout(); + timeLayout.setSpacing(true); + timeLayout.setMargin(true); + currentTime = new Label("No TIME..."); + timeLayout.addComponent(currentTime); + serverPushPanel.setContent(timeLayout); + serverPushPanel.setSizeUndefined(); + ScheduledExecutorService scheduleExecutor = Executors.newScheduledThreadPool(1); + Runnable task = () -> { + currentTime.setValue("Current Time : " + Instant.now()); + }; + scheduleExecutor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS); + + FormLayout dataBindingLayout = new FormLayout(); + dataBindingLayout.setSpacing(true); + dataBindingLayout.setMargin(true); + + Binder binder = new Binder<>(); + BindData bindData = new BindData("BindData"); + binder.readBean(bindData); + TextField bindedTextField = new TextField(); + bindedTextField.setWidth("250px"); + binder.forField(bindedTextField).bind(BindData::getBindName, BindData::setBindName); + dataBindingLayout.addComponent(bindedTextField); + + FormLayout validatorLayout = new FormLayout(); + validatorLayout.setSpacing(true); + validatorLayout.setMargin(true); + + HorizontalLayout textValidatorLayout = new HorizontalLayout(); + textValidatorLayout.setSpacing(true); + textValidatorLayout.setMargin(true); + + + BindData stringValidatorBindData = new BindData(""); + TextField stringValidator = new TextField(); + Binder stringValidatorBinder = new Binder<>(); + stringValidatorBinder.setBean(stringValidatorBindData); + stringValidatorBinder.forField(stringValidator) + .withValidator(new StringLengthValidator("String must have 2-5 characters lenght", 2, 5)) + .bind(BindData::getBindName, BindData::setBindName); + + textValidatorLayout.addComponent(stringValidator); + Button buttonStringValidator = new Button("Validate String"); + buttonStringValidator.addClickListener(e -> stringValidatorBinder.validate()); + textValidatorLayout.addComponent(buttonStringValidator); + + validatorLayout.addComponent(textValidatorLayout); + verticalLayout.addComponent(gridLayout); + verticalLayout.addComponent(richTextPanel); + verticalLayout.addComponent(horizontalLayout); + verticalLayout.addComponent(formLayout); + verticalLayout.addComponent(twinColSelect); + verticalLayout.addComponent(panel); + verticalLayout.addComponent(serverPushPanel); + verticalLayout.addComponent(dataBindingLayout); + verticalLayout.addComponent(validatorLayout); + setContent(verticalLayout); + } + + @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true) + @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) + public static class MyUIServlet extends VaadinServlet { + } +} \ No newline at end of file diff --git a/vertx-and-rxjava/.gitignore b/vertx-and-rxjava/.gitignore new file mode 100644 index 0000000000..3aba11e2fd --- /dev/null +++ b/vertx-and-rxjava/.gitignore @@ -0,0 +1 @@ +/.vertx \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 2492951d1a..200ca7577f 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -141,10 +141,6 @@ 2.8.0 4.1 - - 3.5 - 2.5 - 3.0.1 3.0.0 diff --git a/xml/pom.xml b/xml/pom.xml index ba6a734dc9..123875b1d9 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -33,17 +33,17 @@ javax.xml jaxb-api - 2.1 + ${jaxb-api.version} javax.xml jaxp-api - 1.4.2 + ${jaxp-api.version} javax.xml.stream stax-api - 1.0-2 + ${stax-api.version} @@ -249,14 +249,11 @@ 1.6.1 1.1.6 2.0.6 - 2.5 4.1 1.2.4.5 - - - 3.5 - 2.4 - 1.8 + 2.1 + 1.4.2 + 1.0-2 1.3.1 diff --git a/xstream/pom.xml b/xstream/pom.xml index f75e10fc7d..b98e258599 100644 --- a/xstream/pom.xml +++ b/xstream/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../pom.xml @@ -28,8 +29,8 @@ - 1.4.9 + 1.4.10 1.3.8 -
\ No newline at end of file + diff --git a/xstream/src/main/java/com/baeldung/rce/App.java b/xstream/src/main/java/com/baeldung/rce/App.java new file mode 100644 index 0000000000..3720c7fa93 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/rce/App.java @@ -0,0 +1,92 @@ +package com.baeldung.rce; + +import com.sun.net.httpserver.HttpServer; +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.NoTypePermission; +import com.thoughtworks.xstream.security.NullPermission; +import com.thoughtworks.xstream.security.PrimitiveTypePermission; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.HashSet; +import java.util.Set; + +/** + * Web application which is intentionally vulnerable to an XStream remote code + * exploitation (RCE). + * + *

+ * This test application is meant to maintain a set of {@link Person} models. It + * exposes a "/persons" endpoint which supports the following operations: + * + *

    + *
  1. {@code POST} XML for adding a new {@link Person} to the set + *
  2. {@code GET} for retrieving the set of {@link Person} models as XML + *
+ * + * The {@code POST} handler is vulnerable to an RCE exploit. + */ +public final class App { + + public static App createHardened(int port) { + final XStream xstream = new XStream(); + xstream.addPermission(NoTypePermission.NONE); + xstream.addPermission(NullPermission.NULL); + xstream.addPermission(PrimitiveTypePermission.PRIMITIVES); + xstream.allowTypes(new Class[] { Person.class }); + return new App(port, xstream); + } + + public static App createVulnerable(int port) { + return new App(port, new XStream()); + } + + private final int port; + private final Set persons; + private final XStream xstream; + private HttpServer server; + + private App(int port, XStream xstream) { + this.port = port; + persons = new HashSet<>(); + // this app is vulnerable because XStream security is not configured + this.xstream = xstream; + this.xstream.alias("person", Person.class); + } + + void start() throws IOException { + server = HttpServer.create(new InetSocketAddress("localhost", port), 0); + server.createContext("/persons", exchange -> { + switch (exchange.getRequestMethod()) { + case "POST": + final Person person = (Person) xstream.fromXML(exchange.getRequestBody()); + persons.add(person); + exchange.sendResponseHeaders(201, 0); + exchange.close(); + break; + case "GET": + exchange.sendResponseHeaders(200, 0); + xstream.toXML(persons, exchange.getResponseBody()); + exchange.close(); + break; + default: + exchange.sendResponseHeaders(405, 0); + exchange.close(); + } + }); + server.start(); + } + + void stop() { + if (server != null) { + server.stop(0); + } + } + + int port() { + if (server == null) + throw new IllegalStateException("Server not started"); + return server.getAddress() + .getPort(); + } +} diff --git a/xstream/src/main/java/com/baeldung/rce/Person.java b/xstream/src/main/java/com/baeldung/rce/Person.java new file mode 100644 index 0000000000..336c47798b --- /dev/null +++ b/xstream/src/main/java/com/baeldung/rce/Person.java @@ -0,0 +1,43 @@ +package com.baeldung.rce; + +import java.util.Objects; + +/** Person model */ +public final class Person { + + private String first; + private String last; + + public String getFirst() { + return first; + } + + public void setFirst(String first) { + this.first = first; + } + + public String getLast() { + return last; + } + + public void setLast(String last) { + this.last = last; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Person)) { + return false; + } + Person person = (Person) o; + return Objects.equals(first, person.first) && Objects.equals(last, person.last); + } + + @Override + public int hashCode() { + return Objects.hash(first, last); + } +} diff --git a/xstream/src/test/java/com/baeldung/rce/AppUnitTest.java b/xstream/src/test/java/com/baeldung/rce/AppUnitTest.java new file mode 100644 index 0000000000..3b541ae099 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/AppUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.rce; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.SocketException; +import java.net.URL; + +import static org.junit.Assert.assertTrue; + +/** + * Unit test which demonstrates a remote code exploit against the {@link App} + * server. Sends an XML request containing an attack payload to the {@code POST} + * endpoint. + */ +public final class AppUnitTest { + + private App app; + + /** start a new web server */ + @Before + public void before() throws IOException { + app = App.createVulnerable(0); + app.start(); + } + + /** stop the web server */ + @After + public void after() { + if (app != null) + app.stop(); + } + + /** + * Test passes when an {@link IOException} is thrown because this indicates that + * the attacker caused the application to fail in some way. This does not + * actually confirm that the exploit took place, because the RCE is a + * side-effect that is difficult to observe. + */ + @Test(expected = SocketException.class) + public void givenAppIsVulneable_whenExecuteRemoteCodeWhichThrowsException_thenThrowsException() throws IOException { + // POST the attack.xml to the application's /persons endpoint + final URL url = new URL("http://localhost:" + app.port() + "/persons"); + final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setUseCaches(false); + connection.setRequestProperty("Content-Type", "application/xml"); + connection.connect(); + try (OutputStream os = connection.getOutputStream(); InputStream is = AppUnitTest.class.getResourceAsStream("/attack.xml")) { + byte[] buffer = new byte[1024]; + while (is.read(buffer) > 0) { + os.write(buffer); + } + } + final int rc = connection.getResponseCode(); + connection.disconnect(); + assertTrue(rc >= 400); + } +} diff --git a/xstream/src/test/java/com/baeldung/rce/AttackExploitedException.java b/xstream/src/test/java/com/baeldung/rce/AttackExploitedException.java new file mode 100644 index 0000000000..16c906abfc --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/AttackExploitedException.java @@ -0,0 +1,7 @@ +package com.baeldung.rce; + +/** + * Indicates a successful remote code execution attack has taken place. + */ +final class AttackExploitedException extends RuntimeException { +} diff --git a/xstream/src/test/java/com/baeldung/rce/AttackExploitedExceptionThrower.java b/xstream/src/test/java/com/baeldung/rce/AttackExploitedExceptionThrower.java new file mode 100644 index 0000000000..16ed143f7a --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/AttackExploitedExceptionThrower.java @@ -0,0 +1,13 @@ +package com.baeldung.rce; + +/** + * Class which contains an action to throw {@link AttackExploitedException}. + * This helper is used by {@link AppTest} to determine when the remote code + * exploit has taken place. + */ +final class AttackExploitedExceptionThrower { + + public void throwAttackExploitedException() { + throw new AttackExploitedException(); + } +} diff --git a/xstream/src/test/java/com/baeldung/rce/XStreamBasicsUnitTest.java b/xstream/src/test/java/com/baeldung/rce/XStreamBasicsUnitTest.java new file mode 100644 index 0000000000..d762813b22 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/XStreamBasicsUnitTest.java @@ -0,0 +1,82 @@ +package com.baeldung.rce; + +import com.thoughtworks.xstream.XStream; + +import org.junit.Before; +import org.junit.Test; + +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +/** + * Demonstrates XStream basics + */ +public final class XStreamBasicsUnitTest { + + private XStream xstream; + + @Before + public void before() { + xstream = new XStream(); + xstream.alias("person", Person.class); + } + + @Test + public void whenWritePerson_thenWritesExpectedXml() { + Person person = new Person(); + person.setFirst("John"); + person.setLast("Smith"); + + String xml = xstream.toXML(person); + + // @formatter:off + String expected = "" + + "\n" + + " John\n" + + " Smith\n" + + ""; + // @formatter:on + assertEquals(expected, xml); + + } + + @Test + public void whenReadXmlAsPerson_thenReturnsNewPerson() { + // @formatter:off + String xml = "" + + "" + + " John" + + " Smith" + + ""; + // @formatter:on + + Person person = (Person) xstream.fromXML(xml); + + Person expected = new Person(); + expected.setFirst("John"); + expected.setLast("Smith"); + assertEquals(person, expected); + } + + @Test + public void givenXmlRepresentationOfMap_whenDeserialize_thenBuildsMap() { + // @formatter:off + String xml = "" + + "" + + " " + + " foo" + + " 10" + + " " + + ""; + // @formatter:on + @SuppressWarnings("unchecked") + Map actual = (Map) xstream.fromXML(xml); + + final Map expected = Collections.singletonMap("foo", 10); + + assertEquals(expected, actual); + } + +} diff --git a/xstream/src/test/resources/attack.xml b/xstream/src/test/resources/attack.xml new file mode 100644 index 0000000000..8a5713648c --- /dev/null +++ b/xstream/src/test/resources/attack.xml @@ -0,0 +1,12 @@ + + foo + + java.lang.Comparable + + + + throwAttackExploitedException + + + diff --git a/xstream/src/test/resources/calculator-attack.xml b/xstream/src/test/resources/calculator-attack.xml new file mode 100644 index 0000000000..ae24843dc6 --- /dev/null +++ b/xstream/src/test/resources/calculator-attack.xml @@ -0,0 +1,16 @@ + + foo + + java.lang.Comparable + + + + open + /Applications/Calculator.app + + + start + + +