diff --git a/.gitignore b/.gitignore index 729dea62d5..d3a5dae06d 100644 --- a/.gitignore +++ b/.gitignore @@ -73,8 +73,6 @@ ninja/devDb.mv.db **/out-tsc **/nbproject/ **/nb-configuration.xml -core-scala/.cache-main -core-scala/.cache-tests persistence-modules/hibernate5/transaction.log diff --git a/README.md b/README.md index 5307efa008..b08a93f23e 100644 --- a/README.md +++ b/README.md @@ -22,10 +22,38 @@ This project is **a collection of small and focused tutorials** - each covering A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security. In additional to Spring, the modules here are covering a number of aspects in Java. +Profile based segregation +==================== + +We are using maven build profiles to segregate the huge list of individual projects we have in our repository. + +The projects are broadly divided into 3 list: first, second and heavy. + +Next, they are segregated further on the basis of tests that we want to execute. + +Therefore, we have a total of 6 profiles: + +| Profile | Includes | Type of test enabled | +| ----------------------- | --------------------------- | -------------------- | +| default-first | First set of projects | *UnitTest | +| integration-lite-first | First set of projects | *IntegrationTest | +| default-second | Second set of projects | *UnitTest | +| integration-lite-second | Second set of projects | *IntegrationTest | +| default-heavy | Heavy/long running projects | *UnitTest | +| integration-heavy | Heavy/long running projects | *IntegrationTest | Building the project ==================== -To do the full build, do: `mvn clean install` + +Though it should not be needed often to build the entire repository at once because we are usually concerned with a specific module. + +But if we want to, we can invoke the below command from the root of the repository if we want to build the entire repository with only Unit Tests enabled: + +`mvn clean install -Pdefault-first,default-second,default-heavy` + +or if we want to build the entire repository with Integration Tests enabled, we can do: + +`mvn clean install -Pintegration-lite-first,integration-lite-second,integration-heavy` Building a single module @@ -46,8 +74,18 @@ When you're working with an individual module, there's no need to import all of 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` +The command `mvn clean install` from within a module will run the unit tests in that module. +For Spring modules this will also run the `SpringContextTest` if present. + +To run the integration tests, use the command: + +`mvn clean install -Pintegration-lite-first` or + +`mvn clean install -Pintegration-lite-second` or + +`mvn clean install -Pintegration-heavy` + +depending on the list where our module exists diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index 00b785c1b2..dd5bbac162 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -13,6 +13,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) - [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique) - [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle) -- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency) - [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm) - More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4) diff --git a/algorithms-miscellaneous-5/README.md b/algorithms-miscellaneous-5/README.md index 87a328e446..6e0de7d64e 100644 --- a/algorithms-miscellaneous-5/README.md +++ b/algorithms-miscellaneous-5/README.md @@ -19,4 +19,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm) - [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences) - [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms) +- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher) - More articles: [[<-- prev]](/../algorithms-miscellaneous-4) diff --git a/algorithms-miscellaneous-5/pom.xml b/algorithms-miscellaneous-5/pom.xml index f2db71a6da..4131e1791d 100644 --- a/algorithms-miscellaneous-5/pom.xml +++ b/algorithms-miscellaneous-5/pom.xml @@ -41,11 +41,6 @@ guava ${guava.version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - org.junit.platform junit-platform-commons @@ -78,7 +73,6 @@ 1.11 3.6.1 28.1-jre - 2.10.2 1.6.0 diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java deleted file mode 100644 index 0f8bc5b296..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.algorithms.boruvka; - -public class BoruvkaMST { - - private static Tree mst = new Tree(); - private static int totalWeight; - - public BoruvkaMST(Graph graph) { - DisjointSet dSet = new DisjointSet(graph.getNodes()); - - // repeat at most log N times or until we have N-1 edges - for (int t = 1; t < graph.getNodes() && mst.getEdgeCount() < graph.getNodes() - 1; t = t + t) { - - // foreach tree in forest, find closest edge - Edge[] closestEdgeArray = new Edge[graph.getNodes()]; - for (Edge edge : graph.getAllEdges()) { - int first = edge.getFirst(); - int second = edge.getSecond(); - int firstParent = dSet.getParent(first); - int secondParent = dSet.getParent(second); - if (firstParent == secondParent) { - continue; // same tree - } - if (closestEdgeArray[firstParent] == null || edge.getWeight() < closestEdgeArray[firstParent].getWeight()) { - closestEdgeArray[firstParent] = edge; - } - if (closestEdgeArray[secondParent] == null || edge.getWeight() < closestEdgeArray[secondParent].getWeight()) { - closestEdgeArray[secondParent] = edge; - } - } - - // add newly discovered edges to MST - for (int i = 0; i < graph.getNodes(); i++) { - Edge edge = closestEdgeArray[i]; - if (edge != null) { - int first = edge.getFirst(); - int second = edge.getSecond(); - // don't add the same edge twice - if (dSet.getParent(first) != dSet.getParent(second)) { - mst.addEdge(edge); - totalWeight += edge.getWeight(); - dSet.union(first, second); - } - } - } - } - } - - public Iterable getMST() { - return mst; - } - - public int getTotalWeight() { - return totalWeight; - } - - public String toString() { - return "MST: " + mst.toString() + " | Total Weight: " + totalWeight; - } - -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/DisjointSet.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/DisjointSet.java deleted file mode 100644 index 7769686e36..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/DisjointSet.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.algorithms.boruvka; - -import java.util.Arrays; - -public class DisjointSet { - - private int[] nodeParents; - private int[] nodeRanks; - - public DisjointSet(int n) { - nodeParents = new int[n]; - nodeRanks = new int[n]; - for (int i = 0; i < n; i++) { - nodeParents[i] = i; - nodeRanks[i] = 0; - } - } - - public int getParent(int node) { - while (node != nodeParents[node]) { - node = nodeParents[node]; - } - return node; - } - - public void union(int node1, int node2) { - int node1Parent = getParent(node1); - int node2Parent = getParent(node2); - if (node1Parent == node2Parent) { - return; - } - - if (nodeRanks[node1Parent] < nodeRanks[node2Parent]) { - nodeParents[node1Parent] = node2Parent; - } - else if (nodeRanks[node1Parent] > nodeRanks[node2Parent]) { - nodeParents[node2Parent] = node1Parent; - } - else { - nodeParents[node2Parent] = node1Parent; - nodeRanks[node1Parent]++; - } - } - - public String toString() { - return "Parent: " + Arrays.toString(nodeParents) + "Rank: " + Arrays.toString(nodeRanks); - } - -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Edge.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Edge.java deleted file mode 100644 index 6ee136fc48..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Edge.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.algorithms.boruvka; - -public class Edge { - - private final int first; - private final int second; - private final int weight; - - public Edge(int first, int second, int weight) { - this.first = first; - this.second = second; - this.weight = weight; - } - - public double getWeight() { - return weight; - } - - public int getFirst() { - return first; - } - - public int getSecond() { - return second; - } - - public int getOtherNode(int firstNode) { - int secondNode = 0; - if (firstNode == first) - secondNode = second; - else if (firstNode == second) - secondNode = first; - return secondNode; - } - - public String toString() { - return String.format("%d-%d %d", first, second, weight); - } - -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Graph.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Graph.java deleted file mode 100644 index e899007dfa..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Graph.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.algorithms.boruvka; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; - -public class Graph { - - private int nodes; - private int edges; - private Tree[] trees; - - public Graph(Input jsonGraph) throws JsonParseException, JsonMappingException, IOException { - nodes = jsonGraph.getNodes(); - trees = (Tree[]) new Tree[nodes]; - for (int i = 0; i < nodes; i++) { - trees[i] = new Tree(); - } - - int edgesFromInput = jsonGraph.getEdges(); - for (int i = 0; i < edgesFromInput; i++) { - int first = jsonGraph.getEdgeList() - .get(i) - .getFirst(); - int second = jsonGraph.getEdgeList() - .get(i) - .getSecond(); - int weight = jsonGraph.getEdgeList() - .get(i) - .getWeight(); - Edge edge = new Edge(first, second, weight); - - trees[first].addEdge(edge); - trees[second].addEdge(edge); - edges++; - } - - } - - public int getNodes() { - return nodes; - } - - public int getEdges() { - return edges; - } - - public Iterable iterableTree(int i) { - return trees[i]; - } - - public Iterable getAllEdges() { - Iterable list = new Tree(); - for (int i = 0; i < nodes; i++) { - for (Edge edge : iterableTree(i)) { - if (edge.getOtherNode(i) > i) { - ((Tree) list).addEdge(edge); - } - } - } - return list; - } -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Input.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Input.java deleted file mode 100644 index b52720d5e9..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Input.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.algorithms.boruvka; - -import java.util.List; - -public class Input { - private int nodes; - private int edges; - private List edgeList; - - public int getNodes() { - return nodes; - } - - public void setNodes(int nodes) { - this.nodes = nodes; - } - - public int getEdges() { - return edges; - } - - public void setEdges(int edges) { - this.edges = edges; - } - - public List getEdgeList() { - return edgeList; - } - - public void setEdgeList(List edgeList) { - this.edgeList = edgeList; - } - - static class E { - private int first; - private int second; - private int weight; - - public int getFirst() { - return first; - } - - public void setFirst(int first) { - this.first = first; - } - - public int getSecond() { - return second; - } - - public void setSecond(int second) { - this.second = second; - } - - public int getWeight() { - return weight; - } - - public void setWeight(int weight) { - this.weight = weight; - } - - } - -} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Tree.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Tree.java deleted file mode 100644 index cc28233e07..0000000000 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/boruvka/Tree.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.algorithms.boruvka; - -import java.util.Iterator; - -public class Tree implements Iterable { - private Node root; - private int edgeCount; - - private static class Node { - private Edge edge; - private Node next; - - public String toString() { - String nextStr = next != null ? next.toString() : ""; - return edge.toString() + " | " + nextStr; - } - } - - public Tree() { - root = null; - edgeCount = 0; - } - - public int getEdgeCount() { - return edgeCount; - } - - public void addEdge(Edge edge) { - Node oldRoot = root; - root = new Node(); - root.edge = edge; - root.next = oldRoot; - edgeCount++; - } - - public String toString() { - String rootStr = root != null ? root.toString() : ""; - return "Tree: " + rootStr + "Size: " + edgeCount; - } - - public Iterator iterator() { - return new LinkedIterator(root); - } - - private class LinkedIterator implements Iterator { - private Node current; - - public LinkedIterator(Node root) { - current = root; - } - - public boolean hasNext() { - return current != null; - } - - public Edge next() { - Edge edge = current.edge; - current = current.next; - return edge; - } - } - -} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java deleted file mode 100644 index 1d03d2d4d9..0000000000 --- a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.algorithms.boruvka; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -import org.junit.Before; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class BoruvkaUnitTest { - - private Input input; - private static String INPUT_JSON = "/input.json"; - - @Before - public void convertInputJsonToObject() throws JsonParseException, JsonMappingException, IOException { - ObjectMapper mapper = new ObjectMapper(); - StringBuilder jsonStr = new StringBuilder(); - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(BoruvkaMST.class.getResourceAsStream(INPUT_JSON)))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - jsonStr.append(line) - .append("\n"); - } - } - - input = mapper.readValue(jsonStr.toString(), Input.class); - - } - - @Test - public void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() throws JsonParseException, JsonMappingException, IOException { - Graph graph = new Graph(input); - BoruvkaMST boruvkaMST = new BoruvkaMST(graph); - - Tree mst = (Tree) boruvkaMST.getMST(); - - assertEquals(30, boruvkaMST.getTotalWeight()); - assertEquals(4, mst.getEdgeCount()); - } - -} diff --git a/algorithms-miscellaneous-6/README.md b/algorithms-miscellaneous-6/README.md new file mode 100644 index 0000000000..99be63d7ca --- /dev/null +++ b/algorithms-miscellaneous-6/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: + +- [Boruvka’s Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm) +- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent) diff --git a/java-math-2/pom.xml b/algorithms-miscellaneous-6/pom.xml similarity index 53% rename from java-math-2/pom.xml rename to algorithms-miscellaneous-6/pom.xml index e22dcc2b31..fda9cf10f9 100644 --- a/java-math-2/pom.xml +++ b/algorithms-miscellaneous-6/pom.xml @@ -2,14 +2,26 @@ 4.0.0 - java-math-2 + algorithms-miscellaneous-6 0.0.1-SNAPSHOT - java-math-2 + algorithms-miscellaneous-6 com.baeldung parent-modules 1.0.0-SNAPSHOT + + + + com.google.guava + guava + ${guava.version} + + + + + 28.1-jre + - \ No newline at end of file + diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java new file mode 100644 index 0000000000..7dae21648c --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/BoruvkaMST.java @@ -0,0 +1,84 @@ +package com.baeldung.algorithms.boruvka; + +import com.google.common.graph.EndpointPair; +import com.google.common.graph.MutableValueGraph; +import com.google.common.graph.ValueGraphBuilder; + +public class BoruvkaMST { + + private static MutableValueGraph mst = ValueGraphBuilder.undirected() + .build(); + private static int totalWeight; + + public BoruvkaMST(MutableValueGraph graph) { + + int size = graph.nodes().size(); + + UnionFind uf = new UnionFind(size); + + // repeat at most log N times or until we have N-1 edges + for (int t = 1; t < size && mst.edges().size() < size - 1; t = t + t) { + + EndpointPair[] closestEdgeArray = new EndpointPair[size]; + + // foreach tree in graph, find closest edge + for (EndpointPair edge : graph.edges()) { + int u = edge.nodeU(); + int v = edge.nodeV(); + int uParent = uf.find(u); + int vParent = uf.find(v); + if (uParent == vParent) { + continue; // same tree + } + + int weight = graph.edgeValueOrDefault(u, v, 0); + + if (closestEdgeArray[uParent] == null) { + closestEdgeArray[uParent] = edge; + } + if (closestEdgeArray[vParent] == null) { + closestEdgeArray[vParent] = edge; + } + + int uParentWeight = graph.edgeValueOrDefault(closestEdgeArray[uParent].nodeU(), closestEdgeArray[uParent].nodeV(), 0); + int vParentWeight = graph.edgeValueOrDefault(closestEdgeArray[vParent].nodeU(), closestEdgeArray[vParent].nodeV(), 0); + + if (weight < uParentWeight) { + closestEdgeArray[uParent] = edge; + } + if (weight < vParentWeight) { + closestEdgeArray[vParent] = edge; + } + } + + // add newly discovered edges to MST + for (int i = 0; i < size; i++) { + EndpointPair edge = closestEdgeArray[i]; + if (edge != null) { + int u = edge.nodeU(); + int v = edge.nodeV(); + int weight = graph.edgeValueOrDefault(u, v, 0); + // don't add the same edge twice + if (uf.find(u) != uf.find(v)) { + mst.putEdgeValue(u, v, weight); + totalWeight += weight; + uf.union(u, v); + } + } + } + } + } + + public MutableValueGraph getMST() { + return mst; + } + + public int getTotalWeight() { + return totalWeight; + } + + public String toString() { + return "MST: " + mst.toString() + " | Total Weight: " + totalWeight; + } + +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/UnionFind.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/UnionFind.java new file mode 100644 index 0000000000..33c9c4a4c8 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/boruvka/UnionFind.java @@ -0,0 +1,39 @@ +package com.baeldung.algorithms.boruvka; + +public class UnionFind { + private int[] parents; + private int[] ranks; + + public UnionFind(int n) { + parents = new int[n]; + ranks = new int[n]; + for (int i = 0; i < n; i++) { + parents[i] = i; + ranks[i] = 0; + } + } + + public int find(int u) { + while (u != parents[u]) { + u = parents[u]; + } + return u; + } + + public void union(int u, int v) { + int uParent = find(u); + int vParent = find(v); + if (uParent == vParent) { + return; + } + + if (ranks[uParent] < ranks[vParent]) { + parents[uParent] = vParent; + } else if (ranks[uParent] > ranks[vParent]) { + parents[vParent] = uParent; + } else { + parents[vParent] = uParent; + ranks[uParent]++; + } + } +} diff --git a/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/gradientdescent/GradientDescent.java b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/gradientdescent/GradientDescent.java new file mode 100644 index 0000000000..c5db3a4a06 --- /dev/null +++ b/algorithms-miscellaneous-6/src/main/java/com/baeldung/algorithms/gradientdescent/GradientDescent.java @@ -0,0 +1,33 @@ +package com.baeldung.algorithms.gradientdescent; + +import java.util.function.Function; + +public class GradientDescent { + + private final double precision = 0.000001; + + public double findLocalMinimum(Function f, double initialX) { + double stepCoefficient = 0.1; + double previousStep = 1.0; + double currentX = initialX; + double previousX = initialX; + double previousY = f.apply(previousX); + int iter = 100; + + currentX += stepCoefficient * previousY; + + while (previousStep > precision && iter > 0) { + iter--; + double currentY = f.apply(currentX); + if (currentY > previousY) { + stepCoefficient = -stepCoefficient / 2; + } + previousX = currentX; + currentX += stepCoefficient * previousY; + previousY = currentY; + previousStep = StrictMath.abs(currentX - previousX); + } + return currentX; + } + +} diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java new file mode 100644 index 0000000000..e61e1e668d --- /dev/null +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.algorithms.boruvka; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +import com.google.common.graph.MutableValueGraph; +import com.google.common.graph.ValueGraphBuilder; + +public class BoruvkaUnitTest { + + private MutableValueGraph graph; + + @Before + public void setup() { + graph = ValueGraphBuilder.undirected() + .build(); + graph.putEdgeValue(0, 1, 8); + graph.putEdgeValue(0, 2, 5); + graph.putEdgeValue(1, 2, 9); + graph.putEdgeValue(1, 3, 11); + graph.putEdgeValue(2, 3, 15); + graph.putEdgeValue(2, 4, 10); + graph.putEdgeValue(3, 4, 7); + } + + @Test + public void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() { + BoruvkaMST boruvkaMST = new BoruvkaMST(graph); + MutableValueGraph mst = boruvkaMST.getMST(); + + assertEquals(30, boruvkaMST.getTotalWeight()); + assertEquals(4, mst.edges().size()); + } + +} diff --git a/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java new file mode 100644 index 0000000000..34d3e188f2 --- /dev/null +++ b/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.gradientdescent; + +import static org.junit.Assert.assertTrue; + +import java.util.function.Function; + +import org.junit.Test; + +public class GradientDescentUnitTest { + + @Test + public void givenFunction_whenStartingPointIsOne_thenLocalMinimumIsFound() { + Function df = x -> + StrictMath.abs(StrictMath.pow(x, 3)) - (3 * StrictMath.pow(x, 2)) + x; + GradientDescent gd = new GradientDescent(); + double res = gd.findLocalMinimum(df, 1); + assertTrue(res > 1.78); + assertTrue(res < 1.84); + } +} diff --git a/algorithms-sorting-2/README.md b/algorithms-sorting-2/README.md index 897621bc41..71c9b8f86c 100644 --- a/algorithms-sorting-2/README.md +++ b/algorithms-sorting-2/README.md @@ -1,3 +1,7 @@ ### Relevant Articles: +- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) +- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) +- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting) - [Partitioning and Sorting Arrays with Many Repeated Entries](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries) +- More articles: [[<-- prev]](/algorithms-sorting) diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java similarity index 94% rename from algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java rename to algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java index b177bd60fc..148a9a21f9 100644 --- a/algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.sort.bynumber; +package com.baeldung.algorithms.bynumber; import java.util.Comparator; diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java similarity index 100% rename from algorithms-sorting/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java rename to algorithms-sorting-2/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java similarity index 100% rename from algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java rename to algorithms-sorting-2/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java similarity index 95% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java index 2f05f62147..aaa5de87e1 100644 --- a/algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java +++ b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java @@ -1,6 +1,5 @@ -package com.baeldung.algorithms.sort.bynumber; +package com.baeldung.algorithms.bynumber; -import com.baeldung.algorithms.sort.bynumber.NaturalOrderComparators; import org.junit.Test; import java.util.ArrayList; diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java similarity index 100% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java similarity index 100% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java similarity index 100% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java diff --git a/algorithms-sorting/README.md b/algorithms-sorting/README.md index 15a5ec6e02..b4b90bf954 100644 --- a/algorithms-sorting/README.md +++ b/algorithms-sorting/README.md @@ -11,10 +11,7 @@ This module contains articles about sorting algorithms. - [Heap Sort in Java](https://www.baeldung.com/java-heap-sort) - [Shell Sort in Java](https://www.baeldung.com/java-shell-sort) - [Counting Sort in Java](https://www.baeldung.com/java-counting-sort) -- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) -- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting) - [Selection Sort in Java](https://www.baeldung.com/java-selection-sort) -- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) - [Radix Sort in Java](https://www.baeldung.com/java-radix-sort) -- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) - [Bucket Sort in Java](https://www.baeldung.com/java-bucket-sort) +- More articles: [[next -->]](/algorithms-sorintg-2) diff --git a/apache-olingo/olingo2/README.md b/apache-olingo/olingo2/README.md deleted file mode 100644 index 826cd0133e..0000000000 --- a/apache-olingo/olingo2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Intro to OData with Olingo](https://www.baeldung.com/olingo) diff --git a/atomikos/README.md b/atomikos/README.md new file mode 100644 index 0000000000..19f2e871d4 --- /dev/null +++ b/atomikos/README.md @@ -0,0 +1,7 @@ +## Atomikos + +This module contains articles about Atomikos + +### Relevant Articles: + +- [Guide Transactions Using Atomikos]() diff --git a/atomikos/pom.xml b/atomikos/pom.xml new file mode 100644 index 0000000000..881adae074 --- /dev/null +++ b/atomikos/pom.xml @@ -0,0 +1,119 @@ + + + 4.0.0 + atomikos + atomikos + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.atomikos + transactions-jdbc + ${atomikos-version} + + + com.atomikos + transactions-jms + ${atomikos-version} + + + com.atomikos + transactions-hibernate4 + ${atomikos-version} + + + org.springframework + spring-context + ${spring-version} + + + org.springframework + spring-tx + ${spring-version} + + + org.springframework.data + spring-data-jpa + 1.11.23.RELEASE + + + org.springframework + spring-test + ${spring-version} + test + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + provided + + + javax.transaction + jta + + + + + org.apache.activemq + activemq-core + 5.7.0 + + + org.apache.derby + derby + 10.8.1.2 + + + junit + junit + 4.12 + test + + + + javax.transaction + jta + 1.1 + + + org.apache.geronimo.specs + geronimo-jta_1.0.1B_spec + 1.0 + + + javax.validation + validation-api + 2.0.1.Final + + + org.hibernate.validator + hibernate-validator + 6.1.2.Final + + + javax.el + javax.el-api + 3.0.0 + + + org.glassfish.web + javax.el + 2.2.4 + + + + + 5.0.6 + 5.1.6.RELEASE + 5.4.3.Final + + + \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java new file mode 100644 index 0000000000..c51ce70dde --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.direct; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import com.atomikos.icatch.jta.UserTransactionImp; + +public class Application { + + private DataSource inventoryDataSource; + private DataSource orderDataSource; + + public Application(DataSource inventoryDataSource, DataSource orderDataSource) { + this.inventoryDataSource = inventoryDataSource; + this.orderDataSource = orderDataSource; + } + + public void placeOrder(String productId, int amount) throws Exception { + + UserTransactionImp utx = new UserTransactionImp(); + String orderId = UUID.randomUUID() + .toString(); + boolean rollback = false; + try { + utx.begin(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "update Inventory set balance = balance - " + amount + " where productId ='" + productId + "'"; + s1.executeUpdate(q1); + s1.close(); + Statement s2 = orderConnection.createStatement(); + String q2 = "insert into Orders values ( '" + orderId + "', '" + productId + "', " + amount + " )"; + s2.executeUpdate(q2); + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } catch (Exception e) { + System.out.println(e.getMessage()); + rollback = true; + } finally { + if (!rollback) + utx.commit(); + else + utx.rollback(); + } + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java new file mode 100644 index 0000000000..b480e68d8d --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java @@ -0,0 +1,41 @@ +package com.baeldung.atomikos.spring; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.springframework.transaction.annotation.Transactional; + +public class Application { + + private DataSource inventoryDataSource; + private DataSource orderDataSource; + + public Application(DataSource inventoryDataSource, DataSource orderDataSource) { + this.inventoryDataSource = inventoryDataSource; + this.orderDataSource = orderDataSource; + } + + @Transactional(rollbackFor = Exception.class) + public void placeOrder(String productId, int amount) throws Exception { + + String orderId = UUID.randomUUID() + .toString(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "update Inventory set balance = balance - " + amount + " where productId ='" + productId + "'"; + s1.executeUpdate(q1); + s1.close(); + Statement s2 = orderConnection.createStatement(); + String q2 = "insert into Orders values ( '" + orderId + "', '" + productId + "', " + amount + " )"; + s2.executeUpdate(q2); + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java new file mode 100644 index 0000000000..c6ef83c4ca --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java @@ -0,0 +1,68 @@ +package com.baeldung.atomikos.spring.config; + +import java.util.Properties; + +import javax.transaction.SystemException; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.jta.JtaTransactionManager; + +import com.atomikos.icatch.jta.UserTransactionManager; +import com.atomikos.jdbc.AtomikosDataSourceBean; +import com.baeldung.atomikos.spring.Application; + +@Configuration +@EnableTransactionManagement +public class Config { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean inventoryDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db1"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db1"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean orderDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db2"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db2"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean(initMethod = "init", destroyMethod = "close") + public UserTransactionManager userTransactionManager() throws SystemException { + UserTransactionManager userTransactionManager = new UserTransactionManager(); + userTransactionManager.setTransactionTimeout(300); + userTransactionManager.setForceShutdown(true); + return userTransactionManager; + } + + @Bean + public JtaTransactionManager jtaTransactionManager() throws SystemException { + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(); + jtaTransactionManager.setTransactionManager(userTransactionManager()); + jtaTransactionManager.setUserTransaction(userTransactionManager()); + return jtaTransactionManager; + } + + @Bean + public Application application() { + return new Application(inventoryDataSource(), orderDataSource()); + } +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java new file mode 100644 index 0000000000..cf1fef2cd8 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java @@ -0,0 +1,48 @@ +package com.baeldung.atomikos.spring.jpa; + +import java.util.Set; +import java.util.UUID; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.atomikos.spring.jpa.inventory.Inventory; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryRepository; +import com.baeldung.atomikos.spring.jpa.order.Order; +import com.baeldung.atomikos.spring.jpa.order.OrderRepository; + +public class Application { + + @Autowired + private InventoryRepository inventoryRepository; + + @Autowired + private OrderRepository orderRepository; + + @Transactional(rollbackFor = Exception.class) + public void placeOrder(String productId, int amount) throws Exception { + + String orderId = UUID.randomUUID() + .toString(); + Inventory inventory = inventoryRepository.findOne(productId); + inventory.setBalance(inventory.getBalance() - amount); + inventoryRepository.save(inventory); + Order order = new Order(); + order.setOrderId(orderId); + order.setProductId(productId); + order.setAmount(new Long(amount)); + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> violations = validator.validate(order); + if (violations.size() > 0) + throw new Exception("Invalid instance of an order."); + orderRepository.save(order); + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java new file mode 100644 index 0000000000..6716f19576 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java @@ -0,0 +1,38 @@ +package com.baeldung.atomikos.spring.jpa.config; + +import javax.transaction.SystemException; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.jta.JtaTransactionManager; + +import com.atomikos.icatch.jta.UserTransactionManager; +import com.baeldung.atomikos.spring.jpa.Application; + +@Configuration +@EnableTransactionManagement +public class Config { + + @Bean(initMethod = "init", destroyMethod = "close") + public UserTransactionManager userTransactionManager() throws SystemException { + UserTransactionManager userTransactionManager = new UserTransactionManager(); + userTransactionManager.setTransactionTimeout(300); + userTransactionManager.setForceShutdown(true); + return userTransactionManager; + } + + @Bean + public JtaTransactionManager transactionManager() throws SystemException { + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(); + jtaTransactionManager.setTransactionManager(userTransactionManager()); + jtaTransactionManager.setUserTransaction(userTransactionManager()); + return jtaTransactionManager; + } + + @Bean + public Application application() { + return new Application(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java new file mode 100644 index 0000000000..999879218c --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java @@ -0,0 +1,31 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "INVENTORY") +public class Inventory { + + @Id + private String productId; + private Long balance; + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public Long getBalance() { + return balance; + } + + public void setBalance(Long balance) { + this.balance = balance; + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java new file mode 100644 index 0000000000..5301ad6ff2 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +import com.atomikos.jdbc.AtomikosDataSourceBean; + +@Configuration +@EnableJpaRepositories(basePackages = "com.baeldung.atomikos.spring.jpa.inventory", entityManagerFactoryRef = "inventoryEntityManager", transactionManagerRef = "transactionManager") +public class InventoryConfig { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean inventoryDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db1"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db1"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean + public EntityManagerFactory inventoryEntityManager() { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(vendorAdapter); + factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.inventory"); + factory.setDataSource(inventoryDataSource()); + Properties jpaProperties = new Properties(); + //jpaProperties.put("hibernate.show_sql", "true"); + //jpaProperties.put("hibernate.format_sql", "true"); + jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); + jpaProperties.put("hibernate.current_session_context_class", "jta"); + jpaProperties.put("javax.persistence.transactionType", "jta"); + jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"); + jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop"); + factory.setJpaProperties(jpaProperties); + factory.afterPropertiesSet(); + return factory.getObject(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java new file mode 100644 index 0000000000..c3868e51bf --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface InventoryRepository extends JpaRepository { + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java new file mode 100644 index 0000000000..4b9ae2dd1d --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java @@ -0,0 +1,42 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.Max; + +@Entity +@Table(name = "ORDERS") +public class Order { + + @Id + private String orderId; + private String productId; + @Max(5) + private Long amount; + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public Long getAmount() { + return amount; + } + + public void setAmount(Long amount) { + this.amount = amount; + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java new file mode 100644 index 0000000000..b4274bb64c --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +import com.atomikos.jdbc.AtomikosDataSourceBean; + +@Configuration +@EnableJpaRepositories(basePackages = "com.baeldung.atomikos.spring.jpa.order", entityManagerFactoryRef = "orderEntityManager", transactionManagerRef = "transactionManager") +public class OrderConfig { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean orderDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db2"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db2"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean + public EntityManagerFactory orderEntityManager() { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(vendorAdapter); + factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.order"); + factory.setDataSource(orderDataSource()); + Properties jpaProperties = new Properties(); + //jpaProperties.put("hibernate.show_sql", "true"); + //jpaProperties.put("hibernate.format_sql", "true"); + jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); + jpaProperties.put("hibernate.current_session_context_class", "jta"); + jpaProperties.put("javax.persistence.transactionType", "jta"); + jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"); + jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop"); + factory.setJpaProperties(jpaProperties); + factory.afterPropertiesSet(); + return factory.getObject(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java new file mode 100644 index 0000000000..2d5610ebca --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface OrderRepository extends JpaRepository { + +} diff --git a/java-collections-maps/src/main/resources/logback.xml b/atomikos/src/main/resources/logback.xml similarity index 100% rename from java-collections-maps/src/main/resources/logback.xml rename to atomikos/src/main/resources/logback.xml diff --git a/atomikos/src/main/resources/schema.sql b/atomikos/src/main/resources/schema.sql new file mode 100644 index 0000000000..5136ad1284 --- /dev/null +++ b/atomikos/src/main/resources/schema.sql @@ -0,0 +1,10 @@ +CREATE TABLE INVENTORY ( + productId VARCHAR PRIMARY KEY, + balance INT +); + +CREATE TABLE ORDERS ( + orderId VARCHAR PRIMARY KEY, + productId VARCHAR, + amount INT NOT NULL CHECK (amount <= 5) +); \ No newline at end of file diff --git a/atomikos/src/main/resources/transactions.properties b/atomikos/src/main/resources/transactions.properties new file mode 100644 index 0000000000..8e027032fa --- /dev/null +++ b/atomikos/src/main/resources/transactions.properties @@ -0,0 +1 @@ +com.atomikos.icatch.file=logs \ No newline at end of file diff --git a/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java new file mode 100644 index 0000000000..1a467807ba --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java @@ -0,0 +1,118 @@ +package com.baeldung.atomikos.direct; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import com.atomikos.icatch.jta.UserTransactionImp; +import com.atomikos.jdbc.AtomikosDataSourceBean; + +public class ApplicationUnitTest { + + private static DataSource inventoryDataSource; + private static DataSource orderDataSource; + + private static String productId = UUID.randomUUID() + .toString(); + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryDataSource, productId); + Application application = new Application(inventoryDataSource, orderDataSource); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryDataSource, productId); + Application application = new Application(inventoryDataSource, orderDataSource); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance, finalBalance); + } + + @BeforeClass + public static void setUp() throws SQLException { + + inventoryDataSource = getDataSource("db1"); + orderDataSource = getDataSource("db2"); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + String createInventoryTable = "create table Inventory ( " + " productId VARCHAR ( 100 ) PRIMARY KEY, balance INT )"; + String createInventoryRow = "insert into Inventory values ( '" + productId + "', 10000 )"; + Statement s1 = inventoryConnection.createStatement(); + try { + s1.executeUpdate(createInventoryTable); + } catch (Exception e) { + System.out.println("Inventory table exists"); + } + try { + s1.executeUpdate(createInventoryRow); + } catch (Exception e) { + System.out.println("Product row exists"); + } + s1.close(); + String createOrderTable = "create table Orders ( orderId VARCHAR ( 100 ) PRIMARY KEY, productId VARCHAR ( 100 ), amount INT NOT NULL CHECK (amount <= 5) )"; + Statement s2 = orderConnection.createStatement(); + try { + s2.executeUpdate(createOrderTable); + } catch (Exception e) { + System.out.println("Orders table exists"); + } + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } + + private static DataSource getDataSource(String db) { + + DataSource ds; + AtomikosDataSourceBean ads = new AtomikosDataSourceBean(); + ads.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties properties = new Properties(); + properties.put("databaseName", db); + properties.put("createDatabase", "create"); + ads.setXaProperties(properties); + ads.setUniqueResourceName(db); + ads.setPoolSize(10); // optional + ads.setBorrowConnectionTimeout(10); // optional + ds = ads; + return ds; + + } + + private static long getBalance(DataSource inventoryDataSource, String productId) throws Exception { + + UserTransactionImp utx = new UserTransactionImp(); + utx.begin(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "select balance from Inventory where productId='" + productId + "'"; + ResultSet rs1 = s1.executeQuery(q1); + if (rs1 == null || !rs1.next()) + throw new Exception("Product not found: " + productId); + long balance = rs1.getLong(1); + inventoryConnection.close(); + utx.commit(); + return balance; + + } + +} diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java new file mode 100644 index 0000000000..0c9392eac4 --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java @@ -0,0 +1,108 @@ +package com.baeldung.atomikos.spring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.atomikos.spring.config.Config; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Config.class }) +public class ApplicationUnitTest { + + private static String productId = UUID.randomUUID() + .toString(); + + @Autowired + Application application; + + @Autowired + DataSource inventoryDataSource; + + @Autowired + DataSource orderDataSource; + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryDataSource, productId); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryDataSource, productId); + try { + application.placeOrder(productId, amount); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance, finalBalance); + } + + @Before + public void setUp() throws SQLException { + + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + String createInventoryTable = "create table Inventory ( " + " productId VARCHAR ( 100 ) PRIMARY KEY, balance INT )"; + String createInventoryRow = "insert into Inventory values ( '" + productId + "', 10000 )"; + Statement s1 = inventoryConnection.createStatement(); + try { + s1.executeUpdate(createInventoryTable); + } catch (Exception e) { + System.out.println("Inventory table exists"); + } + try { + s1.executeUpdate(createInventoryRow); + } catch (Exception e) { + System.out.println("Product row exists"); + } + s1.close(); + String createOrderTable = "create table Orders ( orderId VARCHAR ( 100 ) PRIMARY KEY, productId VARCHAR ( 100 ), amount INT NOT NULL CHECK (amount <= 5) )"; + Statement s2 = orderConnection.createStatement(); + try { + s2.executeUpdate(createOrderTable); + } catch (Exception e) { + System.out.println("Orders table exists"); + } + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } + + private static long getBalance(DataSource inventoryDataSource, String productId) throws Exception { + + Connection inventoryConnection = inventoryDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "select balance from Inventory where productId='" + productId + "'"; + ResultSet rs1 = s1.executeQuery(q1); + if (rs1 == null || !rs1.next()) + throw new Exception("Product not found: " + productId); + long balance = rs1.getLong(1); + inventoryConnection.close(); + return balance; + + } + +} diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java new file mode 100644 index 0000000000..e6a3c1982c --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.atomikos.spring.jpa; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.SQLException; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.atomikos.spring.jpa.config.Config; +import com.baeldung.atomikos.spring.jpa.inventory.Inventory; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryConfig; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryRepository; +import com.baeldung.atomikos.spring.jpa.order.OrderConfig; +import com.baeldung.atomikos.spring.jpa.order.OrderRepository; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Config.class, InventoryConfig.class, OrderConfig.class }) +public class ApplicationUnitTest { + + private static String productId = UUID.randomUUID() + .toString(); + + @Autowired + Application application; + + @Autowired + InventoryRepository inventoryRepository; + + @Autowired + OrderRepository orderRepository; + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryRepository, productId); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryRepository, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryRepository, productId); + try { + application.placeOrder(productId, amount); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + long finalBalance = getBalance(inventoryRepository, productId); + assertEquals(initialBalance, finalBalance); + } + + @Before + public void setUp() throws SQLException { + + Inventory inventory = new Inventory(); + inventory.setProductId(productId); + inventory.setBalance(new Long(10000)); + inventoryRepository.save(inventory); + + } + + private static long getBalance(InventoryRepository inventoryRepository, String productId) throws Exception { + + return inventoryRepository.findOne(productId) + .getBalance(); + + } + +} diff --git a/java-math-2/src/main/resources/logback.xml b/atomikos/src/test/resources/logback.xml similarity index 100% rename from java-math-2/src/main/resources/logback.xml rename to atomikos/src/test/resources/logback.xml diff --git a/atomikos/src/test/resources/transactions.properties b/atomikos/src/test/resources/transactions.properties new file mode 100644 index 0000000000..8e027032fa --- /dev/null +++ b/atomikos/src/test/resources/transactions.properties @@ -0,0 +1 @@ +com.atomikos.icatch.file=logs \ No newline at end of file diff --git a/aws-reactive/pom.xml b/aws-reactive/pom.xml index 950b3f373a..d4f0e5e231 100644 --- a/aws-reactive/pom.xml +++ b/aws-reactive/pom.xml @@ -16,12 +16,6 @@ aws-reactive AWS Reactive Sample - - 1.8 - 2.2.1.RELEASE - 2.10.27 - - @@ -105,4 +99,9 @@ + + 1.8 + 2.2.1.RELEASE + 2.10.27 + diff --git a/bazel/bazelgreeting/README.md b/bazel/bazelgreeting/README.md deleted file mode 100644 index 528f797c21..0000000000 --- a/bazel/bazelgreeting/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool) diff --git a/cas/README.md b/cas/README.md index 16775a8a02..6ceeaea0c4 100644 --- a/cas/README.md +++ b/cas/README.md @@ -1,7 +1,18 @@ ## CAS -This module contains articles about the Central Authentication Service (CAS) +This module contains articles about the Central Authentication Service (CAS). + +The module consists of 2 submodules: +1. `cas-server` - it requires JDK11 and uses the Gradle War Overlay style to ease setup and deployment. To start the server, simply run: + +`./gradlew run + -Dorg.gradle.java.home=$JAVA11_HOME + -Pargs="-Dcas.standalone.configurationDirectory=/cas-server/src/main/resources/etc/cas/config"` + +The server starts at https://localhost:8443. `casuser`/`Mellon` are the username and password for logging in. + +2. `cas-secured-app` - A Maven based Springboot Application ### Relevant Articles: -- [CAS SSO With Spring Security](baeldung.com/spring-security-cas-sso) \ No newline at end of file +- [CAS SSO With Spring Security](https://www.baeldung.com/spring-security-cas-sso) \ No newline at end of file diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 8e6f28e3a8..426d65c32b 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -11,11 +11,15 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 + + 2.2.6.RELEASE + + org.springframework.boot diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java deleted file mode 100644 index 25cbb9bc9b..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.cassecuredapp; - -import org.jasig.cas.client.session.SingleSignOutFilter; -import org.jasig.cas.client.session.SingleSignOutHttpSessionListener; -import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; -import org.jasig.cas.client.validation.TicketValidator; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Primary; -import org.springframework.context.event.EventListener; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.cas.web.CasAuthenticationEntryPoint; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.logout.LogoutFilter; -import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; - -import javax.servlet.http.HttpSessionEvent; - -@SpringBootApplication -public class CasSecuredAppApplication { - - public static void main(String[] args) { - SpringApplication.run(CasSecuredAppApplication.class, args); - } - - @Bean - public ServiceProperties serviceProperties() { - ServiceProperties serviceProperties = new ServiceProperties(); - serviceProperties.setService("http://localhost:9000/login/cas"); - serviceProperties.setSendRenew(false); - return serviceProperties; - } - - @Bean - @Primary - public AuthenticationEntryPoint authenticationEntryPoint(ServiceProperties sP) { - CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); - entryPoint.setLoginUrl("https://localhost:6443/cas/login"); - entryPoint.setServiceProperties(sP); - return entryPoint; - } - - @Bean - public TicketValidator ticketValidator() { - return new Cas30ServiceTicketValidator("https://localhost:6443/cas"); - } - - @Bean - public CasAuthenticationProvider casAuthenticationProvider() { - CasAuthenticationProvider provider = new CasAuthenticationProvider(); - provider.setServiceProperties(serviceProperties()); - provider.setTicketValidator(ticketValidator()); - provider.setUserDetailsService((s) -> new User("test@test.com", "smatt", - true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); - provider.setKey("CAS_PROVIDER_LOCALHOST_9000"); - return provider; - } - - - @Bean - public SecurityContextLogoutHandler securityContextLogoutHandler() { - return new SecurityContextLogoutHandler(); - } - - @Bean - public LogoutFilter logoutFilter() { - LogoutFilter logoutFilter = new LogoutFilter( - "https://localhost:6443/cas/logout", securityContextLogoutHandler()); - logoutFilter.setFilterProcessesUrl("/logout/cas"); - return logoutFilter; - } - - @Bean - public SingleSignOutFilter singleSignOutFilter() { - SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); - singleSignOutFilter.setCasServerUrlPrefix("https://localhost:6443/cas"); - singleSignOutFilter.setIgnoreInitConfiguration(true); - return singleSignOutFilter; - } - - @EventListener - public SingleSignOutHttpSessionListener singleSignOutHttpSessionListener(HttpSessionEvent event) { - return new SingleSignOutHttpSessionListener(); - } -} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java new file mode 100644 index 0000000000..4a2c609758 --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java @@ -0,0 +1,97 @@ +package com.baeldung.cassecuredapp; + +import org.jasig.cas.client.session.SingleSignOutFilter; +import org.jasig.cas.client.session.SingleSignOutHttpSessionListener; +import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; +import org.jasig.cas.client.validation.TicketValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.context.event.EventListener; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.cas.ServiceProperties; +import org.springframework.security.cas.authentication.CasAuthenticationProvider; +import org.springframework.security.cas.web.CasAuthenticationEntryPoint; +import org.springframework.security.cas.web.CasAuthenticationFilter; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; +import org.springframework.security.web.authentication.logout.LogoutFilter; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; + +import javax.servlet.http.HttpSessionEvent; + +@SpringBootApplication +public class CasSecuredApplication { + + private static final Logger logger = LoggerFactory.getLogger(CasSecuredApplication.class); + + public static void main(String... args) { + SpringApplication.run(CasSecuredApplication.class, args); + } + + @Bean + public CasAuthenticationFilter casAuthenticationFilter( + AuthenticationManager authenticationManager, + ServiceProperties serviceProperties) throws Exception { + CasAuthenticationFilter filter = new CasAuthenticationFilter(); + filter.setAuthenticationManager(authenticationManager); + filter.setServiceProperties(serviceProperties); + return filter; + } + + @Bean + public ServiceProperties serviceProperties() { + logger.info("service properties"); + ServiceProperties serviceProperties = new ServiceProperties(); + serviceProperties.setService("http://cas-client:8900/login/cas"); + serviceProperties.setSendRenew(false); + return serviceProperties; + } + + @Bean + public TicketValidator ticketValidator() { + return new Cas30ServiceTicketValidator("https://localhost:8443"); + } + + @Bean + public CasAuthenticationProvider casAuthenticationProvider( + TicketValidator ticketValidator, + ServiceProperties serviceProperties) { + CasAuthenticationProvider provider = new CasAuthenticationProvider(); + provider.setServiceProperties(serviceProperties); + provider.setTicketValidator(ticketValidator); + provider.setUserDetailsService( + s -> new User("test@test.com", "Mellon", true, true, true, true, + AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); + provider.setKey("CAS_PROVIDER_LOCALHOST_8900"); + return provider; + } + + + @Bean + public SecurityContextLogoutHandler securityContextLogoutHandler() { + return new SecurityContextLogoutHandler(); + } + + @Bean + public LogoutFilter logoutFilter() { + LogoutFilter logoutFilter = new LogoutFilter("https://localhost:8443/logout", securityContextLogoutHandler()); + logoutFilter.setFilterProcessesUrl("/logout/cas"); + return logoutFilter; + } + + @Bean + public SingleSignOutFilter singleSignOutFilter() { + SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); + singleSignOutFilter.setCasServerUrlPrefix("https://localhost:8443"); + singleSignOutFilter.setLogoutCallbackPath("/exit/cas"); + singleSignOutFilter.setIgnoreInitConfiguration(true); + return singleSignOutFilter; + } + +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java deleted file mode 100644 index 2eabed49e1..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.cassecuredapp.config; - -import org.jasig.cas.client.session.SingleSignOutFilter; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.ProviderManager; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.cas.web.CasAuthenticationFilter; -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.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.logout.LogoutFilter; - -import java.util.Arrays; - -@EnableWebSecurity -@Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - private AuthenticationProvider authenticationProvider; - private AuthenticationEntryPoint authenticationEntryPoint; - private SingleSignOutFilter singleSignOutFilter; - private LogoutFilter logoutFilter; - - @Autowired - public SecurityConfig(CasAuthenticationProvider casAuthenticationProvider, AuthenticationEntryPoint eP, - LogoutFilter lF - , SingleSignOutFilter ssF - ) { - this.authenticationProvider = casAuthenticationProvider; - this.authenticationEntryPoint = eP; - - this.logoutFilter = lF; - this.singleSignOutFilter = ssF; - - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .regexMatchers("/secured.*", "/login") - .authenticated() - .and() - .authorizeRequests() - .regexMatchers("/") - .permitAll() - .and() - .httpBasic() - .authenticationEntryPoint(authenticationEntryPoint) - .and() - .logout().logoutSuccessUrl("/logout") - .and() - .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) - .addFilterBefore(logoutFilter, LogoutFilter.class); - - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(authenticationProvider); - } - - @Override - protected AuthenticationManager authenticationManager() throws Exception { - return new ProviderManager(Arrays.asList(authenticationProvider)); - } - - @Bean - public CasAuthenticationFilter casAuthenticationFilter(ServiceProperties sP) throws Exception { - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setServiceProperties(sP); - filter.setAuthenticationManager(authenticationManager()); - return filter; - } - -} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java new file mode 100644 index 0000000000..b0c3c68387 --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java @@ -0,0 +1,79 @@ +package com.baeldung.cassecuredapp.config; + +import org.jasig.cas.client.session.SingleSignOutFilter; +import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; +import org.jasig.cas.client.validation.TicketValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.cas.ServiceProperties; +import org.springframework.security.cas.authentication.CasAuthenticationProvider; +import org.springframework.security.cas.web.CasAuthenticationEntryPoint; +import org.springframework.security.cas.web.CasAuthenticationFilter; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.authentication.logout.LogoutFilter; + +import java.util.Collections; + +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class); + private SingleSignOutFilter singleSignOutFilter; + private LogoutFilter logoutFilter; + private CasAuthenticationProvider casAuthenticationProvider; + private ServiceProperties serviceProperties; + + @Autowired + public WebSecurityConfig(SingleSignOutFilter singleSignOutFilter, LogoutFilter logoutFilter, + CasAuthenticationProvider casAuthenticationProvider, + ServiceProperties serviceProperties) { + this.logoutFilter = logoutFilter; + this.singleSignOutFilter = singleSignOutFilter; + this.serviceProperties = serviceProperties; + this.casAuthenticationProvider = casAuthenticationProvider; + } + + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().antMatchers( "/secured", "/login").authenticated() + .and() + .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()) + .and() + .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) + .addFilterBefore(logoutFilter, LogoutFilter.class) + .csrf().ignoringAntMatchers("/exit/cas"); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(casAuthenticationProvider); + } + + @Bean + @Override + protected AuthenticationManager authenticationManager() throws Exception { + return new ProviderManager(Collections.singletonList(casAuthenticationProvider)); + } + + public AuthenticationEntryPoint authenticationEntryPoint() { + CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); + entryPoint.setLoginUrl("https://localhost:8443/login"); + entryPoint.setServiceProperties(serviceProperties); + return entryPoint; + } + + + +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java index 2c88b74a83..16254c8cbd 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java @@ -1,7 +1,7 @@ package com.baeldung.cassecuredapp.controllers; -import org.apache.log4j.LogManager; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler; @@ -13,24 +13,27 @@ import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY; + @Controller public class AuthController { - private Logger logger = LogManager.getLogger(AuthController.class); - - @GetMapping("/logout") - public String logout( - HttpServletRequest request, HttpServletResponse response, SecurityContextLogoutHandler logoutHandler) { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - logoutHandler.logout(request, response, auth ); - new CookieClearingLogoutHandler(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY).logout(request, response, auth); - return "auth/logout"; - } - + private Logger logger = LoggerFactory.getLogger(AuthController.class); @GetMapping("/login") public String login() { + logger.info("/login called"); return "redirect:/secured"; } + + @GetMapping("/logout") + public String logout(HttpServletRequest request, HttpServletResponse response, SecurityContextLogoutHandler logoutHandler) { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + CookieClearingLogoutHandler cookieClearingLogoutHandler = new CookieClearingLogoutHandler(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + cookieClearingLogoutHandler.logout(request, response, auth); + logoutHandler.logout(request, response, auth); + return "auth/logout"; + } + } diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java index 75956cf493..d4800206d4 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java @@ -1,15 +1,19 @@ package com.baeldung.cassecuredapp.controllers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - @Controller public class IndexController { + private Logger logger = LoggerFactory.getLogger(IndexController.class); + @GetMapping("/") public String index() { + logger.info("Index controller called"); return "index"; } + } diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java new file mode 100644 index 0000000000..0b3ab6199f --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java @@ -0,0 +1,30 @@ +package com.baeldung.cassecuredapp.controllers; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class SecuredController { + + private Logger logger = LoggerFactory.getLogger(SecuredController.class); + + @GetMapping("/secured") + public String securedIndex(ModelMap modelMap) { + + logger.info("/secured called"); + + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); + + if(auth.getPrincipal() instanceof UserDetails) + modelMap.put("username", ((UserDetails) auth.getPrincipal()).getUsername()); + + return "secure/index"; + } +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java deleted file mode 100644 index 9a872d1f40..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.cassecuredapp.controllers; - -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping(value = "/secured") -public class SecuredPageController { - - @GetMapping - public String index(ModelMap modelMap) { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if( auth != null && auth.getPrincipal() != null - && auth.getPrincipal() instanceof UserDetails) { - modelMap.put("username", ((UserDetails) auth.getPrincipal()).getUsername()); - } - return "secure/index"; - } -} diff --git a/cas/cas-secured-app/src/main/resources/application.properties b/cas/cas-secured-app/src/main/resources/application.properties index 99802c632f..f8789997d5 100644 --- a/cas/cas-secured-app/src/main/resources/application.properties +++ b/cas/cas-secured-app/src/main/resources/application.properties @@ -1 +1,2 @@ -server.port=9000 \ No newline at end of file +server.port=8900 +spring.freemarker.suffix=.ftl \ No newline at end of file diff --git a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java similarity index 84% rename from cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java rename to cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java index 2f2644e2ea..de13f6665d 100644 --- a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java +++ b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class CasSecuredAppApplicationIntegrationTest { +public class CasSecuredApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/cas/cas-server/.factorypath b/cas/cas-server/.factorypath deleted file mode 100644 index 006c761796..0000000000 --- a/cas/cas-server/.factorypath +++ /dev/null @@ -1,228 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/.gitignore b/cas/cas-server/.gitignore old mode 100644 new mode 100755 index 5304519922..6121b5ea9d --- a/cas/cas-server/.gitignore +++ b/cas/cas-server/.gitignore @@ -2,6 +2,8 @@ !/.project .project .settings +.history +.vscode target/ .idea/ .DS_Store @@ -9,6 +11,11 @@ target/ overlays/ .gradle/ build/ +log/ bin/ +*.war *.iml *.log +tmp/ +./apache-tomcat +apache-tomcat.zip \ No newline at end of file diff --git a/cas/cas-server/.mergify.yml b/cas/cas-server/.mergify.yml new file mode 100644 index 0000000000..4fcbdbe4ac --- /dev/null +++ b/cas/cas-server/.mergify.yml @@ -0,0 +1,32 @@ +# +# Licensed to Apereo under one or more contributor license +# agreements. See the NOTICE file distributed with this work +# for additional information regarding copyright ownership. +# Apereo licenses this file to you under the Apache License, +# Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a +# copy of the License at the following location: +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +pull_request_rules: +- name: automatic merge by dependabot + conditions: + - status-success=continuous-integration/travis-ci/pr + - status-success=WIP + - "#changes-requested-reviews-by=0" + - base=master + - label=dependencies + actions: + merge: + method: merge + strict: true + delete_head_branch: \ No newline at end of file diff --git a/cas/cas-server/.travis.yml b/cas/cas-server/.travis.yml new file mode 100644 index 0000000000..8347dd1719 --- /dev/null +++ b/cas/cas-server/.travis.yml @@ -0,0 +1,62 @@ +language: java +sudo: required +dist: trusty +services: + - docker +branches: + only: + - master +before_cache: + - rm -rf $HOME/.gradle/caches/5.*/ + - rm -rf $HOME/.gradle/caches/4.*/ + - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ + - find ~/.gradle/caches/ -name "*.lock" -type f -delete +cache: + bundler: false + cargo: false + directories: + - $HOME/.m2 + - $HOME/.npm/ + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ +env: + global: + - JAVA_OPTS="-Xms512m -Xmx4048m -Xss128m -XX:ReservedCodeCacheSize=512m -XX:+UseG1GC -Xverify:none -server" + - GRADLE_OPTS="-Xms512m -Xmx1024m -Xss128m -XX:ReservedCodeCacheSize=512m -XX:+UseG1GC -Xverify:none -server" +jdk: +- openjdk11 +before_install: +- echo -e "Configuring Gradle wrapper...\n" +- mkdir -p ~/.gradle && echo "org.gradle.daemon=false" >> ~/.gradle/gradle.properties +- chmod -R 777 ./gradlew +- chmod -R 777 *.sh +install: true +stages: + - build + - validate + - docker +jobs: + include: + - stage: build + script: ./gradlew clean build --stacktrace --no-daemon --refresh-dependencies -Dorg.gradle.internal.http.socketTimeout=600000 -Dorg.gradle.internal.http.connectionTimeout=600000 + name: "Build CAS" + ############################################ + - stage: validate + script: ./gradlew downloadShell + name: "Download CAS Shell" + - stage: validate + script: ./gradlew listTemplateViews + name: "List CAS Template Views" + - stage: validate + script: ./gradlew explodeWar + name: "Unzip CAS Web Application" + ############################################ + - stage: docker + script: ./gradlew build jibDockerBuild --stacktrace --no-daemon --refresh-dependencies + name: "Build Docker Image via Jib" + - stage: docker + script: docker-compose build + name: "Build Docker Image via Docker Compose" + - stage: docker + script: ./docker-build.sh + name: "Build Docker Image" \ No newline at end of file diff --git a/cas/cas-server/Dockerfile b/cas/cas-server/Dockerfile new file mode 100644 index 0000000000..b2f15ef4c3 --- /dev/null +++ b/cas/cas-server/Dockerfile @@ -0,0 +1,40 @@ +FROM adoptopenjdk/openjdk11:alpine-slim AS overlay + +RUN mkdir -p cas-overlay +COPY ./src cas-overlay/src/ +COPY ./gradle/ cas-overlay/gradle/ +COPY ./gradlew ./settings.gradle ./build.gradle ./gradle.properties /cas-overlay/ + +RUN mkdir -p ~/.gradle \ + && echo "org.gradle.daemon=false" >> ~/.gradle/gradle.properties \ + && echo "org.gradle.configureondemand=true" >> ~/.gradle/gradle.properties \ + && cd cas-overlay \ + && chmod 750 ./gradlew \ + && ./gradlew --version; + +RUN cd cas-overlay \ + && ./gradlew clean build --parallel; + +FROM adoptopenjdk/openjdk11:alpine-jre AS cas + +LABEL "Organization"="Apereo" +LABEL "Description"="Apereo CAS" + +RUN cd / \ + && mkdir -p /etc/cas/config \ + && mkdir -p /etc/cas/services \ + && mkdir -p /etc/cas/saml \ + && mkdir -p cas-overlay; + +COPY etc/cas/ /etc/cas/ +COPY etc/cas/config/ /etc/cas/config/ +COPY etc/cas/services/ /etc/cas/services/ +COPY etc/cas/saml/ /etc/cas/saml/ +COPY --from=overlay cas-overlay/build/libs/cas.war cas-overlay/ + +EXPOSE 8080 8443 + +ENV PATH $PATH:$JAVA_HOME/bin:. + +WORKDIR cas-overlay +ENTRYPOINT ["java", "-server", "-noverify", "-Xmx2048M", "-jar", "cas.war"] diff --git a/cas/cas-server/README.md b/cas/cas-server/README.md deleted file mode 100644 index 44cfa2246c..0000000000 --- a/cas/cas-server/README.md +++ /dev/null @@ -1,105 +0,0 @@ -CAS Overlay Template -============================ - -Generic CAS WAR overlay to exercise the latest versions of CAS. This overlay could be freely used as a starting template for local CAS war overlays. The CAS services management overlay is available [here](https://github.com/apereo/cas-services-management-overlay). - -# Versions - -```xml -5.3.x -``` - -# Requirements - -* JDK 1.8+ - -# Configuration - -The `etc` directory contains the configuration files and directories that need to be copied to `/etc/cas/config`. - -# Build - -To see what commands are available to the build script, run: - -```bash -./build.sh help -``` - -To package the final web application, run: - -```bash -./build.sh package -``` - -To update `SNAPSHOT` versions run: - -```bash -./build.sh package -U -``` - -# Deployment - -- Create a keystore file `thekeystore` under `/etc/cas`. Use the password `changeit` for both the keystore and the key/certificate entries. -- Ensure the keystore is loaded up with keys and certificates of the server. - -On a successful deployment via the following methods, CAS will be available at: - -* `http://cas.server.name:8080/cas` -* `https://cas.server.name:8443/cas` - -## Executable WAR - -Run the CAS web application as an executable WAR. - -```bash -./build.sh run -``` - -## Spring Boot - -Run the CAS web application as an executable WAR via Spring Boot. This is most useful during development and testing. - -```bash -./build.sh bootrun -``` - -### Warning! - -Be careful with this method of deployment. `bootRun` is not designed to work with already executable WAR artifacts such that CAS server web application. YMMV. Today, uses of this mode ONLY work when there is **NO OTHER** dependency added to the build script and the `cas-server-webapp` is the only present module. See [this issue](https://github.com/spring-projects/spring-boot/issues/8320) for more info. - - -## Spring Boot App Server Selection - -There is an app.server property in the `pom.xml` that can be used to select a spring boot application server. -It defaults to `-tomcat` but `-jetty` and `-undertow` are supported. - -It can also be set to an empty value (nothing) if you want to deploy CAS to an external application server of your choice. - -```xml --tomcat -``` - -## Windows Build - -If you are building on windows, try `build.cmd` instead of `build.sh`. Arguments are similar but for usage, run: - -``` -build.cmd help -``` - -## External - -Deploy resultant `target/cas.war` to a servlet container of choice. - - -## Command Line Shell - -Invokes the CAS Command Line Shell. For a list of commands either use no arguments or use `-h`. To enter the interactive shell use `-sh`. - -```bash -./build.sh cli -``` - -### Relevant Articles: - -- [CAS SSO With Spring Security](https://www.baeldung.com/spring-security-cas-sso) diff --git a/cas/cas-server/build.cmd b/cas/cas-server/build.cmd deleted file mode 100644 index 2cf9262afe..0000000000 --- a/cas/cas-server/build.cmd +++ /dev/null @@ -1,102 +0,0 @@ -@echo off - -@set JAVA_ARGS=-Xms500m -Xmx1g -@set CAS_DIR=\etc\cas -@set CONFIG_DIR=\etc\cas\config - -@rem Call this script with DNAME and CERT_SUBJ_ALT_NAMES already set to override -@if "%DNAME%" == "" set DNAME=CN=cas.example.org,OU=Example,OU=Org,C=US -@rem List other host names or ip addresses you want in your certificate, may help with host name verification, -@rem if client apps make https connection for ticket validation and compare name in cert (include sub. alt. names) -@rem to name used to access CAS -@if "%CERT_SUBJ_ALT_NAMES%" == "" set CERT_SUBJ_ALT_NAMES=dns:example.org,dns:localhost,dns:%COMPUTERNAME%,ip:127.0.0.1 - -@rem Check for mvn in path, use it if found, otherwise use maven wrapper -@set MAVEN_CMD=mvn -@where /q mvn -@if %ERRORLEVEL% neq 0 set MAVEN_CMD=.\mvnw.bat - -@if "%1" == "" call:help -@if "%1" == "copy" call:copy -@if "%1" == "clean" call:clean %2 %3 %4 -@if "%1" == "package" call:package %2 %3 %4 -@if "%1" == "bootrun" call:bootrun %2 %3 %4 -@if "%1" == "debug" call:debug %2 %3 %4 -@if "%1" == "run" call:run %2 %3 %4 -@if "%1" == "runalone" call:runalone %2 %3 %4 -@if "%1" == "help" call:help -@if "%1" == "gencert" call:gencert -@if "%1" == "cli" call:runcli %2 %3 %4 - -@rem function section starts here -@goto:eof - -:copy - @echo "Creating configuration directory under %CONFIG_DIR%" - if not exist %CONFIG_DIR% mkdir %CONFIG_DIR% - - @echo "Copying configuration files from etc/cas to /etc/cas" - xcopy /S /Y etc\cas\* \etc\cas -@goto:eof - -:help - @echo "Usage: build.bat [copy|clean|package|run|debug|bootrun|gencert|cli] [optional extra args for maven or cli]" - @echo "To get started on a clean system, run "build.bat copy" and "build.bat gencert", then "build.bat run" - @echo "Note that using the copy or gencert arguments will create and/or overwrite the %CAS_DIR% which is outside this project" -@goto:eof - -:clean - call %MAVEN_CMD% clean %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:package - call %MAVEN_CMD% clean package -T 5 %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:bootrun - call %MAVEN_CMD% clean package spring-boot:run -T 5 %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:debug - call:package %1 %2 %3 & java %JAVA_ARGS% -Xdebug -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=n -jar target/cas.war -@goto:eof - -:run - call:package %1 %2 %3 & java %JAVA_ARGS% -jar target/cas.war -@goto:eof - -:runalone - call:package %1 %2 %3 & target/cas.war -@goto:eof - -:gencert - where /q keytool - if ERRORLEVEL 1 ( - @echo Java keytool.exe not found in path. - exit /b 1 - ) else ( - if not exist %CAS_DIR% mkdir %CAS_DIR% - @echo on - @echo Generating self-signed SSL cert for %DNAME% in %CAS_DIR%\thekeystore - keytool -genkeypair -alias cas -keyalg RSA -keypass changeit -storepass changeit -keystore %CAS_DIR%\thekeystore -dname %DNAME% -ext SAN=%CERT_SUBJ_ALT_NAMES% - @echo Exporting cert for use in trust store (used by cas clients) - keytool -exportcert -alias cas -storepass changeit -keystore %CAS_DIR%\thekeystore -file %CAS_DIR%\cas.cer - ) -@goto:eof - -:runcli - for /f %%i in ('call %MAVEN_CMD% -q --non-recursive "-Dexec.executable=cmd" "-Dexec.args=/C echo ${cas.version}" "org.codehaus.mojo:exec-maven-plugin:1.3.1:exec"') do set CAS_VERSION=%%i - @set CAS_VERSION=%CAS_VERSION: =% - @set DOWNLOAD_DIR=target - @set COMMAND_FILE=cas-server-support-shell-%CAS_VERSION%.jar - @if not exist %DOWNLOAD_DIR% mkdir %DOWNLOAD_DIR% - @if not exist %DOWNLOAD_DIR%\%COMMAND_FILE% ( - @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=%CAS_VERSION% -Dpackaging=jar -DartifactItem.outputDirectory=%DOWNLOAD_DIR% -DartifactItem.destFileName=%COMMAND_FILE% -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false - @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:%CAS_VERSION%:jar -DoutputDirectory=%DOWNLOAD_DIR% - ) - @call java %JAVA_ARGS% -jar %DOWNLOAD_DIR%\%COMMAND_FILE% %1 %2 %3 - -@goto:eof \ No newline at end of file diff --git a/cas/cas-server/build.gradle b/cas/cas-server/build.gradle new file mode 100644 index 0000000000..41381e2d8f --- /dev/null +++ b/cas/cas-server/build.gradle @@ -0,0 +1,106 @@ +buildscript { + repositories { + mavenLocal() + mavenCentral() + jcenter() + maven { url "https://repo.spring.io/libs-milestone" } + maven { url "https://repo.spring.io/libs-snapshot" } + maven { url "https://plugins.gradle.org/m2/" } + } + dependencies { + classpath "de.undercouch:gradle-download-task:${project.gradleDownloadTaskVersion}" + classpath "org.springframework.boot:spring-boot-gradle-plugin:${project.springBootVersion}" + classpath "gradle.plugin.com.google.cloud.tools:jib-gradle-plugin:${project.jibVersion}" + classpath "io.freefair.gradle:maven-plugin:${project.gradleMavenPluginVersion}" + } +} + +repositories { + mavenLocal() + mavenCentral() + jcenter() + maven { url "https://oss.sonatype.org/content/repositories/snapshots" } + maven { url "https://build.shibboleth.net/nexus/content/repositories/releases/" } + maven { url "https://repo.spring.io/milestone/" } + maven { url "https://repo.spring.io/snapshot/" } + maven { url "https://oss.jfrog.org/artifactory/oss-snapshot-local" } +} + +def casServerVersion = project.'cas.version' +def casWebApplicationBinaryName = "cas.war" + +project.ext."casServerVersion" = casServerVersion +project.ext."casWebApplicationBinaryName" = casWebApplicationBinaryName + +apply plugin: "io.freefair.war-overlay" +apply from: rootProject.file("gradle/tasks.gradle") + +apply plugin: "war" +apply plugin: "eclipse" +apply plugin: "idea" + +apply from: rootProject.file("gradle/springboot.gradle") +apply from: rootProject.file("gradle/dockerjib.gradle") + +dependencies { + // Other CAS dependencies/modules may be listed here... + compile "org.apereo.cas:cas-server-support-json-service-registry:${casServerVersion}" + compile "org.apereo.cas:cas-server-support-jdbc:${casServerVersion}" +} + +tasks.findByName("jibDockerBuild") + .dependsOn(copyWebAppIntoJib, copyConfigIntoJib) + .finalizedBy(deleteWebAppFromJib) + +tasks.findByName("jib") + .dependsOn(copyWebAppIntoJib, copyConfigIntoJib) + .finalizedBy(deleteWebAppFromJib) + +configurations.all { + resolutionStrategy { + cacheChangingModulesFor 0, "seconds" + cacheDynamicVersionsFor 0, "seconds" + + preferProjectModules() + + def failIfConflict = project.hasProperty("failOnVersionConflict") && Boolean.valueOf(project.getProperty("failOnVersionConflict")) + if (failIfConflict) { + failOnVersionConflict() + } + } +} + +eclipse { + classpath { + downloadSources = true + downloadJavadoc = true + } +} + +idea { + module { + downloadJavadoc = true + downloadSources = true + } +} + +bootWar { + entryCompression = ZipEntryCompression.STORED + overlays { + // https://docs.freefair.io/gradle-plugins/current/reference/#_io_freefair_war_overlay + // Note: The "excludes" property is only for files in the war dependency. + // If a jar is excluded from the war, it could be brought back into the final war as a dependency + // of non-war dependencies. Those should be excluded via normal gradle dependency exclusions. + cas { + from "org.apereo.cas:cas-server-webapp${project.appServer}:${casServerVersion}@war" + provided = false + //excludes = ["WEB-INF/lib/somejar-1.0*"] + } + } +} + + +wrapper { + distributionType = Wrapper.DistributionType.BIN + gradleVersion = "${project.gradleVersion}" +} diff --git a/cas/cas-server/build.sh b/cas/cas-server/build.sh deleted file mode 100644 index 4d80aa2593..0000000000 --- a/cas/cas-server/build.sh +++ /dev/null @@ -1,189 +0,0 @@ -#!/bin/bash - - -function copy() { - echo -e "Creating configuration directory under /etc/cas" - mkdir -p /etc/cas/config - - echo -e "Copying configuration files from etc/cas to /etc/cas" - cp -rfv etc/cas/* /etc/cas -} - -function help() { - echo "Usage: build.sh [copy|clean|package|run|debug|bootrun|gencert]" - echo " copy: Copy config from ./etc/cas/config to /etc/cas/config" - echo " clean: Clean Maven build directory" - echo " package: Clean and build CAS war" - echo " run: Build and run cas.war via Java (i.e. java -jar target/cas.war)" - echo " runalone: Build and run cas.war on its own as a standalone executable (target/cas.war)" - echo " debug: Run CAS.war and listen for Java debugger on port 5000" - echo " bootrun: Run with maven spring boot plugin" - echo " listviews: List all CAS views that ship with the web application and can be customized in the overlay" - echo " getview: Ask for a view name to be included in the overlay for customizations" - echo " gencert: Create keystore with SSL certificate in location where CAS looks by default" - echo " cli: Run the CAS command line shell and pass commands" -} - -function clean() { - shift - ./mvnw clean "$@" -} - -function package() { - shift - ./mvnw clean package -T 5 "$@" - # copy -} - -function bootrun() { - shift - ./mvnw clean package spring-boot:run -P bootiful -T 5 "$@" -} - -function debug() { - package && java -Xdebug -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=n -jar target/cas.war -} - -function run() { - package && java -jar target/cas.war -} - -function runalone() { - shift - ./mvnw clean package -P default,exec "$@" - chmod +x target/cas.war - target/cas.war -} - -function listviews() { - shift - explodeapp - find $PWD/target/cas -type f -name "*.html" | xargs -n 1 basename | sort | more -} - -function explodeapp() { - if [ ! -d $PWD/target/cas ];then - echo "Building the CAS web application and exploding the final war file..." - ./mvnw clean package war:exploded "$@" - fi - echo "Exploded the CAS web application file." -} - -function getview() { - shift - explodeapp - echo "Searching for view name $@..." - results=`find $PWD/target/cas -type f -name "*.html" | grep -i "$@"` - echo -e "Found view(s): \n$results" - count=`wc -w <<< "$results"` - if [ "$count" -eq 1 ];then - # echo "Found view $results to include in the overlay" - firststring="target/cas/WEB-INF/classes" - secondstring="src/main/resources" - overlayfile=`echo "${results/$firststring/$secondstring}"` - overlaypath=`dirname "${overlayfile}"` - # echo "Overlay file is $overlayfile to be created at $overlaypath" - mkdir -p $overlaypath - cp $results $overlaypath - echo "Created view at $overlayfile" - ls $overlayfile - else - echo "More than one view file is found. Narrow down the search query..." - fi -} - - -function gencert() { - if [[ ! -d /etc/cas ]] ; then - copy - fi - which keytool - if [[ $? -ne 0 ]] ; then - echo Error: Java JDK \'keytool\' is not installed or is not in the path - exit 1 - fi - # override DNAME and CERT_SUBJ_ALT_NAMES before calling or use dummy values - DNAME="${DNAME:-CN=cas.example.org,OU=Example,OU=Org,C=US}" - CERT_SUBJ_ALT_NAMES="${CERT_SUBJ_ALT_NAMES:-dns:example.org,dns:localhost,ip:127.0.0.1}" - echo "Generating keystore for CAS with DN ${DNAME}" - keytool -genkeypair -alias cas -keyalg RSA -keypass changeit -storepass changeit -keystore /etc/cas/thekeystore -dname ${DNAME} -ext SAN=${CERT_SUBJ_ALT_NAMES} - keytool -exportcert -alias cas -storepass changeit -keystore /etc/cas/thekeystore -file /etc/cas/cas.cer -} - -function cli() { - - CAS_VERSION=$(./mvnw -q -Dexec.executable="echo" -Dexec.args='${cas.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec 2>/dev/null) - # echo "CAS version: $CAS_VERSION" - JAR_FILE_NAME="cas-server-support-shell-${CAS_VERSION}.jar" - # echo "JAR name: $JAR_FILE_NAME" - JAR_PATH="org/apereo/cas/cas-server-support-shell/${CAS_VERSION}/${JAR_FILE_NAME}" - # echo "JAR path: $JAR_PATH" - - JAR_FILE_LOCAL="$HOME/.m2/repository/$JAR_PATH"; - # echo "Local JAR file path: $JAR_FILE_LOCAL"; - if [ -f "$JAR_FILE_LOCAL" ]; then - # echo "Using JAR file locally at $JAR_FILE_LOCAL" - java -jar $JAR_FILE_LOCAL "$@" - exit 0; - fi - - DOWNLOAD_DIR=./target - COMMAND_FILE="${DOWNLOAD_DIR}/${JAR_FILE_NAME}" - if [ ! -f "$COMMAND_FILE" ]; then - mkdir -p $DOWNLOAD_DIR - ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=$CAS_VERSION -Dpackaging=jar -DartifactItem.outputDirectory=$DOWNLOAD_DIR -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false - ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:$CAS_VERSION:jar -DoutputDirectory=$DOWNLOAD_DIR - fi - java -jar $COMMAND_FILE "$@" - exit 0; - -} - -if [ $# -eq 0 ]; then - echo -e "No commands provided. Defaulting to [run]\n" - run - exit 0 -fi - -case "$1" in -"copy") - copy - ;; -"clean") - shift - clean "$@" - ;; -"package") - shift - package "$@" - ;; -"bootrun") - shift - bootrun "$@" - ;; -"debug") - debug "$@" - ;; -"run") - run "$@" - ;; -"runalone") - runalone "$@" - ;; -"listviews") - listviews "$@" - ;; -"gencert") - gencert "$@" - ;; -"getview") - getview "$@" - ;; -"cli") - shift - cli "$@" - ;; -*) - help - ;; -esac diff --git a/cas/cas-server/docker-build.sh b/cas/cas-server/docker-build.sh new file mode 100755 index 0000000000..8f2c2776bf --- /dev/null +++ b/cas/cas-server/docker-build.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) + +echo "Building CAS docker image tagged as [$image_tag]" +# read -p "Press [Enter] to continue..." any_key; + +docker build --tag="org.apereo.cas/cas:$image_tag" . \ + && echo "Built CAS image successfully tagged as org.apereo.cas/cas:$image_tag" \ + && docker images "org.apereo.cas/cas:$image_tag" \ No newline at end of file diff --git a/cas/cas-server/docker-compose.yml b/cas/cas-server/docker-compose.yml new file mode 100644 index 0000000000..8f2e6ca7c9 --- /dev/null +++ b/cas/cas-server/docker-compose.yml @@ -0,0 +1,7 @@ +version: '3' +services: + cas: + build: . + ports: + - "8443:8443" + - "8080:8080" \ No newline at end of file diff --git a/cas/cas-server/docker-push.sh b/cas/cas-server/docker-push.sh new file mode 100755 index 0000000000..e04b107212 --- /dev/null +++ b/cas/cas-server/docker-push.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +read -p "Docker username: " docker_user +read -s -p "Docker password: " docker_psw + +echo "$docker_psw" | docker login --username "$docker_user" --password-stdin + +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) + +echo "Pushing CAS docker image tagged as $image_tag to org.apereo.cas/cas..." +docker push org.apereo.cas/cas:"$image_tag" \ + && echo "Pushed org.apereo.cas/cas:$image_tag successfully."; \ No newline at end of file diff --git a/cas/cas-server/docker-run.sh b/cas/cas-server/docker-run.sh new file mode 100755 index 0000000000..f8627859f2 --- /dev/null +++ b/cas/cas-server/docker-run.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +docker stop cas > /dev/null 2>&1 +docker rm cas > /dev/null 2>&1 +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) +docker run -d -p 8080:8080 -p 8443:8443 --name="cas" org.apereo.cas/cas:"${image_tag}" +docker logs -f cas \ No newline at end of file diff --git a/cas/cas-server/etc/cas/config/application.yml b/cas/cas-server/etc/cas/config/application.yml deleted file mode 100644 index be1f7c3edd..0000000000 --- a/cas/cas-server/etc/cas/config/application.yml +++ /dev/null @@ -1,2 +0,0 @@ -info: - description: CAS Configuration \ No newline at end of file diff --git a/cas/cas-server/etc/cas/config/cas.properties b/cas/cas-server/etc/cas/config/cas.properties index 47a1477308..a3be0e1388 100644 --- a/cas/cas-server/etc/cas/config/cas.properties +++ b/cas/cas-server/etc/cas/config/cas.properties @@ -1,7 +1,6 @@ -cas.server.name: https://cas.example.org:8443 -cas.server.prefix: https://cas.example.org:8443/cas - -cas.adminPagesSecurity.ip=127\.0\.0\.1 +cas.server.name=https://cas.example.org:8443 +cas.server.prefix=${cas.server.name}/cas logging.config: file:/etc/cas/config/log4j2.xml -# cas.serviceRegistry.config.location: classpath:/services + +# cas.authn.accept.users= diff --git a/cas/cas-server/etc/cas/config/log4j2.xml b/cas/cas-server/etc/cas/config/log4j2.xml index e688cc0350..685dfab245 100644 --- a/cas/cas-server/etc/cas/config/log4j2.xml +++ b/cas/cas-server/etc/cas/config/log4j2.xml @@ -2,20 +2,26 @@ - - . - - warn + /var/log + + info + warn + info + warn + debug + warn + warn + warn + warn + warn + warn - + - + @@ -23,8 +29,8 @@ - + @@ -33,16 +39,6 @@ - - - - - - - - - @@ -52,52 +48,58 @@ - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/etc/cas/saml/.gitkeep b/cas/cas-server/etc/cas/saml/.gitkeep new file mode 100644 index 0000000000..882c99944d --- /dev/null +++ b/cas/cas-server/etc/cas/saml/.gitkeep @@ -0,0 +1 @@ +This directory is references in the Dockerfile so it needs to be here. \ No newline at end of file diff --git a/cas/cas-server/etc/cas/services/.donotdel b/cas/cas-server/etc/cas/services/.donotdel new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cas/cas-server/etc/cas/thekeystore b/cas/cas-server/etc/cas/thekeystore new file mode 100644 index 0000000000..78f49baf74 Binary files /dev/null and b/cas/cas-server/etc/cas/thekeystore differ diff --git a/cas/cas-server/gradle.properties b/cas/cas-server/gradle.properties new file mode 100644 index 0000000000..28daacc245 --- /dev/null +++ b/cas/cas-server/gradle.properties @@ -0,0 +1,28 @@ +# Versions +cas.version=6.1.5 +springBootVersion=2.2.0.RELEASE + +# Use -jetty, -undertow to other containers +# Or blank if you want to deploy to an external container +appServer=-tomcat +executable=false + +gradleVersion=5.6.3 +tomcatVersion=9.0.30 + +group=org.apereo.cas +sourceCompatibility=11 +targetCompatibility=11 + +jibVersion=1.7.0 + +# Location of the downloaded CAS shell JAR +shellDir=build/libs +ivyVersion=2.4.0 +gradleDownloadTaskVersion=3.4.3 +gradleMavenPluginVersion=3.8.4 + +# use without "-slim" in tag name if you want tools like jstack, adds about 100MB to image size +# (https://hub.docker.com/r/adoptopenjdk/openjdk11/tags/) +baseDockerImage=adoptopenjdk/openjdk11:alpine-jre +allowInsecureRegistries=false diff --git a/cas/cas-server/gradle/dockerjib.gradle b/cas/cas-server/gradle/dockerjib.gradle new file mode 100644 index 0000000000..dcd70e3875 --- /dev/null +++ b/cas/cas-server/gradle/dockerjib.gradle @@ -0,0 +1,52 @@ +apply plugin: "com.google.cloud.tools.jib" + +jib { + from { + image = project.baseDockerImage + } + to { + image = "${project.group}/${project.name}" + /** + ecr-login: Amazon Elastic Container Registry (ECR) + gcr: Google Container Registry (GCR) + osxkeychain: Docker Hub + */ + credHelper = "osxkeychain" + /** + auth { + username = "*******" + password = "*******" + } + tags = [casServerVersion] + */ + } + container { + useCurrentTimestamp = true + entrypoint = ['docker/entrypoint.sh'] + ports = ['80', '443', '8080', '8443'] + labels = [version:casServerVersion, name:project.name, group:project.group] + } + extraDirectories { + paths = 'src/main/jib' + permissions = [ + '/docker/entrypoint.sh': '755' + ] + } + allowInsecureRegistries = project.allowInsecureRegistries +} + +task copyWebAppIntoJib(type: Copy, group: "Docker", description: "Copy the web application into Docker image") { + dependsOn build + from "build/libs/${casWebApplicationBinaryName}" + into "src/main/jib/docker/cas/war" +} + +task copyConfigIntoJib(type: Copy, group: "Docker", description: "Copy the CAS configuration into Docker image") { + dependsOn build + from "etc/cas" + into "src/main/jib/docker/cas" +} + +task deleteWebAppFromJib(type: Delete, group: "Docker", description: "Explodes the CAS web application archive") { + delete "src/main/jib/docker/cas" +} \ No newline at end of file diff --git a/cas/cas-server/gradle/springboot.gradle b/cas/cas-server/gradle/springboot.gradle new file mode 100644 index 0000000000..b6a46b8940 --- /dev/null +++ b/cas/cas-server/gradle/springboot.gradle @@ -0,0 +1,24 @@ +apply plugin: "org.springframework.boot" + +bootRun.enabled = false +bootRun.onlyIf { return false } +tasks.remove(tasks['bootRun']) + +springBoot { + mainClassName = "org.apereo.cas.web.CasWebApplication" +} + +bootWar { + doFirst { + def executable = project.hasProperty("executable") && Boolean.valueOf(project.getProperty("executable")) + if (executable) { + logger.info "Including launch script for executable WAR artifact" + launchScript() + } else { + logger.info "WAR artifact is not marked as an executable" + } + archiveName "${casWebApplicationBinaryName}" + baseName "cas" + excludeDevtools = true + } +} \ No newline at end of file diff --git a/cas/cas-server/gradle/tasks.gradle b/cas/cas-server/gradle/tasks.gradle new file mode 100644 index 0000000000..2babeb2d1f --- /dev/null +++ b/cas/cas-server/gradle/tasks.gradle @@ -0,0 +1,258 @@ +import org.apache.ivy.util.url.* +import org.apache.tools.ant.taskdefs.condition.Os +import org.gradle.api.tasks.Copy + +import java.nio.file.* +import org.gradle.internal.logging.text.StyledTextOutputFactory; +import static org.gradle.internal.logging.text.StyledTextOutput.Style; + +buildscript { + repositories { + mavenLocal() + mavenCentral() + jcenter() + } + dependencies { + classpath "org.apache.ivy:ivy:${project.ivyVersion}" + } +} + +apply plugin: "de.undercouch.download" + +def tomcatDirectory = "${buildDir}/apache-tomcat-${tomcatVersion}" +project.ext."tomcatDirectory" = tomcatDirectory + +def explodedDir="${buildDir}/cas" +def explodedResourcesDir="${buildDir}/cas-resources" +def resourceJarName = "cas-server-webapp-resources" + +task copyCasConfiguration(type: Copy, group: "build", description: "Copy the CAS configuration from this project to /etc/cas/config") { + from "etc/cas/config" + into new File('/etc/cas/config').absolutePath + doFirst { + new File('/etc/cas/config').mkdirs() + } +} + +task explodeWarOnly(type: Copy, group: "build", description: "Explodes the CAS web application archive") { + dependsOn 'build' + from zipTree("build/libs/${casWebApplicationBinaryName}") + into explodedDir +} + +task explodeWar(type: Copy, group: "build", description: "Explodes the CAS archive and resources jar from the CAS web application archive") { + dependsOn explodeWarOnly + from zipTree("${explodedDir}/WEB-INF/lib/${resourceJarName}-${casServerVersion}.jar") + into explodedResourcesDir +} + +task run(group: "build", description: "Run the CAS web application in embedded container mode") { + dependsOn 'build' + doLast { + def casRunArgs = new ArrayList<>(Arrays.asList("-server -noverify -Xmx2048M -XX:+TieredCompilation -XX:TieredStopAtLevel=1".split(" "))) + if (project.hasProperty('args')) { + casRunArgs.addAll(project.args.split('\\s+')) + } + javaexec { + main = "-jar" + jvmArgs = casRunArgs + args = ["build/libs/${casWebApplicationBinaryName}"] + logger.info "Started ${commandLine}" + } + } +} + +task setExecutable(group: "build", description: "Configure the project to run in executable mode") { + doFirst { + project.setProperty("executable", "true") + logger.info "Configuring the project as executable" + } +} + +task executable(type:Exec, group: "build", description: "Run the CAS web application in standalone executable mode") { + dependsOn setExecutable, 'build' + doFirst { + workingDir "." + if (!Os.isFamily(Os.FAMILY_WINDOWS)) { + commandLine "chmod", "+x", bootWar.archivePath + } + logger.info "Running ${bootWar.archivePath}" + commandLine bootWar.archivePath + } +} + +task debug(group: "build", description: "Debug the CAS web application in embedded mode on port 5005") { + dependsOn 'build' + doLast { + logger.info "Debugging process is started in a suspended state, listening on port 5005." + def casArgs = Arrays.asList("-Xmx2048M".split(" ")) + javaexec { + main = "-jar" + jvmArgs = casArgs + debug = true + args = ["build/libs/${casWebApplicationBinaryName}"] + logger.info "Started ${commandLine}" + } + } +} + +task downloadShell(group: "shell", description: "Download CAS shell jar from snapshot or release maven repo") { + doFirst { + mkdir "${project.shellDir}" + } + doLast { + def downloadFile + if (isRunningCasServerSnapshot(casServerVersion)) { + def snapshotDir = "https://oss.sonatype.org/content/repositories/snapshots/org/apereo/cas/cas-server-support-shell/${casServerVersion}/" + def files = new ApacheURLLister().listFiles(new URL(snapshotDir)) + files = files.sort{it.path} + files.each { + if (it.path.endsWith(".jar")) { + downloadFile = it + } + } + } else { + downloadFile = "https://repo1.maven.org/maven2/org/apereo/cas/cas-server-support-shell/${casServerVersion}/cas-server-support-shell-${casServerVersion}.jar" + } + logger.info "Downloading file: ${downloadFile}" + download { + src downloadFile + dest new File("${project.shellDir}", "cas-server-support-shell-${casServerVersion}.jar") + overwrite false + } + } +} + +task runShell(group: "shell", description: "Run the CAS shell") { + dependsOn downloadShell + doLast { + println "Run the following command to launch the shell:\n\tjava -jar ${project.shellDir}/cas-server-support-shell-${casServerVersion}.jar" + } +} + +task debugShell(group: "shell", description: "Run the CAS shell with debug options, wait for debugger on port 5005") { + dependsOn downloadShell + doLast { + println """ + Run the following command to launch the shell:\n\t + java -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=y -jar ${project.shellDir}/cas-server-support-shell-${casServerVersion}.jar + """ + } +} + +task showConfiguration(group: "build", description: "Show configurations for each dependency, etc") { + doLast() { + def cfg = project.hasProperty("configuration") ? project.property("configuration") : "compile" + configurations.getByName(cfg).each { println it } + } +} + +task allDependenciesInsight(group: "build", type: DependencyInsightReportTask, description: "Produce insight information for all dependencies") {} + +task allDependencies(group: "build", type: DependencyReportTask, description: "Display a graph of all project dependencies") {} + +task casVersion (group: "build", description: "Display the current CAS version") { + doFirst { + def verbose = project.hasProperty("verbose") && Boolean.valueOf(project.getProperty("verbose")) + if (verbose) { + def out = services.get(StyledTextOutputFactory).create("CAS") + println "******************************************************************" + out.withStyle(Style.Info).println "Apereo CAS $casServerVersion" + out.withStyle(Style.Description).println "Enterprise Single SignOn for all earthlings and beyond" + out.withStyle(Style.SuccessHeader).println "- GitHub: " + out.withStyle(Style.Success).println "https://github.com/apereo/cas" + out.withStyle(Style.SuccessHeader).println "- Docs: " + out.withStyle(Style.Success).println "https://apereo.github.io/cas" + out.withStyle(Style.SuccessHeader).println "- Blog: " + out.withStyle(Style.Success).println "https://apereo.github.io" + println "******************************************************************" + } else { + println casServerVersion + } + } +} + +task createKeystore(group: "build", description: "Create CAS keystore") { + doFirst { + mkdir "/etc/cas" + + def keystorePath = "/etc/cas/thekeystore" + + def dn = "CN=cas.example.org,OU=Example,OU=Org,C=US" + if (project.hasProperty("certificateDn")) { + dn = project.getProperty("certificateDn") + } + def subjectAltName = "dns:example.org,dns:localhost,ip:127.0.0.1" + if (project.hasProperty("certificateSubAltName")) { + subjectAltName = project.getProperty("certificateSubAltName") + } + // this will fail if thekeystore exists and has cert with cas alias already (so delete if you want to recreate) + logger.info "Generating keystore for CAS with DN ${dn}" + exec { + workingDir "." + commandLine "keytool", "-genkeypair", "-alias", "cas", + "-keyalg", "RSA", + "-keypass", "changeit", "-storepass", "changeit", + "-keystore", keystorePath, + "-dname", dn, "-ext", "SAN=${subjectAltName}" + } + logger.info "Exporting cert from keystore..." + exec { + workingDir "." + commandLine "keytool", "-exportcert", "-alias", "cas", + "-storepass", "changeit", "-keystore", keystorePath, + "-file", "/etc/cas/cas.cer" + } + logger.info "Import /etc/cas/cas.cer into your Java truststore (JAVA_HOME/lib/security/cacerts)" + } +} + +task listTemplateViews (group: "build", description: "List all CAS views") { + dependsOn explodeWar + + doFirst { + fileTree(explodedResourcesDir).matching { + include "**/*.html" + } + .collect { it.name } + .toSorted() + .each { println it } + } +} + +task getResource(group: "build", description: "Fetch a CAS resource and move it into the overlay") { + dependsOn explodeWar + + doFirst { + def resourceName = project.getProperty("resourceName") + + def results = fileTree(explodedResourcesDir).matching { + include "**/${resourceName}.*" + } + if (results.isEmpty()) { + println "No resources could be found matching ${resourceName}" + return + } + if (results.size() > 1) { + println "Multiple resources found matching ${resourceName}: ${results}" + return + } + + def fromFile = explodedResourcesDir + def resourcesDir = "src/main/resources" + mkdir resourcesDir + + def resourceFile = results[0].canonicalPath + def toResourceFile = resourceFile.replace(fromFile, resourcesDir) + + def parent = file(toResourceFile).getParent() + mkdir parent + + Files.copy(Paths.get(resourceFile), Paths.get(toResourceFile), StandardCopyOption.REPLACE_EXISTING) + println "Copied file ${resourceFile} to ${toResourceFile}" + } +} + +def isRunningCasServerSnapshot(casServerVersion) { + return "${casServerVersion}".contains("-SNAPSHOT") +} \ No newline at end of file diff --git a/cas/cas-server/gradle/wrapper/gradle-wrapper.properties b/cas/cas-server/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..f04d6a20ae --- /dev/null +++ b/cas/cas-server/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/cas/cas-server/gradlew b/cas/cas-server/gradlew new file mode 100755 index 0000000000..83f2acfdc3 --- /dev/null +++ b/cas/cas-server/gradlew @@ -0,0 +1,188 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/cas/cas-server/gradlew.bat b/cas/cas-server/gradlew.bat new file mode 100644 index 0000000000..24467a141f --- /dev/null +++ b/cas/cas-server/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/cas/cas-server/maven/maven-wrapper.jar b/cas/cas-server/maven/maven-wrapper.jar deleted file mode 100644 index 18ba302c65..0000000000 Binary files a/cas/cas-server/maven/maven-wrapper.jar and /dev/null differ diff --git a/cas/cas-server/maven/maven-wrapper.properties b/cas/cas-server/maven/maven-wrapper.properties deleted file mode 100644 index 97a946225a..0000000000 --- a/cas/cas-server/maven/maven-wrapper.properties +++ /dev/null @@ -1,3 +0,0 @@ -#Maven download properties -#Fri Dec 01 21:35:11 MST 2017 -distributionUrl=https\://repository.apache.org/content/repositories/releases/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip diff --git a/cas/cas-server/mvnw b/cas/cas-server/mvnw deleted file mode 100644 index 2275ac7647..0000000000 --- a/cas/cas-server/mvnw +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - wdir=$(cd "$wdir/.."; pwd) - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER="org.apache.maven.wrapper.MavenWrapperMain" - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - -classpath \ -"$MAVEN_PROJECTBASEDIR/maven/maven-wrapper.jar" \ - ${WRAPPER_LAUNCHER} "$@" diff --git a/cas/cas-server/mvnw.bat b/cas/cas-server/mvnw.bat deleted file mode 100644 index d391151aa7..0000000000 --- a/cas/cas-server/mvnw.bat +++ /dev/null @@ -1,174 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto chkMHome - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:chkMHome -if not "%M2_HOME%"=="" goto valMHome - -SET "M2_HOME=%~dp0.." -if not "%M2_HOME%"=="" goto valMHome - -echo. -echo Error: M2_HOME not found in your environment. >&2 -echo Please set the M2_HOME variable in your environment to match the >&2 -echo location of the Maven installation. >&2 -echo. -goto error - -:valMHome - -:stripMHome -if not "_%M2_HOME:~-1%"=="_\" goto checkMCmd -set "M2_HOME=%M2_HOME:~0,-1%" -goto stripMHome - -:checkMCmd -if exist "%M2_HOME%\bin\mvn.cmd" goto init - -echo. -echo Error: M2_HOME is set to an invalid directory. >&2 -echo M2_HOME = "%M2_HOME%" >&2 -echo Please set the M2_HOME variable in your environment to match the >&2 -echo location of the Maven installation >&2 -echo. -goto error -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\maven\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% - -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml deleted file mode 100644 index abcf251667..0000000000 --- a/cas/cas-server/pom.xml +++ /dev/null @@ -1,208 +0,0 @@ - - - 4.0.0 - cas-server - 1.0 - cas-server - war - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.apereo.cas - cas-server-support-json-service-registry - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc-drivers - ${cas.version} - - - - - - - com.rimerosolutions.maven.plugins - wrapper-maven-plugin - ${wrapper-maven-plugin.version} - - true - MD5 - - - - org.springframework.boot - spring-boot-maven-plugin - - ${mainClassName} - true - ${isExecutable} - WAR - - - - - repackage - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - cas - false - false - - false - ${manifestFileToUse} - - - - org.apereo.cas - cas-server-webapp${app.server} - - - - - - cas - - - - - - true - - default - - - org.apereo.cas - cas-server-webapp${app.server} - ${cas.version} - war - runtime - - - - - - - - false - - exec - - org.apereo.cas.web.CasWebApplication - true - - - - - - com.soebes.maven.plugins - echo-maven-plugin - ${echo-maven-plugin.version} - - - prepare-package - - echo - - - - - - Executable profile to make the generated CAS web application executable. - - - - - - - - - - false - - bootiful - - -tomcat - false - - - - org.apereo.cas - cas-server-webapp${app.server} - ${cas.version} - war - runtime - - - - - - - false - - pgp - - - - com.github.s4u.plugins - pgpverify-maven-plugin - ${pgpverify-maven-plugin.version} - - - - check - - - - - hkp://pool.sks-keyservers.net - ${settings.localRepository}/pgpkeys-cache - test - true - false - - - - - - - - - 5.3.3 - - -tomcat - - org.springframework.boot.loader.WarLauncher - false - ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF - - 0.0.4 - 2.6 - - 0.3.0 - 1.1.0 - - - diff --git a/cas/cas-server/settings.gradle b/cas/cas-server/settings.gradle new file mode 100644 index 0000000000..3ad50900ea --- /dev/null +++ b/cas/cas-server/settings.gradle @@ -0,0 +1 @@ +rootProject.name='cas' \ No newline at end of file diff --git a/cas/cas-server/src/main/jib/docker/entrypoint.sh b/cas/cas-server/src/main/jib/docker/entrypoint.sh new file mode 100755 index 0000000000..a3a0895b04 --- /dev/null +++ b/cas/cas-server/src/main/jib/docker/entrypoint.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +#echo -e "\nChecking java..." +#java -version + +#echo -e "\nCreating CAS configuration directories..." +mkdir -p /etc/cas/config +mkdir -p /etc/cas/services + +#echo "Listing provided CAS docker artifacts..." +#ls -R docker/cas + +#echo -e "\nMoving CAS configuration artifacts..." +mv docker/cas/thekeystore /etc/cas 2>/dev/null +mv docker/cas/config/*.* /etc/cas/config 2>/dev/null +mv docker/cas/services/*.* /etc/cas/services 2>/dev/null + +#echo -e "\nListing CAS configuration under /etc/cas..." +#ls -R /etc/cas + +echo -e "\nRunning CAS..." +exec java -Xms512m -Xmx2048M -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -jar docker/cas/war/cas.war diff --git a/cas/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties index 7735fcabdc..185532f943 100644 --- a/cas/cas-server/src/main/resources/application.properties +++ b/cas/cas-server/src/main/resources/application.properties @@ -1,134 +1,4 @@ -## -# CAS Server Context Configuration -# -server.context-path=/cas -server.port=6443 - +server.port=8443 +spring.main.allow-bean-definition-overriding=true server.ssl.key-store=classpath:/etc/cas/thekeystore -server.ssl.key-store-password=changeit -server.ssl.key-password=changeit -# server.ssl.ciphers= -# server.ssl.client-auth= -# server.ssl.enabled= -# server.ssl.key-alias= -# server.ssl.key-store-provider= -# server.ssl.key-store-type= -# server.ssl.protocol= -# server.ssl.trust-store= -# server.ssl.trust-store-password= -# server.ssl.trust-store-provider= -# server.ssl.trust-store-type= - -server.max-http-header-size=2097152 -server.use-forward-headers=true -server.connection-timeout=20000 -server.error.include-stacktrace=NEVER - -server.tomcat.max-http-post-size=2097152 -server.tomcat.basedir=build/tomcat -server.tomcat.accesslog.enabled=true -server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms) -server.tomcat.accesslog.suffix=.log -server.tomcat.max-threads=10 -server.tomcat.port-header=X-Forwarded-Port -server.tomcat.protocol-header=X-Forwarded-Proto -server.tomcat.protocol-header-https-value=https -server.tomcat.remote-ip-header=X-FORWARDED-FOR -server.tomcat.uri-encoding=UTF-8 - -spring.http.encoding.charset=UTF-8 -spring.http.encoding.enabled=true -spring.http.encoding.force=true - -## -#CAS CONFIG LOCATION -# -standalone.config=classpath:/etc/cas/config - - -## -# CAS Cloud Bus Configuration -# -spring.cloud.bus.enabled=false -# spring.cloud.bus.refresh.enabled=true -# spring.cloud.bus.env.enabled=true -# spring.cloud.bus.destination=CasCloudBus -# spring.cloud.bus.ack.enabled=true - -endpoints.enabled=false -endpoints.sensitive=true - -endpoints.restart.enabled=false -endpoints.shutdown.enabled=false - -management.security.enabled=true -management.security.roles=ACTUATOR,ADMIN -management.security.sessions=if_required -management.context-path=/status -management.add-application-context-header=false - -security.basic.authorize-mode=role -security.basic.enabled=false -security.basic.path=/cas/status/** - -## -# CAS Web Application Session Configuration -# -server.session.timeout=300 -server.session.cookie.http-only=true -server.session.tracking-modes=COOKIE - -## -# CAS Thymeleaf View Configuration -# -spring.thymeleaf.encoding=UTF-8 -spring.thymeleaf.cache=true -spring.thymeleaf.mode=HTML -## -# CAS Log4j Configuration -# -# logging.config=file:/etc/cas/log4j2.xml - -server.context-parameters.isLog4jAutoInitializationDisabled=true - -## -# CAS AspectJ Configuration -# -spring.aop.auto=true -spring.aop.proxy-target-class=true - -## -# CAS Authentication Credentials -# -#cas.authn.accept.users=casuser::Mellon -cas.authn.accept.users= -cas.authn.accept.name= - -#CAS Database Authentication Property -cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? -cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC -cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect -cas.authn.jdbc.query[0].user=root -cas.authn.jdbc.query[0].password=1234 -cas.authn.jdbc.query[0].ddlAuto=none -#cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver -cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver -cas.authn.jdbc.query[0].fieldPassword=password -cas.authn.jdbc.query[0].passwordEncoder.type=NONE - - -## -# CAS Delegated Authentication -# -cas.authn.pac4j.bitbucket.clientName=Bitbucket -cas.authn.pac4j.dropbox.clientName=Dropbox -cas.authn.pac4j.facebook.clientName=Facebook -cas.authn.pac4j.foursquare.clientName=Foursquare -cas.authn.pac4j.github.clientName=Github -cas.authn.pac4j.google.clientName=Google -cas.authn.pac4j.linkedIn.clientName=LinkedIn -cas.authn.pac4j.paypal.clientName=PayPal -cas.authn.pac4j.twitter.clientName=Twitter -cas.authn.pac4j.yahoo.clientName=Yahoo -cas.authn.pac4j.windowsLive.clientName=Windows Live -cas.authn.pac4j.wordpress.clientName=WordPress +server.ssl.key-store-password=changeit \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/cas.properties b/cas/cas-server/src/main/resources/cas.properties deleted file mode 100644 index e39d68f312..0000000000 --- a/cas/cas-server/src/main/resources/cas.properties +++ /dev/null @@ -1,9 +0,0 @@ -cas.server.name: https://localhost:6443 -cas.server.prefix: https://localhost:643/cas - -cas.adminPagesSecurity.ip=127\.0\.0\.1 - -logging.config: file:/etc/cas/config/log4j2.xml - -cas.serviceRegistry.initFromJson=true -cas.serviceRegistry.config.location=classpath:/services \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql index 79a4a48a82..104b515813 100644 --- a/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql +++ b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql @@ -4,13 +4,13 @@ USE `test`; -- Dumping structure for table test.users CREATE TABLE IF NOT EXISTS `users` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `email` varchar(50) DEFAULT NULL, - `password` text DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; + `id` int(11) NOT NULL AUTO_INCREMENT, + `email` varchar(50) DEFAULT NULL, + `password` text DEFAULT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40000 ALTER TABLE `users` DISABLE KEYS */; INSERT INTO `users` (`id`, `email`, `password`) VALUES - (1, 'test@test.com', 'Mellon'); + (1, 'test@test.com', 'Mellon'); /*!40000 ALTER TABLE `users` ENABLE KEYS */; \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/application.yml b/cas/cas-server/src/main/resources/etc/cas/config/application.yml deleted file mode 100644 index be1f7c3edd..0000000000 --- a/cas/cas-server/src/main/resources/etc/cas/config/application.yml +++ /dev/null @@ -1,2 +0,0 @@ -info: - description: CAS Configuration \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/cas.properties b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties index 47a1477308..dda939bc1d 100644 --- a/cas/cas-server/src/main/resources/etc/cas/config/cas.properties +++ b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties @@ -1,7 +1,15 @@ -cas.server.name: https://cas.example.org:8443 -cas.server.prefix: https://cas.example.org:8443/cas +cas.serviceRegistry.initFromJson=true +cas.serviceRegistry.json.location=classpath:/etc/cas/services -cas.adminPagesSecurity.ip=127\.0\.0\.1 -logging.config: file:/etc/cas/config/log4j2.xml -# cas.serviceRegistry.config.location: classpath:/services +cas.authn.accept.users= + +cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? +cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC +cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect +cas.authn.jdbc.query[0].user=root +cas.authn.jdbc.query[0].password=smattroot +cas.authn.jdbc.query[0].ddlAuto=none +cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver +cas.authn.jdbc.query[0].fieldPassword=password +cas.authn.jdbc.query[0].passwordEncoder.type=NONE \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml deleted file mode 100644 index e688cc0350..0000000000 --- a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - . - - warn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json b/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json new file mode 100644 index 0000000000..5d468945ff --- /dev/null +++ b/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json @@ -0,0 +1,8 @@ +{ + "@class" : "org.apereo.cas.services.RegexRegisteredService", + "serviceId" : "http://cas-client:8900/login/cas", + "name" : "casSecuredApp", + "id" : 8900, + "logoutType" : "BACK_CHANNEL", + "logoutUrl" : "http://cas-client:8900/exit/cas" +} \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore b/cas/cas-server/src/main/resources/etc/cas/thekeystore index 77bf895249..a361bf03f9 100644 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore and b/cas/cas-server/src/main/resources/etc/cas/thekeystore differ diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt deleted file mode 100644 index 12ef688a08..0000000000 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt and /dev/null differ diff --git a/cas/cas-server/src/main/resources/log4j2.xml b/cas/cas-server/src/main/resources/log4j2.xml deleted file mode 100644 index e688cc0350..0000000000 --- a/cas/cas-server/src/main/resources/log4j2.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - . - - warn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json b/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json deleted file mode 100644 index 336007e484..0000000000 --- a/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "@class" : "org.apereo.cas.services.RegexRegisteredService", - "serviceId" : "^http://localhost:9000/login/cas", - "name" : "CAS Spring Secured App", - "description": "This is a Spring App that usses the CAS Server for it's authentication", - "id" : 19991, - "evaluationOrder" : 1 -} \ No newline at end of file diff --git a/cas/pom.xml b/cas/pom.xml deleted file mode 100644 index 77fae3b50a..0000000000 --- a/cas/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - 4.0.0 - cas - cas - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - - - - cas-secured-app - cas-server - - - diff --git a/core-groovy-2/determine-datatype/pom.xml b/core-groovy-2/determine-datatype/pom.xml new file mode 100644 index 0000000000..0bcef4e5d8 --- /dev/null +++ b/core-groovy-2/determine-datatype/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + com.baeldung.groovy + determine-datatype + 0.0.1-SNAPSHOT + + src + + + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + org.codehaus.gmaven + groovy-maven-plugin + + + org.codehaus.groovy + groovy-all + 2.0.6 + + + + + + + + + org.junit + junit5-engine + 5.0.0-ALPHA + + + \ No newline at end of file diff --git a/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/Person.groovy b/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/Person.groovy new file mode 100644 index 0000000000..1a89dce435 --- /dev/null +++ b/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/Person.groovy @@ -0,0 +1,14 @@ +package com.baeldung.groovy.determine.datatype + +class Person { + + private int ageAsInt + private Double ageAsDouble + private String ageAsString + + Person() {} + Person(int ageAsInt) { this.ageAsInt = ageAsInt} + Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble} + Person(String ageAsString) { this.ageAsString = ageAsString} +} +class Student extends Person {} diff --git a/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/PersonTest.groovy b/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/PersonTest.groovy new file mode 100644 index 0000000000..56095a3f1b --- /dev/null +++ b/core-groovy-2/determine-datatype/src/com/baeldung/groovy/determine/datatype/PersonTest.groovy @@ -0,0 +1,55 @@ +package com.baeldung.groovy.determine.datatype; + +import org.junit.Assert +import org.junit.Test; + +public class PersonTest { + + @Test + public void givenWhenParameterTypeIsInteger_thenReturnTrue() { + Person personObj = new Person(10) + Assert.assertTrue(personObj.ageAsInt instanceof Integer); + } + + @Test + public void givenWhenParameterTypeIsDouble_thenReturnTrue() { + Person personObj = new Person(10.0) + Assert.assertTrue((personObj.ageAsDouble).getClass() == Double) + } + + @Test + public void givenWhenParameterTypeIsString_thenReturnTrue() { + Person personObj = new Person("10 years") + Assert.assertTrue(personObj.ageAsString.class == String) + } + + @Test + public void givenClassName_WhenParameterIsInteger_thenReturnTrue() { + Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class) + } + + @Test + public void givenWhenObjectIsInstanceOfType_thenReturnTrue() { + Person personObj = new Person() + Assert.assertTrue(personObj instanceof Person) + } + + @Test + public void givenWhenInstanceIsOfSubtype_thenReturnTrue() { + Student studentObj = new Student() + Assert.assertTrue(studentObj in Person) + } + + @Test + public void givenGroovyList_WhenFindClassName_thenReturnTrue() { + def ageList = ['ageAsString','ageAsDouble', 10] + Assert.assertTrue(ageList.class == ArrayList) + Assert.assertTrue(ageList.getClass() == ArrayList) + } + + @Test + public void givenGrooyMap_WhenFindClassName_thenReturnTrue() { + def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0] + Assert.assertFalse(ageMap.class == LinkedHashMap) + } +} \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy new file mode 100644 index 0000000000..48cf48fa8a --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy @@ -0,0 +1,110 @@ +package com.baeldung.stringtoint + +import org.junit.Test + +import java.text.DecimalFormat + +import static org.junit.Assert.assertEquals +import static org.junit.Assert.assertNull + +class ConvertStringToInt { + + @Test + void givenString_whenUsingAsInteger_thenConvertToInteger() { + def stringNum = "123" + def invalidString = "123a" + Integer expectedInteger = 123 + Integer integerNum = stringNum as Integer + def intNum = invalidString?.isInteger() ? invalidString as Integer : null + + assertNull(null, intNum) + assertEquals(integerNum, expectedInteger) + } + + @Test + void givenString_whenUsingAsInt_thenConvertToInt() { + def stringNum = "123" + int expectedInt = 123 + int intNum = stringNum as int + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingToInteger_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = stringNum.toInteger() + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingParseInt_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = Integer.parseInt(stringNum) + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingValueOf_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = Integer.valueOf(stringNum) + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingIntValue_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = new Integer(stringNum).intValue() + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingNewInteger_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = new Integer(stringNum) + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_whenUsingDecimalFormat_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + DecimalFormat decimalFormat = new DecimalFormat("#") + int intNum = decimalFormat.parse(stringNum).intValue() + + assertEquals(intNum, expectedInt) + } + + @Test(expected = NumberFormatException.class) + void givenInvalidString_whenUsingAs_thenThrowNumberFormatException() { + def invalidString = "123a" + invalidString as Integer + } + + @Test(expected = NullPointerException.class) + void givenNullString_whenUsingToInteger_thenThrowNullPointerException() { + def invalidString = null + invalidString.toInteger() + } + + @Test + void givenString_whenUsingIsInteger_thenCheckIfCorrectValue() { + def invalidString = "123a" + def validString = "123" + def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false + def correctNum = validString?.isInteger() ? validString as Integer : false + + assertEquals(false, invalidNum) + assertEquals(123, correctNum) + } +} diff --git a/core-java-modules/core-java-14/README.md b/core-java-modules/core-java-14/README.md index 0e8278c4f6..13bb468b30 100644 --- a/core-java-modules/core-java-14/README.md +++ b/core-java-modules/core-java-14/README.md @@ -7,3 +7,4 @@ This module contains articles about Java 14. - [Guide to the @Serial Annotation in Java 14](https://www.baeldung.com/java-14-serial-annotation) - [Java Text Blocks](https://www.baeldung.com/java-text-blocks) - [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof) +- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception) diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/npe/HelpfulNullPointerException.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/npe/HelpfulNullPointerException.java new file mode 100644 index 0000000000..913f796cd4 --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/npe/HelpfulNullPointerException.java @@ -0,0 +1,56 @@ +package com.baeldung.java14.npe; + +public class HelpfulNullPointerException { + + public static void main(String[] args) { + Employee employee = null; + employee.getName(); + } + + public String getEmployeeEmailAddress(Employee employee) { + String emailAddress = employee.getPersonalDetails().getEmailAddress().toLowerCase(); + return emailAddress; + } + + static class Employee { + String name; + PersonalDetails personalDetails; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public PersonalDetails getPersonalDetails() { + return personalDetails; + } + + public void setPersonalDetails(PersonalDetails personalDetails) { + this.personalDetails = personalDetails; + } + } + + static class PersonalDetails { + String emailAddress; + String phone; + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + } +} diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/npe/HelpfulNullPointerExceptionUnitTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/npe/HelpfulNullPointerExceptionUnitTest.java new file mode 100644 index 0000000000..1b5153c706 --- /dev/null +++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/npe/HelpfulNullPointerExceptionUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.java14.npe; + +import org.junit.Test; + +import static com.baeldung.java14.helpfulnullpointerexceptions.HelpfulNullPointerException.Employee; +import static com.baeldung.java14.helpfulnullpointerexceptions.HelpfulNullPointerException.PersonalDetails; +import static org.assertj.core.api.Assertions.assertThat; + +public class HelpfulNullPointerExceptionUnitTest { + + @Test (expected = NullPointerException.class) + public void givenAnEmptyPersonalDetails_whenEmailAddressIsAccessed_thenThrowNPE() { + var helpfulNPE = new HelpfulNullPointerException(); + + var employee = new Employee(); + employee.setName("Eduard"); + employee.setPersonalDetails(new PersonalDetails()); + helpfulNPE.getEmployeeEmailAddress(employee); + } + + @Test + public void givenCompletePersonalDetails_whenEmailAddressIsAccessed_thenSuccess() { + var helpfulNPE = new HelpfulNullPointerException(); + var emailAddress = "eduard@gmx.com"; + + var employee = new Employee(); + employee.setName("Eduard"); + + var personalDetails = new PersonalDetails(); + personalDetails.setEmailAddress(emailAddress.toUpperCase()); + personalDetails.setPhone("1234"); + employee.setPersonalDetails(personalDetails); + + assertThat(helpfulNPE.getEmployeeEmailAddress(employee)).isEqualTo(emailAddress); + } + +} diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md index 961941aac7..c1c09d2192 100644 --- a/core-java-modules/core-java-8-2/README.md +++ b/core-java-modules/core-java-8-2/README.md @@ -4,7 +4,6 @@ This module contains articles about Java 8 core features ### Relevant Articles: -- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) - [Run a Java Application from the Command Line](https://www.baeldung.com/java-run-jar-with-arguments) - [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit) - [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface) diff --git a/core-java-modules/core-java-8-datetime-2/README.md b/core-java-modules/core-java-8-datetime-2/README.md new file mode 100644 index 0000000000..f16563aacc --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/README.md @@ -0,0 +1,5 @@ +### Relevant Articles: + +- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates) +- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values) +- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1) \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-java8-2/pom.xml b/core-java-modules/core-java-8-datetime-2/pom.xml similarity index 91% rename from core-java-modules/core-java-datetime-java8-2/pom.xml rename to core-java-modules/core-java-8-datetime-2/pom.xml index a15113bddc..ce98b72781 100644 --- a/core-java-modules/core-java-datetime-java8-2/pom.xml +++ b/core-java-modules/core-java-8-datetime-2/pom.xml @@ -4,9 +4,9 @@ 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 - core-java-datetime-java8 + core-java-8-datetime ${project.parent.version} - core-java-datetime-java8 + core-java-8-datetime jar @@ -64,8 +64,8 @@ - 1.9 - 1.9 + 1.8 + 1.8 2.10 3.6.1 diff --git a/core-java-modules/core-java-datetime-java8-2/src/main/java/com/baeldung/localdate/LocalDateExample.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/localdate/LocalDateExample.java similarity index 100% rename from core-java-modules/core-java-datetime-java8-2/src/main/java/com/baeldung/localdate/LocalDateExample.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/localdate/LocalDateExample.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDateTimes.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDateTimes.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDateTimes.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDateTimes.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDates.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDates.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDates.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDates.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomTimes.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomTimes.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomTimes.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomTimes.java diff --git a/core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java similarity index 87% rename from core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java index dff15486a4..d65118ba3a 100644 --- a/core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java @@ -11,31 +11,31 @@ public class LocalDateExampleUnitTest { @Test public void givenValues_whenUsingOfMethod_thenLocalDate() { - assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8)); + assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8).toString()); } @Test public void givenValuesWithMonthEnum_whenUsingOfMethod_thenLocalDate() { - assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8)); + assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8).toString()); } @Test public void givenValues_whenUsingEpochDay_thenLocalDate() { - assertEquals("2020-01-08", date.getDateFromEpochDay(18269)); + assertEquals("2020-01-08", date.getDateFromEpochDay(18269).toString()); } @Test public void givenValues_whenUsingYearDay_thenLocalDate() { - assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8)); + assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8).toString()); } @Test public void givenValues_whenUsingParse_thenLocalDate() { - assertEquals("2020-01-08", date.getDateFromString("2020-01-08")); + assertEquals("2020-01-08", date.getDateFromString("2020-01-08").toString()); } @Test public void givenValuesWithFormatter_whenUsingParse_thenLocalDate() { - assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy")); + assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy").toString()); } } diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDatesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDatesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDatesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDatesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomTimesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomTimesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomTimesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/README.md b/core-java-modules/core-java-8-datetime/README.md similarity index 92% rename from core-java-modules/core-java-datetime-java8/README.md rename to core-java-modules/core-java-8-datetime/README.md index dfbe9c997f..c35683a589 100644 --- a/core-java-modules/core-java-datetime-java8/README.md +++ b/core-java-modules/core-java-8-datetime/README.md @@ -13,4 +13,4 @@ This module contains articles about the Date and Time API introduced with Java 8 - [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) - [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone) - [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates) -- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates) +- [[Next -->]](/core-java-modules/core-java-datetime-java8-2) diff --git a/core-java-modules/core-java-datetime-java8/pom.xml b/core-java-modules/core-java-8-datetime/pom.xml similarity index 91% rename from core-java-modules/core-java-datetime-java8/pom.xml rename to core-java-modules/core-java-8-datetime/pom.xml index a15113bddc..ce98b72781 100644 --- a/core-java-modules/core-java-datetime-java8/pom.xml +++ b/core-java-modules/core-java-8-datetime/pom.xml @@ -4,9 +4,9 @@ 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 - core-java-datetime-java8 + core-java-8-datetime ${project.parent.version} - core-java-datetime-java8 + core-java-8-datetime jar @@ -64,8 +64,8 @@ - 1.9 - 1.9 + 1.8 + 1.8 2.10 3.6.1 diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDuration.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDuration.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDuration.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDate.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDate.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDate.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDateTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UsePeriod.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UsePeriod.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UsePeriod.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseToInstant.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseToInstant.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseToInstant.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseZonedDateTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseZonedDateTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/ConversionExample.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/ConversionExample.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/ConversionExample.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/ConversionExample.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java diff --git a/core-java-modules/core-java-9/README.md b/core-java-modules/core-java-9/README.md index bfd426b9c1..0a9bf76ac4 100644 --- a/core-java-modules/core-java-9/README.md +++ b/core-java-modules/core-java-9/README.md @@ -8,8 +8,4 @@ This module contains articles about Java 9 core features - [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue) - [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) - [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list) - -Note: also contains part of the code for the article -[How to Filter a Collection in Java](https://www.baeldung.com/java-collection-filtering). diff --git a/core-java-modules/core-java-arrays-2/README.md b/core-java-modules/core-java-arrays-2/README.md deleted file mode 100644 index c4ae3f03f7..0000000000 --- a/core-java-modules/core-java-arrays-2/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## Core Java Arrays (Part 2) - -This module contains articles about Java arrays - -## Relevant Articles - -- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end) -- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array) -- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array) -- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array) -- [Array Operations in Java](https://www.baeldung.com/java-common-array-operations) -- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) -- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element) -- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element) -- [Adding an Element to a Java Array vs an ArrayList](https://www.baeldung.com/java-add-element-to-array-vs-list) -- [Arrays.sort vs Arrays.parallelSort](https://www.baeldung.com/java-arrays-sort-vs-parallelsort) -- [[<-- Prev]](/core-java-modules/core-java-arrays) diff --git a/core-java-modules/core-java-arrays-3/README.md b/core-java-modules/core-java-arrays-3/README.md deleted file mode 100644 index 255d3d097d..0000000000 --- a/core-java-modules/core-java-arrays-3/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Arrays.deepEquals](https://www.baeldung.com/java-arrays-deepequals) diff --git a/core-java-modules/core-java-arrays-convert/README.md b/core-java-modules/core-java-arrays-convert/README.md new file mode 100644 index 0000000000..4bd060a246 --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/README.md @@ -0,0 +1,7 @@ +## Core Java Arrays - Conversions + +This module contains articles about arrays conversion in Java + +## Relevant Articles +- [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-convert/pom.xml b/core-java-modules/core-java-arrays-convert/pom.xml new file mode 100644 index 0000000000..bd50289f47 --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/pom.xml @@ -0,0 +1,27 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-arrays-convert + core-java-arrays-convert + jar + + + + com.google.guava + guava + ${guava.version} + + + + + 28.2-jre + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/FloatToByteArray.java b/core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/FloatToByteArray.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/FloatToByteArray.java rename to core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/FloatToByteArray.java diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java b/core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java rename to core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/FloatToByteArrayUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/FloatToByteArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/FloatToByteArrayUnitTest.java rename to core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/FloatToByteArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java rename to core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java diff --git a/core-java-modules/core-java-arrays-guides/README.md b/core-java-modules/core-java-arrays-guides/README.md new file mode 100644 index 0000000000..2e66080002 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/README.md @@ -0,0 +1,7 @@ +## Core Java Arrays - Guides + +This module contains complete guides about arrays in Java + +### Relevant Articles: +- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) +- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-guides/pom.xml b/core-java-modules/core-java-arrays-guides/pom.xml new file mode 100644 index 0000000000..ef718d5117 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/pom.xml @@ -0,0 +1,32 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-arrays-guides + core-java-arrays-guides + jar + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + + 1.19 + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayReferenceGuide.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayReferenceGuide.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayReferenceGuide.java rename to core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayReferenceGuide.java diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arrays/ParallelPrefixBenchmark.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/arrays/ParallelPrefixBenchmark.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/arrays/ParallelPrefixBenchmark.java rename to core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/arrays/ParallelPrefixBenchmark.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/arrays/ArraysUnitTest.java b/core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/arrays/ArraysUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/arrays/ArraysUnitTest.java rename to core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/arrays/ArraysUnitTest.java diff --git a/core-java-modules/core-java-arrays-multidimensional/README.md b/core-java-modules/core-java-arrays-multidimensional/README.md new file mode 100644 index 0000000000..d92747a4fb --- /dev/null +++ b/core-java-modules/core-java-arrays-multidimensional/README.md @@ -0,0 +1,7 @@ +## Core Java Arrays - Multidimensional + +This module contains articles about multidimensional arrays in Java + +### Relevant Articles: +- [Multi-Dimensional Arrays In Java](https://www.baeldung.com/java-jagged-arrays) +- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array) \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-multidimensional/pom.xml b/core-java-modules/core-java-arrays-multidimensional/pom.xml new file mode 100644 index 0000000000..6e49a20521 --- /dev/null +++ b/core-java-modules/core-java-arrays-multidimensional/pom.xml @@ -0,0 +1,15 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-arrays-multidimensional + core-java-arrays-multidimensional + jar + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java b/core-java-modules/core-java-arrays-multidimensional/src/main/java/com/baeldung/array/MultiDimensionalArray.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java rename to core-java-modules/core-java-arrays-multidimensional/src/main/java/com/baeldung/array/MultiDimensionalArray.java diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java b/core-java-modules/core-java-arrays-multidimensional/src/main/java/com/baeldung/array/looping/LoopDiagonally.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java rename to core-java-modules/core-java-arrays-multidimensional/src/main/java/com/baeldung/array/looping/LoopDiagonally.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java b/core-java-modules/core-java-arrays-multidimensional/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java rename to core-java-modules/core-java-arrays-multidimensional/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java b/core-java-modules/core-java-arrays-multidimensional/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java rename to core-java-modules/core-java-arrays-multidimensional/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java diff --git a/core-java-modules/core-java-arrays-operations-advanced/README.md b/core-java-modules/core-java-arrays-operations-advanced/README.md new file mode 100644 index 0000000000..af0c00641a --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/README.md @@ -0,0 +1,9 @@ +## Core Java Arrays - Advanced Operations + +This module contains articles about advanced operations on arrays in Java. They assume some background knowledge with arrays in Java. + +### Relevant Articles: +- [How to Copy an Array in Java](https://www.baeldung.com/java-array-copy) +- [Arrays.deepEquals](https://www.baeldung.com/java-arrays-deepequals) +- [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average) +- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) diff --git a/core-java-modules/core-java-arrays-operations-advanced/pom.xml b/core-java-modules/core-java-arrays-operations-advanced/pom.xml new file mode 100644 index 0000000000..8989e91189 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/pom.xml @@ -0,0 +1,36 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + + 4.0.0 + + core-java-arrays-operations-advanced + core-java-arrays-operations-advanced + jar + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + 3.9 + + 3.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SumAndAverageInArray.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/array/SumAndAverageInArray.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SumAndAverageInArray.java rename to core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/array/SumAndAverageInArray.java diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/array/operations/ArraysIntersectionOperations.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/array/operations/ArraysIntersectionOperations.java new file mode 100644 index 0000000000..6c4ce837ad --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/array/operations/ArraysIntersectionOperations.java @@ -0,0 +1,27 @@ +package com.baeldung.array.operations; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.stream.Stream; + +public class ArraysIntersectionOperations { + + public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b) { + return Stream.of(a) + .filter(Arrays.asList(b)::contains) + .toArray(Integer[]::new); + } + + public static Integer[] intersectionSet(final Integer[] a, final Integer[] b) { + return Stream.of(a) + .filter(Arrays.asList(b)::contains) + .distinct() + .toArray(Integer[]::new); + } + + public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b) { + return Stream.of(a) + .filter(new LinkedList<>(Arrays.asList(b))::remove) + .toArray(Integer[]::new); + } +} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Address.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycopy/model/Address.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Address.java rename to core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycopy/model/Address.java 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-operations-advanced/src/main/java/com/baeldung/arraycopy/model/Employee.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java rename to core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycopy/model/Employee.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java rename to core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java similarity index 97% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java rename to core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java index 1560cc5701..b0d4a80b06 100644 --- a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java @@ -2,7 +2,7 @@ package com.baeldung.array.operations; import org.junit.jupiter.api.Test; -import static com.baeldung.array.operations.ArrayOperations.*; +import static com.baeldung.array.operations.ArraysIntersectionOperations.*; import static org.assertj.core.api.Assertions.assertThat; class IntersectionUnitTest { diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java rename to core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilUnitTest.java diff --git a/core-java-modules/core-java-arrays-3/src/test/java/com/baeldung/arrays/deepequals/ArraysDeepEqualsUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arrays/deepequals/ArraysDeepEqualsUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-3/src/test/java/com/baeldung/arrays/deepequals/ArraysDeepEqualsUnitTest.java rename to core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arrays/deepequals/ArraysDeepEqualsUnitTest.java diff --git a/core-java-modules/core-java-arrays-operations-basic/README.md b/core-java-modules/core-java-arrays-operations-basic/README.md new file mode 100644 index 0000000000..ca81c23c98 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic/README.md @@ -0,0 +1,12 @@ +## Core Java Arrays - Basic Operations + +This module contains articles about Java array fundamentals. They assume no previous background knowledge on working with arrays. + +### Relevant Articles: +- [Initializing Arrays in Java](https://www.baeldung.com/java-initialize-array) +- [Array Operations in Java](https://www.baeldung.com/java-common-array-operations) +- [Adding an Element to a Java Array vs an ArrayList](https://www.baeldung.com/java-add-element-to-array-vs-list) +- [Check if a Java Array Contains a Value](https://www.baeldung.com/java-array-contains-value) +- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element) +- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element) +- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end) diff --git a/core-java-modules/core-java-arrays-2/pom.xml b/core-java-modules/core-java-arrays-operations-basic/pom.xml similarity index 72% rename from core-java-modules/core-java-arrays-2/pom.xml rename to core-java-modules/core-java-arrays-operations-basic/pom.xml index 1445a322d7..4480c14bb2 100644 --- a/core-java-modules/core-java-arrays-2/pom.xml +++ b/core-java-modules/core-java-arrays-operations-basic/pom.xml @@ -1,54 +1,19 @@ - + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + 4.0.0 - core-java-arrays-2 - 0.1.0-SNAPSHOT - core-java-arrays-2 + + core-java-arrays-operations-basic + core-java-arrays-operations-basic jar - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - org.openjdk.jmh - jmh-core - ${jmh.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh.version} - - - - org.assertj - assertj-core - ${assertj-core.version} - test - - - - core-java-arrays-2 - - - src/main/resources - true - - org.apache.maven.plugins @@ -74,13 +39,40 @@ - - 1.19 - - 3.9 - - 3.10.0 - 3.2.0 - + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + 3.2.0 + + 3.9 + + 1.19 + + 3.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/AddElementToEndOfArray.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/AddElementToEndOfArray.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/AddElementToEndOfArray.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/AddElementToEndOfArray.java diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java similarity index 86% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java index f35064b783..30c3978a3a 100644 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java +++ b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java @@ -9,7 +9,7 @@ public class ArrayBenchmarkRunner { public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() - .include(SearchArrayUnitTest.class.getSimpleName()).threads(1) + .include(SearchArrayBenchmark.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true).shouldDoGC(true) .jvmArgs("-server").build(); diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayInitializer.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/ArrayInitializer.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayInitializer.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/ArrayInitializer.java diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SearchArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/SearchArrayBenchmark.java similarity index 98% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SearchArrayUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/SearchArrayBenchmark.java index bed58356cb..fc4b513250 100644 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SearchArrayUnitTest.java +++ b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/SearchArrayBenchmark.java @@ -8,7 +8,7 @@ import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) @Warmup(iterations = 5) @OutputTimeUnit(TimeUnit.MICROSECONDS) -public class SearchArrayUnitTest { +public class SearchArrayBenchmark { @State(Scope.Benchmark) public static class SearchData { diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/operations/ArrayOperations.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/array/operations/ArrayOperations.java diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java rename to core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/AddElementToEndOfArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/AddElementToEndOfArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/AddElementToEndOfArrayUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/AddElementToEndOfArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/removefirst/RemoveFirstElementUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/removefirst/RemoveFirstElementUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/removefirst/RemoveFirstElementUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/removefirst/RemoveFirstElementUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java rename to core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java diff --git a/core-java-modules/core-java-arrays-sorting/README.md b/core-java-modules/core-java-arrays-sorting/README.md new file mode 100644 index 0000000000..f83dd43526 --- /dev/null +++ b/core-java-modules/core-java-arrays-sorting/README.md @@ -0,0 +1,9 @@ +## Core Java Arrays - Sorting + +This module contains articles about sorting arrays in Java + +### Relevant Articles: +- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays) +- [Checking If an Array Is Sorted in Java](https://www.baeldung.com/java-check-sorted-array) +- [How to Reverse an Array in Java](http://www.baeldung.com/java-invert-array) +- [Arrays.sort vs Arrays.parallelSort](https://www.baeldung.com/java-arrays-sort-vs-parallelsort) diff --git a/core-java-modules/core-java-arrays-sorting/pom.xml b/core-java-modules/core-java-arrays-sorting/pom.xml new file mode 100644 index 0000000000..127d921b2a --- /dev/null +++ b/core-java-modules/core-java-arrays-sorting/pom.xml @@ -0,0 +1,87 @@ + + + + core-java-modules + com.baeldung.core-java-modules + 1.0.0-SNAPSHOT + ../pom.xml + + 4.0.0 + + core-java-arrays-sorting + core-java-arrays-sorting + jar + + + + + org.apache.maven.plugins + maven-shade-plugin + ${shade.plugin.version} + + + package + + shade + + + benchmarks + + + org.openjdk.jmh.Main + + + + + + + + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + com.google.guava + guava + ${guava.version} + + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + 3.2.0 + + 3.9 + 28.2-jre + + 1.19 + + 3.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayInverter.java b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/array/ArrayInverter.java similarity index 100% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/ArrayInverter.java rename to core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/array/ArrayInverter.java diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/array/SortedArrayChecker.java similarity index 97% rename from core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java rename to core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/array/SortedArrayChecker.java index 78a9a8f4d1..8fa64972f2 100644 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java +++ b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/array/SortedArrayChecker.java @@ -1,7 +1,5 @@ package com.baeldung.array; -import com.baeldung.arraycopy.model.Employee; - import java.util.Comparator; public class SortedArrayChecker { diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java rename to core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java diff --git a/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/sort/Employee.java b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/sort/Employee.java new file mode 100644 index 0000000000..e9c737b74b --- /dev/null +++ b/core-java-modules/core-java-arrays-sorting/src/main/java/com/baeldung/sort/Employee.java @@ -0,0 +1,48 @@ +package com.baeldung.sort; + +import java.io.Serializable; + +public class Employee implements Serializable { + private static final long serialVersionUID = -2454619097207585825L; + private int id; + private String name; + private int age; + + public Employee() { + } + + public Employee(int id, String name) { + this.id = id; + 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; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java rename to core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/array/ArrayInverterUnitTest.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java similarity index 98% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java rename to core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java index 7971e0eab7..5411dcba72 100644 --- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java +++ b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java @@ -1,6 +1,6 @@ package com.baeldung.array; -import com.baeldung.arraycopy.model.Employee; +import com.baeldung.sort.Employee; import org.junit.Before; import org.junit.Test; diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraysort/SortComparisonUnitTest.java b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/arraysort/SortComparisonUnitTest.java similarity index 100% rename from core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraysort/SortComparisonUnitTest.java rename to core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/arraysort/SortComparisonUnitTest.java diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/sort/ArraySortUnitTest.java b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/sort/ArraySortUnitTest.java similarity index 98% rename from core-java-modules/core-java-arrays/src/test/java/com/baeldung/sort/ArraySortUnitTest.java rename to core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/sort/ArraySortUnitTest.java index 59035738fe..b89a870c51 100644 --- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/sort/ArraySortUnitTest.java +++ b/core-java-modules/core-java-arrays-sorting/src/test/java/com/baeldung/sort/ArraySortUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.sort; -import com.baeldung.arraycopy.model.Employee; import org.junit.Before; import org.junit.Test; @@ -86,5 +85,4 @@ public class ArraySortUnitTest { assertArrayEquals(new Employee[]{david, john, mary}, employees); } - } diff --git a/core-java-modules/core-java-arrays/README.md b/core-java-modules/core-java-arrays/README.md deleted file mode 100644 index 42fe3f83a1..0000000000 --- a/core-java-modules/core-java-arrays/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## Core Java Arrays - -This module contains articles about Java arrays - -### Relevant Articles: -- [How to Copy an Array in Java](https://www.baeldung.com/java-array-copy) -- [Check if a Java Array Contains a Value](https://www.baeldung.com/java-array-contains-value) -- [Initializing Arrays in Java](https://www.baeldung.com/java-initialize-array) -- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) -- [Multi-Dimensional Arrays In Java](https://www.baeldung.com/java-jagged-arrays) -- [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average) -- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) -- [Read and Write User Input in Java](https://www.baeldung.com/java-console-input-output) -- [How to Reverse an Array in Java](http://www.baeldung.com/java-invert-array) -- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays) -- [Checking If an Array Is Sorted in Java](https://www.baeldung.com/java-check-sorted-array) -- [[More -->]](/core-java-modules/core-java-arrays-2) diff --git a/core-java-modules/core-java-arrays/pom.xml b/core-java-modules/core-java-arrays/pom.xml deleted file mode 100644 index ea28eb25eb..0000000000 --- a/core-java-modules/core-java-arrays/pom.xml +++ /dev/null @@ -1,180 +0,0 @@ - - - 4.0.0 - core-java-arrays - 0.1.0-SNAPSHOT - core-java-arrays - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - org.assertj - assertj-core - ${assertj-core.version} - test - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-generator-annprocess.version} - - - - - core-java-arrays - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - java - com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed - - -Xmx300m - -XX:+UseParallelGC - -classpath - - com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - ${source.version} - ${target.version} - - - - - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - json - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - - run-benchmarks - - none - - exec - - - test - java - - -classpath - - org.openjdk.jmh.Main - .* - - - - - - - - - - - - - - 3.9 - - 1.19 - 1.19 - - - 3.10.0 - - - 3.0.0-M1 - 1.6.0 - 1.8 - 1.8 - - - diff --git a/core-java-modules/core-java-collections-2/README.md b/core-java-modules/core-java-collections-2/README.md index de5daddb38..e5f6126811 100644 --- a/core-java-modules/core-java-collections-2/README.md +++ b/core-java-modules/core-java-collections-2/README.md @@ -12,4 +12,3 @@ - [Sorting in Java](https://www.baeldung.com/java-sorting) - [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size) - [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) -- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) diff --git a/java-collections-maps-2/README.md b/core-java-modules/core-java-collections-maps-2/README.md similarity index 86% rename from java-collections-maps-2/README.md rename to core-java-modules/core-java-collections-maps-2/README.md index 8b33276f56..f49ba25c8c 100644 --- a/java-collections-maps-2/README.md +++ b/core-java-modules/core-java-collections-maps-2/README.md @@ -13,5 +13,4 @@ This module contains articles about Map data structures in Java. - [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort) - [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap) -- More articles: [[<-- prev>]](/../java-collections-maps) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps) [[next -->]](/core-java-modules/core-java-collections-maps-3) diff --git a/java-collections-maps-2/pom.xml b/core-java-modules/core-java-collections-maps-2/pom.xml similarity index 94% rename from java-collections-maps-2/pom.xml rename to core-java-modules/core-java-collections-maps-2/pom.xml index a246559f61..a08a4ac072 100644 --- a/java-collections-maps-2/pom.xml +++ b/core-java-modules/core-java-collections-maps-2/pom.xml @@ -3,16 +3,16 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - java-collections-maps-2 + core-java-collections-maps-2 0.1.0-SNAPSHOT - java-collections-maps-2 + core-java-collections-maps-2 jar com.baeldung parent-java 0.0.1-SNAPSHOT - ../parent-java + ../../parent-java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/Product.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/Product.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java similarity index 100% rename from java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java rename to core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java similarity index 77% rename from java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java index 2015909870..ba29d5c454 100644 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java @@ -3,6 +3,8 @@ package com.baeldung.map; import org.junit.jupiter.api.Test; import java.util.HashMap; +import java.util.Map; +import java.util.Objects; import static org.junit.jupiter.api.Assertions.*; @@ -121,4 +123,52 @@ class ProductUnitTest { assertNull(productsByName.get("E-Bike")); } + @Test + public void givenMutableKeyWhenKeyChangeThenValueNotFound() { + // Given + MutableKey key = new MutableKey("initial"); + + Map items = new HashMap<>(); + items.put(key, "success"); + + // When + key.setName("changed"); + + // Then + assertNull(items.get(key)); + } + + static class MutableKey { + private String name; + + public MutableKey(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MutableKey that = (MutableKey) o; + return Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + } + } diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-3/README.md b/core-java-modules/core-java-collections-maps-3/README.md new file mode 100644 index 0000000000..64a3b75d83 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/README.md @@ -0,0 +1,8 @@ +## Java Collections Cookbooks and Examples + +This module contains articles about Map data structures in Java. + +### Relevant Articles: +- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap) +- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2) diff --git a/core-java-modules/core-java-collections-maps-3/pom.xml b/core-java-modules/core-java-collections-maps-3/pom.xml new file mode 100644 index 0000000000..95414c12c2 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + core-java-collections-maps-3 + 0.1.0-SNAPSHOT + core-java-collections-maps-3 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + + + + + + \ No newline at end of file diff --git a/java-collections-maps/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java rename to core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/computeifabsent/ComputeIfAbsentUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/computeifabsent/ComputeIfAbsentUnitTest.java new file mode 100644 index 0000000000..391a059f05 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/computeifabsent/ComputeIfAbsentUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.map.computeifabsent; + +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class ComputeIfAbsentUnitTest { + + @Test + public void whenKeyIsPresent_thenFetchTheValue() { + Map stringLength = new HashMap<>(); + stringLength.put("John", 5); + assertEquals((long)stringLength.computeIfAbsent("John", s -> s.length()), 5); + } + + @Test + public void whenKeyIsNotPresent_thenComputeTheValueUsingMappingFunctionAndStore() { + Map stringLength = new HashMap<>(); + assertEquals((long)stringLength.computeIfAbsent("John", s -> s.length()), 4); + assertEquals((long)stringLength.get("John"), 4); + } + + @Test + public void whenMappingFunctionReturnsNull_thenDoNotRecordMapping() { + Map stringLength = new HashMap<>(); + assertEquals(stringLength.computeIfAbsent("John", s -> null), null); + assertNull(stringLength.get("John")); + } + + @Test(expected = RuntimeException.class) + public void whenMappingFunctionThrowsException_thenExceptionIsRethrown() { + Map stringLength = new HashMap<>(); + stringLength.computeIfAbsent("John", s -> {throw new RuntimeException();}); + } +} diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java rename to core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java diff --git a/java-collections-maps/README.md b/core-java-modules/core-java-collections-maps/README.md similarity index 81% rename from java-collections-maps/README.md rename to core-java-modules/core-java-collections-maps/README.md index dfd0d47dbc..15cb32fbe8 100644 --- a/java-collections-maps/README.md +++ b/core-java-modules/core-java-collections-maps/README.md @@ -4,14 +4,12 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: - [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap) -- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) - [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap) - [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap) - [How to Store Duplicate Keys in a Map in Java?](https://www.baeldung.com/java-map-duplicate-keys) - [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value) - [How to Check If a Key Exists in a Map](https://www.baeldung.com/java-map-key-exists) -- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) - [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps) - [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map) - [The Java HashMap Under the Hood](https://www.baeldung.com/java-hashmap-advanced) -- More articles: [[next -->]](/../java-collections-maps-2) +- More articles: [[next -->]](/core-java-modules/core-java-collections-maps-2) diff --git a/java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml similarity index 87% rename from java-collections-maps/pom.xml rename to core-java-modules/core-java-collections-maps/pom.xml index 38cf1c38ad..c0dd705c1c 100644 --- a/java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -2,16 +2,16 @@ 4.0.0 - java-collections-maps + core-java-collections-maps 0.1.0-SNAPSHOT - java-collections-maps + core-java-collections-maps jar - + com.baeldung parent-java 0.0.1-SNAPSHOT - ../parent-java + ../../parent-java diff --git a/java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java similarity index 100% rename from java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java rename to core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java diff --git a/java-collections-maps/src/main/java/com/baeldung/map/MyKey.java b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyKey.java similarity index 100% rename from java-collections-maps/src/main/java/com/baeldung/map/MyKey.java rename to core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyKey.java diff --git a/java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java similarity index 100% rename from java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java rename to core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java diff --git a/java-math/src/main/resources/logback.xml b/core-java-modules/core-java-collections-maps/src/main/resources/logback.xml similarity index 100% rename from java-math/src/main/resources/logback.xml rename to core-java-modules/core-java-collections-maps/src/main/resources/logback.xml diff --git a/java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java rename to core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java diff --git a/core-java-modules/core-java-collections-set/README.md b/core-java-modules/core-java-collections-set/README.md index 2b34ef3449..b97cd3216f 100644 --- a/core-java-modules/core-java-collections-set/README.md +++ b/core-java-modules/core-java-collections-set/README.md @@ -11,3 +11,4 @@ This module contains articles about the Java Set collection - [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) +- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 8ba1b2400d..c89ba0c091 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -34,7 +34,23 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + 11 + 11 4.3 2.8.5 diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java similarity index 97% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java rename to core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java index 7dbcd2a3a3..2af040b13e 100644 --- a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java +++ b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java @@ -1,4 +1,4 @@ -package com.baeldung.java9.set; +package com.baeldung.set; import com.google.common.collect.ImmutableSet; diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java b/core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java similarity index 97% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java rename to core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java index 28e71affcc..d89927dfd6 100644 --- a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java +++ b/core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java @@ -1,9 +1,10 @@ -package com.baeldung.java9; +package com.baeldung.set; + +import org.junit.Test; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import org.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/core-java-modules/core-java-collections/README.md b/core-java-modules/core-java-collections/README.md index 340c2b286e..12e3c5ac17 100644 --- a/core-java-modules/core-java-collections/README.md +++ b/core-java-modules/core-java-collections/README.md @@ -3,7 +3,6 @@ This module contains articles about Java collections ### Relevant Articles: -- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection) - [Introduction to the Java ArrayDeque](https://www.baeldung.com/java-array-deque) - [An Introduction to Java.util.Hashtable Class](https://www.baeldung.com/java-hash-table) - [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe) @@ -13,4 +12,4 @@ This module contains articles about Java collections - [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack) - [Guide to the Java Queue Interface](https://www.baeldung.com/java-queue) - [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections) -- [[More -->]](/core-java-modules/core-java-collections-2) \ No newline at end of file +- [[More -->]](/core-java-modules/core-java-collections-2) diff --git a/core-java-modules/core-java-concurrency-advanced-3/README.md b/core-java-modules/core-java-concurrency-advanced-3/README.md index 2c554e948b..b11cde5158 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/README.md +++ b/core-java-modules/core-java-concurrency-advanced-3/README.md @@ -10,4 +10,5 @@ This module contains articles about advanced topics about multithreading with co - [Guide to RejectedExecutionHandler](https://www.baeldung.com/java-rejectedexecutionhandler) - [Guide to Work Stealing in Java](https://www.baeldung.com/java-work-stealing) - [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming) +- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock) - [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2) diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java new file mode 100644 index 0000000000..1a46e1ba52 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java @@ -0,0 +1,34 @@ +package com.baeldung.atomicstampedreference; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicStampedReference; + +public class StampedAccount { + + private AtomicInteger stamp = new AtomicInteger(0); + private AtomicStampedReference account = new AtomicStampedReference<>(0, 0); + + public int getBalance() { + return this.account.get(new int[1]); + } + + public int getStamp() { + int[] stamps = new int[1]; + this.account.get(stamps); + return stamps[0]; + } + + public boolean deposit(int funds) { + int[] stamps = new int[1]; + int current = this.account.get(stamps); + int newStamp = this.stamp.incrementAndGet(); + return this.account.compareAndSet(current, current + funds, stamps[0], newStamp); + } + + public boolean withdrawal(int funds) { + int[] stamps = new int[1]; + int current = this.account.get(stamps); + int newStamp = this.stamp.incrementAndGet(); + return this.account.compareAndSet(current, current - funds, stamps[0], newStamp); + } +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java new file mode 100644 index 0000000000..ce83355073 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.atomicstampedreference; + +import org.junit.Assert; +import org.junit.Test; + +public class ThreadStampedAccountUnitTest { + + @Test + public void givenMultiThread_whenStampedAccount_thenSetBalance() throws InterruptedException { + StampedAccount account = new StampedAccount(); + Thread t = new Thread(() -> { + while (!account.withdrawal(100)) + Thread.yield(); + }); + t.start(); + Assert.assertTrue(account.deposit(100)); + t.join(1_000); + Assert.assertFalse(t.isAlive()); + Assert.assertSame(0, account.getBalance()); + } +} diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/TaskRunner.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/TaskRunner.java new file mode 100644 index 0000000000..f0493d4911 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/TaskRunner.java @@ -0,0 +1,25 @@ +package com.baeldung.concurrent.volatilekeyword; + +public class TaskRunner { + + private static int number; + private volatile static boolean ready; + + private static class Reader extends Thread { + + @Override + public void run() { + while (!ready) { + Thread.yield(); + } + + System.out.println(number); + } + } + + public static void main(String[] args) { + new Reader().start(); + number = 42; + ready = true; + } +} diff --git a/core-java-modules/core-java-concurrency-basic-2/README.md b/core-java-modules/core-java-concurrency-basic-2/README.md index e3f7a94e14..c7143baf36 100644 --- a/core-java-modules/core-java-concurrency-basic-2/README.md +++ b/core-java-modules/core-java-concurrency-basic-2/README.md @@ -8,4 +8,5 @@ This module contains articles about basic Java concurrency - [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep) - [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized) - [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle) -- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic) \ No newline at end of file +- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference) +- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic) diff --git a/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/atomic/AtomicMarkableReferenceUnitTest.java b/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/atomic/AtomicMarkableReferenceUnitTest.java new file mode 100644 index 0000000000..5f526344be --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-2/src/test/java/com/baeldung/concurrent/atomic/AtomicMarkableReferenceUnitTest.java @@ -0,0 +1,189 @@ +package com.baeldung.concurrent.atomic; + +import java.util.concurrent.atomic.AtomicMarkableReference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class AtomicMarkableReferenceUnitTest { + + class Employee { + private int id; + private String name; + + Employee(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @Test + void givenMarkValueAsTrue_whenUsingIsMarkedMethod_thenMarkValueShouldBeTrue() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenMarkValueAsFalse_whenUsingIsMarkedMethod_thenMarkValueShouldBeFalse() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, false); + + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void whenUsingGetReferenceMethod_thenCurrentReferenceShouldBeReturned() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Assertions.assertEquals(employee, employeeNode.getReference()); + } + + @Test + void whenUsingGetMethod_thenCurrentReferenceAndMarkShouldBeReturned() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + boolean[] markHolder = new boolean[1]; + Employee currentEmployee = employeeNode.get(markHolder); + + Assertions.assertEquals(employee, currentEmployee); + Assertions.assertTrue(markHolder[0]); + } + + @Test + void givenNewReferenceAndMark_whenUsingSetMethod_thenCurrentReferenceAndMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Employee newEmployee = new Employee(124, "John"); + employeeNode.set(newEmployee, false); + + Assertions.assertEquals(newEmployee, employeeNode.getReference()); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenTheSameObjectReference_whenUsingAttemptMarkMethod_thenMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + + Assertions.assertTrue(employeeNode.attemptMark(employee, false)); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenDifferentObjectReference_whenUsingAttemptMarkMethod_thenMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee expectedEmployee = new Employee(123, "Mike"); + + Assertions.assertFalse(employeeNode.attemptMark(expectedEmployee, false)); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertTrue(employeeNode.compareAndSet(employee, newEmployee, true, false)); + Assertions.assertEquals(newEmployee, employeeNode.getReference()); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.compareAndSet(new Employee(1234, "Steve"), newEmployee, true, false)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndNotCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.compareAndSet(employee, newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndNotCurrentMark_whenUsingCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.compareAndSet(new Employee(1234, "Steve"), newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertTrue(employeeNode.weakCompareAndSet(employee, newEmployee, true, false)); + Assertions.assertEquals(newEmployee, employeeNode.getReference()); + Assertions.assertFalse(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.weakCompareAndSet(new Employee(1234, "Steve"), newEmployee, true, false)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenCurrentReferenceAndNotCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.weakCompareAndSet(employee, newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } + + @Test + void givenNotCurrentReferenceAndNotCurrentMark_whenUsingWeakCompareAndSet_thenReferenceAndMarkShouldNotBeUpdated() { + Employee employee = new Employee(123, "Mike"); + AtomicMarkableReference employeeNode = new AtomicMarkableReference(employee, true); + Employee newEmployee = new Employee(124, "John"); + + Assertions.assertFalse(employeeNode.weakCompareAndSet(new Employee(1234, "Steve"), newEmployee, false, true)); + Assertions.assertEquals(employee, employeeNode.getReference()); + Assertions.assertTrue(employeeNode.isMarked()); + } +} diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java index 5fcb28cd2a..ebd027ea68 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java @@ -9,7 +9,7 @@ import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCount import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable; import com.baeldung.concurrent.threadsafety.services.AtomicCounter; import com.baeldung.concurrent.threadsafety.services.Counter; -import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import com.baeldung.concurrent.threadsafety.services.ObjectLockCounter; import com.baeldung.concurrent.threadsafety.services.MessageService; import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter; import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter; @@ -48,9 +48,9 @@ public class Application { System.out.println(future3.get()); System.out.println(future4.get()); - ExtrinsicLockCounter extrinsicLockCounter = new ExtrinsicLockCounter(); - Future future5 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter)); - Future future6 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter)); + ObjectLockCounter objectLockCounter = new ObjectLockCounter(); + Future future5 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(objectLockCounter)); + Future future6 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(objectLockCounter)); System.out.println(future5.get()); System.out.println(future6.get()); diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java index 370e5d1f00..dcc929d3c4 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java @@ -1,13 +1,13 @@ package com.baeldung.concurrent.threadsafety.callables; -import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import com.baeldung.concurrent.threadsafety.services.ObjectLockCounter; import java.util.concurrent.Callable; public class ExtrinsicLockCounterCallable implements Callable { - private final ExtrinsicLockCounter counter; + private final ObjectLockCounter counter; - public ExtrinsicLockCounterCallable(ExtrinsicLockCounter counter) { + public ExtrinsicLockCounterCallable(ObjectLockCounter counter) { this.counter = counter; } diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ObjectLockCounter.java similarity index 84% rename from core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java rename to core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ObjectLockCounter.java index 0a6ff3f60e..f31cf899ba 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ObjectLockCounter.java @@ -1,11 +1,11 @@ package com.baeldung.concurrent.threadsafety.services; -public class ExtrinsicLockCounter { +public class ObjectLockCounter { private int counter; private final Object lock = new Object(); - public ExtrinsicLockCounter() { + public ObjectLockCounter() { this.counter = 0; } diff --git a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ExtrinsicLockCounterUnitTest.java b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ObjectLockCounterUnitTest.java similarity index 82% rename from core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ExtrinsicLockCounterUnitTest.java rename to core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ObjectLockCounterUnitTest.java index 0fc3dd3a54..b0ac80a3aa 100644 --- a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ExtrinsicLockCounterUnitTest.java +++ b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ObjectLockCounterUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.concurrent.threadsafety; import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable; -import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import com.baeldung.concurrent.threadsafety.services.ObjectLockCounter; import org.junit.Test; import java.util.concurrent.ExecutorService; @@ -10,12 +10,12 @@ import java.util.concurrent.Future; import static org.assertj.core.api.Assertions.assertThat; -public class ExtrinsicLockCounterUnitTest { +public class ObjectLockCounterUnitTest { @Test public void whenCalledIncrementCounter_thenCorrect() throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(2); - ExtrinsicLockCounter counter = new ExtrinsicLockCounter(); + ObjectLockCounter counter = new ObjectLockCounter(); Future future1 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); Future future2 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); diff --git a/core-java-modules/core-java-concurrency-collections-2/README.md b/core-java-modules/core-java-concurrency-collections-2/README.md new file mode 100644 index 0000000000..91da6c623c --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Lock Striping](https://www.baeldung.com/java-lock-stripping) diff --git a/core-java-modules/core-java-concurrency-collections-2/pom.xml b/core-java-modules/core-java-concurrency-collections-2/pom.xml new file mode 100644 index 0000000000..65a91c9a9c --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + com.baeldung.concurrent.lock + core-java-concurrency-collections-2 + 0.0.1-SNAPSHOT + + + + com.google.guava + guava + ${guava.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + + src + + + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + + + + 1.21 + 28.2-jre + + + \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessBenchmark.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessBenchmark.java new file mode 100644 index 0000000000..ceb53ce077 --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessBenchmark.java @@ -0,0 +1,54 @@ +package com.baeldung.concurrent.lock; + +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.Map; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +@State(Scope.Thread) +@Fork(value = 2) +@Warmup(iterations = 0) +public class ConcurrentAccessBenchmark { + static final int SLOTS = 4; + static final int THREADS = 10000; + static final int BUCKETS = Runtime.getRuntime().availableProcessors() * SLOTS; + SingleLock singleLock = new SingleLock(); + StripedLock stripedLock = new StripedLock(BUCKETS); + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map singleLockHashMap() throws InterruptedException { + return singleLock.doWork(new HashMap(), THREADS, SLOTS); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map stripedLockHashMap() throws InterruptedException { + return stripedLock.doWork(new HashMap(), THREADS, SLOTS); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map singleLockConcurrentHashMap() throws InterruptedException { + return singleLock.doWork(new ConcurrentHashMap(), THREADS, SLOTS); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + public Map stripedLockConcurrentHashMap() throws InterruptedException { + return stripedLock.doWork(new ConcurrentHashMap(), THREADS, SLOTS); + } +} diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessExperiment.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessExperiment.java new file mode 100644 index 0000000000..ec6d3895da --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/ConcurrentAccessExperiment.java @@ -0,0 +1,26 @@ +package com.baeldung.concurrent.lock; + +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +import com.google.common.base.Supplier; + +public abstract class ConcurrentAccessExperiment { + + public final Map doWork(Map map, int threads, int slots) { + CompletableFuture[] requests = new CompletableFuture[threads * slots]; + + for (int i = 0; i < threads; i++) { + requests[slots * i + 0] = CompletableFuture.supplyAsync(putSupplier(map, i)); + requests[slots * i + 1] = CompletableFuture.supplyAsync(getSupplier(map, i)); + requests[slots * i + 2] = CompletableFuture.supplyAsync(getSupplier(map, i)); + requests[slots * i + 3] = CompletableFuture.supplyAsync(getSupplier(map, i)); + } + CompletableFuture.allOf(requests).join(); + + return map; + } + + protected abstract Supplier putSupplier(Map map, int key); + protected abstract Supplier getSupplier(Map map, int key); +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/SingleLock.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/SingleLock.java new file mode 100644 index 0000000000..4dff459df6 --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/SingleLock.java @@ -0,0 +1,36 @@ +package com.baeldung.concurrent.lock; + +import java.util.Map; +import java.util.concurrent.locks.ReentrantLock; + +import com.google.common.base.Supplier; + +public class SingleLock extends ConcurrentAccessExperiment { + ReentrantLock lock; + + public SingleLock() { + lock = new ReentrantLock(); + } + + protected Supplier putSupplier(Map map, int key) { + return (()-> { + lock.lock(); + try { + return map.put("key" + key, "value" + key); + } finally { + lock.unlock(); + } + }); + } + + protected Supplier getSupplier(Map map, int key) { + return (()-> { + lock.lock(); + try { + return map.get("key" + key); + } finally { + lock.unlock(); + } + }); + } +} diff --git a/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/StripedLock.java b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/StripedLock.java new file mode 100644 index 0000000000..47c47d8813 --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/main/java/com/baeldung/concurrent/lock/StripedLock.java @@ -0,0 +1,41 @@ +package com.baeldung.concurrent.lock; + +import java.util.Map; +import java.util.concurrent.locks.Lock; + +import com.google.common.base.Supplier; +import com.google.common.util.concurrent.Striped; + +public class StripedLock extends ConcurrentAccessExperiment { + Striped stripedLock; + + public StripedLock(int buckets) { + stripedLock = Striped.lock(buckets); + } + + protected Supplier putSupplier(Map map, int key) { + return (()-> { + int bucket = key % stripedLock.size(); + Lock lock = stripedLock.get(bucket); + lock.lock(); + try { + return map.put("key" + key, "value" + key); + } finally { + lock.unlock(); + } + }); + } + + protected Supplier getSupplier(Map map, int key) { + return (()-> { + int bucket = key % stripedLock.size(); + Lock lock = stripedLock.get(bucket); + lock.lock(); + try { + return map.get("key" + key); + } finally { + lock.unlock(); + } + }); + } +} diff --git a/core-java-modules/core-java-concurrency-testing/README.md b/core-java-modules/core-java-concurrency-testing/README.md new file mode 100644 index 0000000000..fef74a6750 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/README.md @@ -0,0 +1,7 @@ +========= + +## Core Java Concurrency Testing Examples + +### Relevant Articles: +- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded) + diff --git a/core-java-modules/core-java-concurrency-testing/pom.xml b/core-java-modules/core-java-concurrency-testing/pom.xml new file mode 100644 index 0000000000..51de83f67c --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + core-java-concurrency-testing + 0.1.0-SNAPSHOT + core-java-concurrency-testing + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + junit + junit + 4.13 + test + + + com.googlecode.thread-weaver + threadweaver + 0.2 + test + + + com.google.code.tempus-fugit + tempus-fugit + 1.1 + test + + + com.googlecode.multithreadedtc + multithreadedtc + 1.01 + test + + + org.openjdk.jcstress + jcstress-core + 0.5 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${javac.target} + ${javac.target} + ${javac.target} + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + main + package + + shade + + + jcstress + + + org.openjdk.jcstress.Main + + + META-INF/TestList + + + + + + + + + + diff --git a/core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java b/core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java new file mode 100644 index 0000000000..a678b047a8 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent; + +public class MyCounter { + + private int count; + + public void increment() { + int temp = count; + count = temp + 1; + } + + public synchronized void incrementWithWait() throws InterruptedException { + int temp = count; + wait(100); + count = temp + 1; + } + + public int getCount() { + return count; + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml b/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java new file mode 100644 index 0000000000..6c76505347 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.concurrent; + +import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE; +import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE_INTERESTING; + +import org.openjdk.jcstress.annotations.Actor; +import org.openjdk.jcstress.annotations.Arbiter; +import org.openjdk.jcstress.annotations.JCStressTest; +import org.openjdk.jcstress.annotations.Outcome; +import org.openjdk.jcstress.annotations.State; +import org.openjdk.jcstress.infra.results.I_Result; + +@JCStressTest +@Outcome(id = "1", expect = ACCEPTABLE_INTERESTING, desc = "One update lost.") +@Outcome(id = "2", expect = ACCEPTABLE, desc = "Both updates.") +@State +public class MyCounterJCStressUnitTest { + + private MyCounter counter; + + @Actor + public void actor1() { + counter.increment(); + } + + @Actor + public void actor2() { + counter.increment(); + } + + @Arbiter + public void arbiter(I_Result r) { + r.r1 = counter.getCount(); + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java new file mode 100644 index 0000000000..eb4e77cae9 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.concurrent; + +import org.junit.Test; + +import edu.umd.cs.mtc.MultithreadedTestCase; +import edu.umd.cs.mtc.TestFramework; + +public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase { + + private MyCounter counter; + + @Override + public void initialize() { + counter = new MyCounter(); + } + + public void thread1() throws InterruptedException { + counter.increment(); + } + + public void thread2() throws InterruptedException { + counter.increment(); + } + + @SuppressWarnings("deprecation") + @Override + public void finish() { + assertEquals(2, counter.getCount()); + } + + @Test + public void testCounter() throws Throwable { + TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000); + } +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java new file mode 100644 index 0000000000..4f3409b923 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.Test; + +public class MyCounterSimpleUnitTest { + + @Test + public void testCounter() { + MyCounter counter = new MyCounter(); + for (int i = 0; i < 500; i++) + counter.increment(); + assertEquals(500, counter.getCount()); + } + + // @Test + public void testCounterWithConcurrency() throws InterruptedException { + int numberOfThreads = 100; + ExecutorService service = Executors.newFixedThreadPool(10); + CountDownLatch latch = new CountDownLatch(numberOfThreads); + MyCounter counter = new MyCounter(); + for (int i = 0; i < numberOfThreads; i++) { + service.execute(() -> { + counter.increment(); + latch.countDown(); + }); + } + latch.await(); + assertEquals(numberOfThreads, counter.getCount()); + } + + // @Test + public void testSummationWithConcurrencyAndWait() throws InterruptedException { + int numberOfThreads = 2; + ExecutorService service = Executors.newFixedThreadPool(10); + CountDownLatch latch = new CountDownLatch(numberOfThreads); + MyCounter counter = new MyCounter(); + for (int i = 0; i < numberOfThreads; i++) { + service.submit(() -> { + try { + counter.incrementWithWait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + latch.countDown(); + }); + } + latch.await(); + assertEquals(numberOfThreads, counter.getCount()); + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java new file mode 100644 index 0000000000..360c61b4f4 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.Rule; +import org.junit.Test; + +import com.google.code.tempusfugit.concurrency.ConcurrentRule; +import com.google.code.tempusfugit.concurrency.RepeatingRule; +import com.google.code.tempusfugit.concurrency.annotations.Concurrent; +import com.google.code.tempusfugit.concurrency.annotations.Repeating; + +public class MyCounterTempusFugitUnitTest { + + @Rule + public ConcurrentRule concurrently = new ConcurrentRule(); + @Rule + public RepeatingRule rule = new RepeatingRule(); + + private static MyCounter counter = new MyCounter(); + + @Test + @Concurrent(count = 2) + @Repeating(repetition = 10) + public void runsMultipleTimes() { + counter.increment(); + } + + @AfterClass + public static void annotatedTestRunsMultipleTimes() throws InterruptedException { + assertEquals(counter.getCount(), 20); + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java new file mode 100644 index 0000000000..29b08996cd --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.google.testing.threadtester.AnnotatedTestRunner; +import com.google.testing.threadtester.ThreadedAfter; +import com.google.testing.threadtester.ThreadedBefore; +import com.google.testing.threadtester.ThreadedMain; +import com.google.testing.threadtester.ThreadedSecondary; + +public class MyCounterThreadWeaverUnitTest { + + private MyCounter counter; + + @ThreadedBefore + public void before() { + counter = new MyCounter(); + } + + @ThreadedMain + public void mainThread() { + counter.increment(); + } + + @ThreadedSecondary + public void secondThread() { + counter.increment(); + } + + @ThreadedAfter + public void after() { + assertEquals(2, counter.getCount()); + } + + @Test + public void testCounter() { + new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore b/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations-2/README.md b/core-java-modules/core-java-date-operations-2/README.md index 728162ca1a..19c7b98d30 100644 --- a/core-java-modules/core-java-date-operations-2/README.md +++ b/core-java-modules/core-java-date-operations-2/README.md @@ -7,4 +7,5 @@ This module contains articles about date operations in Java. - [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day) - [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime) - [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone) +- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week) - [[<-- Prev]](/core-java-modules/core-java-date-operations-1) diff --git a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractor.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractor.java new file mode 100644 index 0000000000..b027790e35 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractor.java @@ -0,0 +1,35 @@ +package com.baeldung.datetime.dayofweek; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.format.TextStyle; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +public class DayOfWeekExtractor { + + public static int getDayNumberOld(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal.get(Calendar.DAY_OF_WEEK); + } + + public static String getDayStringOld(Date date, Locale locale ) { + DateFormat formatter = new SimpleDateFormat("EEEE", locale); + return formatter.format(date); + } + + public static int getDayNumberNew(LocalDate date) { + DayOfWeek day = date.getDayOfWeek(); + return day.getValue(); + } + + public static String getDayStringNew(LocalDate date, Locale locale ) { + DayOfWeek day = date.getDayOfWeek(); + return day.getDisplayName(TextStyle.FULL, locale); + } + +} diff --git a/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractorUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractorUnitTest.java new file mode 100644 index 0000000000..0dfd50dca2 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/datetime/dayofweek/DayOfWeekExtractorUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.datetime.dayofweek; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Locale; + +import org.junit.Test; + +public class DayOfWeekExtractorUnitTest { + + private DateFormat oldDateParser = new SimpleDateFormat("yyyy-MM-dd"); + + @Test + public void givenFeb29_2020_thenOldSaturdayNumber() throws ParseException { + assertThat(DayOfWeekExtractor.getDayNumberOld(oldDateParser.parse("2020-02-29")) == Calendar.SATURDAY); + } + + @Test + public void givenFeb29_2020_and_localeUS_thenOldSaturdayText() throws ParseException { + assertThat("Saturday".equals(DayOfWeekExtractor.getDayStringOld(oldDateParser.parse("2020-02-29"), Locale.US)) ); + } + + @Test + public void givenFeb29_2020_and_localeDE_thenOldSaturdayText() throws ParseException { + assertThat("Samstag".equals(DayOfWeekExtractor.getDayStringOld(oldDateParser.parse("2020-02-29"), Locale.GERMANY)) ); + } + + @Test + public void givenFeb29_2020_thenNewSaturdayNumber() throws ParseException { + assertThat(DayOfWeekExtractor.getDayNumberNew(LocalDate.parse("2020-02-29")) == Calendar.SATURDAY); + } + + @Test + public void givenFeb29_2020_and_localeUS_thenNewSaturdayText() throws ParseException { + assertThat("Saturday".equals(DayOfWeekExtractor.getDayStringOld(oldDateParser.parse("2020-02-29"), Locale.US)) ); + } + + @Test + public void givenFeb29_2020_and_localeDE_thenNewSaturdayText() throws ParseException { + assertThat("Samstag".equals(DayOfWeekExtractor.getDayStringOld(oldDateParser.parse("2020-02-29"), Locale.GERMANY)) ); + } + + +} + + + diff --git a/core-java-modules/core-java-datetime-java8-2/README.md b/core-java-modules/core-java-datetime-java8-2/README.md deleted file mode 100644 index e53d0236c2..0000000000 --- a/core-java-modules/core-java-datetime-java8-2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values) diff --git a/core-java-modules/core-java-io-2/README.md b/core-java-modules/core-java-io-2/README.md index 62461be0ff..84cabc5992 100644 --- a/core-java-modules/core-java-io-2/README.md +++ b/core-java-modules/core-java-io-2/README.md @@ -12,4 +12,5 @@ This module contains articles about core Java input and output (IO) - [Java – Append Data to a File](https://www.baeldung.com/java-append-to-file) - [How to Copy a File with Java](https://www.baeldung.com/java-copy-file) - [Create a Directory in Java](https://www.baeldung.com/java-create-directory) +- [Java IO vs NIO](https://www.baeldung.com/java-io-vs-nio) - [[<-- Prev]](/core-java-modules/core-java-io) diff --git a/core-java-modules/core-java-io-conversions-2/README.md b/core-java-modules/core-java-io-conversions-2/README.md new file mode 100644 index 0000000000..4a28bf37c5 --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/README.md @@ -0,0 +1,9 @@ +## Core Java IO Conversions (Part 2) + +This module contains articles about core Java input/output(IO) conversions. + +### Relevant Articles: +- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string) +- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) +- [Java – Write an InputStream to a File](https://www.baeldung.com/convert-input-stream-to-a-file) +- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions) diff --git a/core-java-modules/core-java-arrays-3/pom.xml b/core-java-modules/core-java-io-conversions-2/pom.xml similarity index 55% rename from core-java-modules/core-java-arrays-3/pom.xml rename to core-java-modules/core-java-io-conversions-2/pom.xml index 210375b878..e95d1f4b67 100644 --- a/core-java-modules/core-java-arrays-3/pom.xml +++ b/core-java-modules/core-java-io-conversions-2/pom.xml @@ -4,9 +4,9 @@ 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 - core-java-arrays-3 + core-java-io-conversions-2 0.1.0-SNAPSHOT - core-java-arrays-3 + core-java-io-conversions-2 jar @@ -18,15 +18,20 @@ - org.assertj - assertj-core - ${assertj.version} - test + org.apache.commons + commons-lang3 + ${commons-lang3.version} - - 3.14.0 - + + core-java-io-conversions + + + src/main/resources + true + + + \ No newline at end of file diff --git a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java rename to core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java diff --git a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java rename to core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java diff --git a/core-java-modules/core-java-io-conversions/src/test/resources/targetFile.tmp b/core-java-modules/core-java-io-conversions-2/src/test/resources/sample.txt similarity index 100% rename from core-java-modules/core-java-io-conversions/src/test/resources/targetFile.tmp rename to core-java-modules/core-java-io-conversions-2/src/test/resources/sample.txt diff --git a/core-java-modules/core-java-io-conversions-2/src/test/resources/targetFile.tmp b/core-java-modules/core-java-io-conversions-2/src/test/resources/targetFile.tmp new file mode 100644 index 0000000000..5e1c309dae --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/src/test/resources/targetFile.tmp @@ -0,0 +1 @@ +Hello World \ No newline at end of file diff --git a/core-java-modules/core-java-io-conversions/README.md b/core-java-modules/core-java-io-conversions/README.md index cdb7df04d0..1f12c87241 100644 --- a/core-java-modules/core-java-io-conversions/README.md +++ b/core-java-modules/core-java-io-conversions/README.md @@ -3,10 +3,8 @@ This module contains articles about core Java input/output(IO) conversions. ### Relevant Articles: -- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string) - [Java – Convert File to InputStream](https://www.baeldung.com/convert-file-to-input-stream) - [Java – Byte Array to Writer](https://www.baeldung.com/java-convert-byte-array-to-writer) -- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) - [Java – String to Reader](https://www.baeldung.com/java-convert-string-to-reader) - [Java – Byte Array to Reader](https://www.baeldung.com/java-convert-byte-array-to-reader) - [Java – File to Reader](https://www.baeldung.com/java-convert-file-to-reader) @@ -15,3 +13,4 @@ This module contains articles about core Java input/output(IO) conversions. - [Java – Write a Reader to File](https://www.baeldung.com/java-write-reader-to-file) - [Java – Reader to Byte Array](https://www.baeldung.com/java-convert-reader-to-byte-array) - [Java – Reader to InputStream](https://www.baeldung.com/java-convert-reader-to-inputstream) +- More articles: [[next -->]](/core-java-modules/core-java-io-conversions-2) diff --git a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index 57d9d8347b..9e510575fc 100644 --- a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -1,18 +1,17 @@ package com.baeldung.java8; -import static org.hamcrest.Matchers.equalTo; +import com.baeldung.java8.entity.Human; +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; +import org.junit.Assert; +import org.junit.Test; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -import org.junit.Assert; -import org.junit.Test; - -import com.baeldung.java8.entity.Human; -import com.google.common.collect.Lists; -import com.google.common.primitives.Ints; +import static org.hamcrest.Matchers.equalTo; public class Java8SortUnitTest { @@ -113,11 +112,11 @@ public class Java8SortUnitTest { humans.sort(Comparator.comparing(Human::getName)); Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12))); } - + @Test public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { final List letters = Lists.newArrayList("B", "A", "C"); - + final List sortedLetters = letters.stream().sorted().collect(Collectors.toList()); Assert.assertThat(sortedLetters.get(0), equalTo("A")); } @@ -126,7 +125,7 @@ public class Java8SortUnitTest { public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); final Comparator nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName()); - + final List sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList()); Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12))); } @@ -164,4 +163,48 @@ public class Java8SortUnitTest { Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10))); } + @Test(expected = NullPointerException.class) + public final void givenANullElement_whenSortingEntitiesByName_thenThrowsNPE() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12)); + + humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName())); + } + + @Test + public final void givenANullElement_whenSortingEntitiesByNameManually_thenMovesTheNullToLast() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12), null); + + humans.sort((h1, h2) -> { + if (h1 == null) return h2 == null ? 0 : 1; + else if (h2 == null) return -1; + + return h1.getName().compareTo(h2.getName()); + }); + + Assert.assertNotNull(humans.get(0)); + Assert.assertNull(humans.get(1)); + Assert.assertNull(humans.get(2)); + } + + @Test + public final void givenANullElement_whenSortingEntitiesByName_thenMovesTheNullToLast() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12), null); + + humans.sort(Comparator.nullsLast(Comparator.comparing(Human::getName))); + + Assert.assertNotNull(humans.get(0)); + Assert.assertNull(humans.get(1)); + Assert.assertNull(humans.get(2)); + } + + @Test + public final void givenANullElement_whenSortingEntitiesByName_thenMovesTheNullToStart() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12), null); + + humans.sort(Comparator.nullsFirst(Comparator.comparing(Human::getName))); + + Assert.assertNull(humans.get(0)); + Assert.assertNull(humans.get(1)); + Assert.assertNotNull(humans.get(2)); + } } diff --git a/core-java-modules/core-java-lang-2/README.md b/core-java-modules/core-java-lang-2/README.md index 65d40c6a26..3ade982397 100644 --- a/core-java-modules/core-java-lang-2/README.md +++ b/core-java-modules/core-java-lang-2/README.md @@ -10,4 +10,5 @@ This module contains articles about core features in the Java language - [How to Return Multiple Values From a Java Method](https://www.baeldung.com/java-method-return-multiple-values) - [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword) - [The Java Headless Mode](https://www.baeldung.com/java-headless-mode) +- [Comparing Long Values in Java](https://www.baeldung.com/java-compare-long-values) - [[<-- Prev]](/core-java-modules/core-java-lang) diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java new file mode 100644 index 0000000000..a26b0a74b0 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.comparelong; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import org.junit.Test; + +import java.util.Objects; + +public class CompareLongUnitTest { + + @Test + public void givenLongValuesLessThan128_whenUsingReferenceComparater_thenSuccess() { + + Long l1 = 127L; + Long l2 = 127L; + + assertThat(l1 == l2).isTrue(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingReferenceComparater_thenFails() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(l1 == l2).isFalse(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingEquals_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(l1.equals(l2)).isTrue(); + } + + @Test + public void givenLongValuesLessThan128_whenUsingObjectsEquals_thenSuccess() { + + Long l1 = 127L; + Long l2 = 127L; + + assertThat(Objects.equals(l1, l2)).isTrue(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingObjectsEquals_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(Objects.equals(l1, l2)).isTrue(); + } + + @Test + public void givenNullReference_whenUsingObjectsEquals_thenNoException() { + + Long l1 = null; + Long l2 = 128L; + + assertThatCode(() -> Objects.equals(l1, l2)).doesNotThrowAnyException(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingComparisonOperator_andLongValue_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(l1.longValue() == l2.longValue()).isTrue(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingCasting_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat((long) l1 == (long) l2).isTrue(); + } + +} \ No newline at end of file diff --git a/java-math/.gitignore b/core-java-modules/core-java-lang-math-2/.gitignore similarity index 100% rename from java-math/.gitignore rename to core-java-modules/core-java-lang-math-2/.gitignore diff --git a/java-math/README.md b/core-java-modules/core-java-lang-math-2/README.md similarity index 73% rename from java-math/README.md rename to core-java-modules/core-java-lang-math-2/README.md index d80a07258a..09039f6ed0 100644 --- a/java-math/README.md +++ b/core-java-modules/core-java-lang-math-2/README.md @@ -1,6 +1,6 @@ -## Java Math +========= -This module contains articles about math in Java. +## Core Java 8 Cookbooks and Examples - Part 2 ### Relevant articles: @@ -10,9 +10,7 @@ This module contains articles about math in Java. - [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points) - [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines) - [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred) -- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage) - [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude) - [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging) - [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication) -- [Calculating Logarithms in Java](https://www.baeldung.com/java-logarithms) -- [Finding Greatest Common Divisor in Java](https://www.baeldung.com/java-greatest-common-divisor) +- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math) diff --git a/java-math/pom.xml b/core-java-modules/core-java-lang-math-2/pom.xml similarity index 92% rename from java-math/pom.xml rename to core-java-modules/core-java-lang-math-2/pom.xml index 9b4af4c13d..92ebcc6a94 100644 --- a/java-math/pom.xml +++ b/core-java-modules/core-java-lang-math-2/pom.xml @@ -2,14 +2,15 @@ 4.0.0 - java-math + core-java-lang-math-2 0.0.1-SNAPSHOT - java-math + core-java-lang-math-2 com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../../parent-java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/factorial/Factorial.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/factorial/Factorial.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/factorial/Factorial.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/factorial/Factorial.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/mercator/Mercator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/Mercator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/mercator/Mercator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/Mercator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java diff --git a/java-math/src/main/java/com/baeldung/matrices/HomemadeMatrix.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/HomemadeMatrix.java similarity index 100% rename from java-math/src/main/java/com/baeldung/matrices/HomemadeMatrix.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/HomemadeMatrix.java diff --git a/java-math/src/main/java/com/baeldung/matrices/benchmark/BigMatrixMultiplicationBenchmarking.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/BigMatrixMultiplicationBenchmarking.java similarity index 100% rename from java-math/src/main/java/com/baeldung/matrices/benchmark/BigMatrixMultiplicationBenchmarking.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/BigMatrixMultiplicationBenchmarking.java diff --git a/java-math/src/main/java/com/baeldung/matrices/benchmark/BigMatrixProvider.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/BigMatrixProvider.java similarity index 100% rename from java-math/src/main/java/com/baeldung/matrices/benchmark/BigMatrixProvider.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/BigMatrixProvider.java diff --git a/java-math/src/main/java/com/baeldung/matrices/benchmark/MatrixMultiplicationBenchmarking.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/MatrixMultiplicationBenchmarking.java similarity index 100% rename from java-math/src/main/java/com/baeldung/matrices/benchmark/MatrixMultiplicationBenchmarking.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/MatrixMultiplicationBenchmarking.java diff --git a/java-math/src/main/java/com/baeldung/matrices/benchmark/MatrixProvider.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/MatrixProvider.java similarity index 100% rename from java-math/src/main/java/com/baeldung/matrices/benchmark/MatrixProvider.java rename to core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/matrices/benchmark/MatrixProvider.java diff --git a/core-java-modules/core-java-lang-math-2/src/main/resources/logback.xml b/core-java-modules/core-java-lang-math-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-modules/core-java-lang-math-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/java-math/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java rename to core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java diff --git a/core-java-modules/core-java-lang-math/README.md b/core-java-modules/core-java-lang-math/README.md index ec97a2ada4..9295349f82 100644 --- a/core-java-modules/core-java-lang-math/README.md +++ b/core-java-modules/core-java-lang-math/README.md @@ -10,3 +10,7 @@ - [Basic Calculator in Java](https://www.baeldung.com/java-basic-calculator) - [Overflow and Underflow in Java](https://www.baeldung.com/java-overflow-underflow) - [Obtaining a Power Set of a Set in Java](https://www.baeldung.com/java-power-set-of-a-set) +- [Calculating Logarithms in Java](https://www.baeldung.com/java-logarithms) +- [Finding Greatest Common Divisor in Java](https://www.baeldung.com/java-greatest-common-divisor) +- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage) +- More articles: [[Next -->]](/core-java-modules/core-java-lang-math-2) diff --git a/java-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java rename to core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/gcd/GCDImplementation.java diff --git a/java-math/src/main/java/com/baeldung/algorithms/percentage/PercentageCalculator.java b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/PercentageCalculator.java similarity index 100% rename from java-math/src/main/java/com/baeldung/algorithms/percentage/PercentageCalculator.java rename to core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/PercentageCalculator.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java rename to core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/gcd/GCDImplementationUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/logarithm/LogarithmUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/logarithm/LogarithmUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/logarithm/LogarithmUnitTest.java rename to core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/logarithm/LogarithmUnitTest.java diff --git a/java-math/src/test/java/com/baeldung/algorithms/percentage/PercentageCalculatorUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/percentage/PercentageCalculatorUnitTest.java similarity index 100% rename from java-math/src/test/java/com/baeldung/algorithms/percentage/PercentageCalculatorUnitTest.java rename to core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/percentage/PercentageCalculatorUnitTest.java 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 035d464c50..c48a3f5cd9 100644 --- a/core-java-modules/core-java-lang-oop-2/README.md +++ b/core-java-modules/core-java-lang-oop-2/README.md @@ -12,7 +12,6 @@ This module contains articles about Object-oriented programming (OOP) in Java - [Immutable Objects in Java](https://www.baeldung.com/java-immutable-object) - [Inheritance and Composition (Is-a vs Has-a relationship) in Java](https://www.baeldung.com/java-inheritance-composition) - [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors) -- [Composition, Aggregation, and Association in Java](https://www.baeldung.com/java-composition-aggregation-association) - [Static and Default Methods in Interfaces in Java](https://www.baeldung.com/java-static-default-methods) - [Java Copy Constructor](https://www.baeldung.com/java-copy-constructor) - [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class) diff --git a/core-java-modules/core-java-lang-syntax/README.md b/core-java-modules/core-java-lang-syntax/README.md index bef03b98ad..f74fa1b546 100644 --- a/core-java-modules/core-java-lang-syntax/README.md +++ b/core-java-modules/core-java-lang-syntax/README.md @@ -5,12 +5,9 @@ This module contains articles about Java syntax ### Relevant Articles: - [The Basics of Java Generics](https://www.baeldung.com/java-generics) - [Java Primitive Conversions](https://www.baeldung.com/java-primitive-conversions) -- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break) - [A Guide to Creating Objects in Java](https://www.baeldung.com/java-initialization) - [A Guide to Java Loops](https://www.baeldung.com/java-loops) - [Varargs in Java](https://www.baeldung.com/java-varargs) -- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums) -- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java) - [Java Switch Statement](https://www.baeldung.com/java-switch) - [Breaking Out of Nested Loops](https://www.baeldung.com/java-breaking-out-nested-loop) - [Java Do-While Loop](https://www.baeldung.com/java-do-while-loop) diff --git a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/connectexception/ConnectionChecker.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/connectexception/ConnectionChecker.java new file mode 100644 index 0000000000..360fb6ecaa --- /dev/null +++ b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/connectexception/ConnectionChecker.java @@ -0,0 +1,24 @@ +package com.baeldung.connectexception; + +import java.net.ConnectException; +import java.net.Socket; + +public class ConnectionChecker { + public static void main(String[] args) { + String host = "localhost"; + int port = 5000; + + try { + Socket clientSocket = new Socket(host, port); + + // successfully connected to host, do something with opened socket + + clientSocket.close(); + } catch (ConnectException e) { + // host and port combination not valid + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java new file mode 100644 index 0000000000..480dc782e4 --- /dev/null +++ b/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java @@ -0,0 +1,21 @@ +package com.baeldung.orelseoptional; + +import java.util.Optional; + +public class ItemsProvider { + + Optional getEmptyItem() { + System.out.println("Returning an empty item"); + return Optional.empty(); + } + + Optional getNail() { + System.out.println("Returning a nail"); + return Optional.of("nail"); + } + + Optional getHammer() { + System.out.println("Returning a hammer"); + return Optional.of("hammer"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java b/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java index e5c4319bf7..de16e9b635 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java +++ b/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java @@ -86,6 +86,15 @@ public class OptionalUnitTest { Optional opt = Optional.ofNullable(null); String name = opt.get(); } + + @Test + public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() { + Optional opt = Optional.of("Baeldung"); + assertTrue(opt.isPresent()); + + opt = Optional.ofNullable(null); + assertFalse(opt.isPresent()); + } // Conditional Return With filter() @Test diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java b/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java index 91aebbeebd..e3bdedcd82 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java +++ b/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java @@ -1,10 +1,10 @@ package com.baeldung.orelseoptional; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.util.Optional; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class OrElseOptionalUnitTest { @@ -25,6 +25,28 @@ public class OrElseOptionalUnitTest { assertEquals(fallbackOptionalString, OptionalUtils.or(optionalString, fallbackOptionalString)); } + @Test + public void givenTwoOptionalMethods_whenFirstEmpty_thenSecondEvaluated() { + ItemsProvider itemsProvider = new ItemsProvider(); + + Optional item = itemsProvider.getEmptyItem() + .map(Optional::of) + .orElseGet(itemsProvider::getNail); + + assertEquals(Optional.of("nail"), item); + } + + @Test + public void givenTwoOptionalMethods_whenFirstNonEmpty_thenSecondNotEvaluated() { + ItemsProvider itemsProvider = new ItemsProvider(); + + Optional item = itemsProvider.getNail() + .map(Optional::of) + .orElseGet(itemsProvider::getHammer); + + assertEquals(Optional.of("nail"), item); + } + // Uncomment code when code base is compatible with Java 9 // @Test // public void givenOptional_whenEmptyValue_thenCustomMessage() { diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java index 21044f82c4..e2a60ac384 100644 --- a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java +++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java @@ -3,7 +3,12 @@ package com.baeldung.jmx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.management.*; +import javax.management.InstanceAlreadyExistsException; +import javax.management.MBeanRegistrationException; +import javax.management.MBeanServer; +import javax.management.MalformedObjectNameException; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; import java.lang.management.ManagementFactory; public class JMXTutorialMainlauncher { @@ -11,24 +16,21 @@ public class JMXTutorialMainlauncher { private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); public static void main(String[] args) { - // TODO Auto-generated method stub LOG.debug("This is basic JMX tutorial"); - ObjectName objectName = null; + try { - objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); - } catch (MalformedObjectNameException e) { - e.printStackTrace(); - } - MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - Game gameObj = new Game(); - try { - server.registerMBean(gameObj, objectName); - } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { + ObjectName objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + server.registerMBean(new Game(), objectName); + } catch (MalformedObjectNameException | InstanceAlreadyExistsException | + MBeanRegistrationException | NotCompliantMBeanException e) { e.printStackTrace(); } + LOG.debug("Registration for Game mbean with the platform server is successfull"); LOG.debug("Please open jconsole to access Game mbean"); + while (true) { // to ensure application does not terminate } diff --git a/core-java-modules/core-java-regex/README.md b/core-java-modules/core-java-regex/README.md index 21cd7a95a3..6fdea9f2ca 100644 --- a/core-java-modules/core-java-regex/README.md +++ b/core-java-modules/core-java-regex/README.md @@ -9,3 +9,4 @@ - [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile) - [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches) - [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement) +- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus) diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/replaceall/ReplaceAllWithWhitespaceRegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/replaceall/ReplaceAllWithWhitespaceRegexUnitTest.java new file mode 100644 index 0000000000..a95d1afd80 --- /dev/null +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/replaceall/ReplaceAllWithWhitespaceRegexUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.replaceall; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ReplaceAllWithWhitespaceRegexUnitTest { + private static final String INPUT_STR = "Text With Whitespaces! "; + + @Test + public void givenString_whenReplaceBySingleCharClass_thenGetExpect() { + String expected = "Text___With_____Whitespaces!___"; + String result = INPUT_STR.replaceAll("\\s", "_"); + assertEquals(expected, result); + } + + @Test + public void givenString_whenReplaceBySingleCharClassWithPlus_thenGetExpect() { + String expected = "Text_With_Whitespaces!_"; + String result = INPUT_STR.replaceAll("\\s+", "_"); + assertEquals(expected, result); + } + + @Test + public void givenString_whenRemoveByWhitespace_thenGetSameResult() { + String expected = "TextWithWhitespaces!"; + String result1 = INPUT_STR.replaceAll("\\s", ""); + String result2 = INPUT_STR.replaceAll("\\s+", ""); + assertEquals(expected, result1); + assertEquals(result1, result2); + } +} diff --git a/core-java-modules/core-java-security-2/README.md b/core-java-modules/core-java-security-2/README.md index c250e24078..24a821bd4d 100644 --- a/core-java-modules/core-java-security-2/README.md +++ b/core-java-modules/core-java-security-2/README.md @@ -1,3 +1,12 @@ +## Core Java Security + +This module contains articles about core Java Security + ### Relevant Articles: - [Guide To The Java Authentication And Authorization Service (JAAS)](https://www.baeldung.com/java-authentication-authorization-service) +- [MD5 Hashing in Java](http://www.baeldung.com/java-md5) +- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) +- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) +- [Checksums in Java](https://www.baeldung.com/java-checksums) +- More articles: [[<-- prev]](/core-java-modules/core-java-security) diff --git a/core-java-modules/core-java-security-2/pom.xml b/core-java-modules/core-java-security-2/pom.xml index 23f0c5aab9..5db3b67c04 100644 --- a/core-java-modules/core-java-security-2/pom.xml +++ b/core-java-modules/core-java-security-2/pom.xml @@ -16,4 +16,45 @@ ../../parent-java + + + + commons-codec + commons-codec + ${commons-codec.version} + + + + org.bouncycastle + bcprov-jdk15on + ${bouncycastle.version} + + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + javax.xml.bind + jaxb-api + 2.3.1 + + + + + + + + 1.60 + 1.11 + + + 3.10.0 + + diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/checksums/ChecksumUtils.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/checksums/ChecksumUtils.java new file mode 100644 index 0000000000..d214a0f757 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/checksums/ChecksumUtils.java @@ -0,0 +1,23 @@ +package com.baeldung.checksums; + +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.CRC32; +import java.util.zip.CheckedInputStream; +import java.util.zip.Checksum; + +public class ChecksumUtils { + + public static long getChecksumCRC32(byte[] bytes) { + Checksum crc32 = new CRC32(); + crc32.update(bytes, 0, bytes.length); + return crc32.getValue(); + } + + public static long getChecksumCRC32(InputStream stream, int bufferSize) throws IOException { + CheckedInputStream checkedInputStream = new CheckedInputStream(stream, new CRC32()); + byte[] buffer = new byte[bufferSize]; + while (checkedInputStream.read(buffer, 0, buffer.length) >= 0) {} + return checkedInputStream.getChecksum().getValue(); + } +} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/DigestAlgorithms.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/DigestAlgorithms.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/Keccak256Hashing.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/Keccak256Hashing.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA256Hashing.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA256Hashing.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA3Hashing.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA3Hashing.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHACommonUtils.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHACommonUtils.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java rename to core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/checksums/ChecksumUtilsUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/checksums/ChecksumUtilsUnitTest.java new file mode 100644 index 0000000000..f5366917f6 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/checksums/ChecksumUtilsUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.checksums; + + +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.jupiter.api.Assertions.*; + +class ChecksumUtilsUnitTest { + + byte[] arr; + + @Before + void setUp() { + arr = new byte[]{0,10,21,20,35,40,120,56,72,22}; + } + + @Test + void givenByteArray_whenChecksumCreated_checkCorrect() { + + long checksum = ChecksumUtils.getChecksumCRC32(arr); + + assertEquals(3915397664L, checksum); + } + + @Test + void givenTwoDifferentStrings_whenChecksumCreated_checkCollision() { + + String plumless = "plumless"; + String buckeroo = "buckeroo"; + + long plumlessChecksum = ChecksumUtils.getChecksumCRC32(plumless.getBytes()); + long buckerooChecksum = ChecksumUtils.getChecksumCRC32(buckeroo.getBytes()); + + assertEquals(plumlessChecksum, buckerooChecksum); + } + + @Test + void givenInputString_whenChecksumCreated_checkCorrect() throws IOException { + + InputStream inputStream = new ByteArrayInputStream(arr); + long checksum = ChecksumUtils.getChecksumCRC32(inputStream, 10); + + assertEquals(3915397664L, checksum); + + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java rename to core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java diff --git a/core-java-modules/core-java-security/src/test/resources/test_md5.txt b/core-java-modules/core-java-security-2/src/test/resources/test_md5.txt similarity index 100% rename from core-java-modules/core-java-security/src/test/resources/test_md5.txt rename to core-java-modules/core-java-security-2/src/test/resources/test_md5.txt diff --git a/core-java-modules/core-java-security/README.md b/core-java-modules/core-java-security/README.md index ff9b1eef14..83b12793b5 100644 --- a/core-java-modules/core-java-security/README.md +++ b/core-java-modules/core-java-security/README.md @@ -3,17 +3,16 @@ This module contains articles about core Java Security ### Relevant Articles: -- [MD5 Hashing in Java](http://www.baeldung.com/java-md5) + - [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class) - [Introduction to SSL in Java](http://www.baeldung.com/java-ssl) - [Java KeyStore API](http://www.baeldung.com/java-keystore) - [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream) -- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures) -- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) - [Enabling TLS v1.2 in Java 7](https://www.baeldung.com/java-7-tls-v12) - [The Java SecureRandom Class](https://www.baeldung.com/java-secure-random) - [An Introduction to Java SASL](https://www.baeldung.com/java-sasl) - [A Guide to Java GSS API](https://www.baeldung.com/java-gss) - [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager) +- More articles: [[next -->]](/core-java-modules/core-java-security-2) diff --git a/core-java-modules/core-java-security/pom.xml b/core-java-modules/core-java-security/pom.xml index a46c2e2d40..96024a73a1 100644 --- a/core-java-modules/core-java-security/pom.xml +++ b/core-java-modules/core-java-security/pom.xml @@ -24,24 +24,9 @@ ${assertj-core.version} test - - - commons-codec - commons-codec - ${commons-codec.version} - - - org.bouncycastle - bcprov-jdk15on - ${bouncycastle.version} - - - 1.60 - 1.11 - 3.10.0 diff --git a/core-java-modules/core-java-streams-3/README.md b/core-java-modules/core-java-streams-3/README.md index a739245399..05c4b99900 100644 --- a/core-java-modules/core-java-streams-3/README.md +++ b/core-java-modules/core-java-streams-3/README.md @@ -9,4 +9,5 @@ This module contains articles about the Stream API in Java. - [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors) - [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) - [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams) +- [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals) - More articles: [[<-- prev>]](/../core-java-streams-2) diff --git a/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/closure/StreamClosureSnippets.java b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/closure/StreamClosureSnippets.java new file mode 100644 index 0000000000..10e5716e31 --- /dev/null +++ b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/closure/StreamClosureSnippets.java @@ -0,0 +1,30 @@ +package com.baeldung.streams.closure; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.stream.Stream; + +/** + * Contains a couple of simple stream API usages. + */ +public class StreamClosureSnippets { + + public static void main(String[] args) throws IOException { + // Collection based streams shouldn't be closed + Arrays.asList("Red", "Blue", "Green") + .stream() + .filter(c -> c.length() > 4) + .map(String::toUpperCase) + .forEach(System.out::print); + + String[] colors = {"Red", "Blue", "Green"}; + Arrays.stream(colors).map(String::toUpperCase).forEach(System.out::println); + + // IO-Based Streams Should be Closed via Try with Resources + try (Stream lines = Files.lines(Paths.get("/path/tp/file"))) { + // lines will be closed after exiting the try block + } + } +} diff --git a/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/bigdecimals/AddNumbersUnitTest.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/bigdecimals/AddNumbersUnitTest.java new file mode 100644 index 0000000000..9399908b30 --- /dev/null +++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/bigdecimals/AddNumbersUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.streams.bigdecimals; + +import static org.junit.Assert.assertEquals; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.junit.Test; + +public class AddNumbersUnitTest { + + @Test + public void givenIntStream_whenSum_thenResultIsCorrect() { + IntStream intNumbers = IntStream.range(0, 3); + assertEquals(3, intNumbers.sum()); + } + + @Test + public void givenCollectionOfDouble_whenUsingMapToDoubleToSum_thenResultIsCorrect() { + List doubleNumbers = Arrays.asList(23.48, 52.26, 13.5); + double result = doubleNumbers.stream() + .mapToDouble(Double::doubleValue) + .sum(); + assertEquals(89.24, result, .1); + } + + public void givenStreamOfIntegers_whenUsingReduceToSum_thenResultIsCorrect() { + Stream intNumbers = Stream.of(0, 1, 2); + int result = intNumbers.reduce(0, Integer::sum); + assertEquals(106, result); + } + + public void givenStreamOfBigDecimals_whenUsingReduceToSum_thenResultIsCorrect() { + Stream bigDecimalNumber = Stream.of(BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN); + BigDecimal result = bigDecimalNumber.reduce(BigDecimal.ZERO, BigDecimal::add); + assertEquals(11, result); + } + +} diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md index 5e92738f5c..2f54aa9467 100644 --- a/core-java-modules/core-java-string-operations-2/README.md +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -9,6 +9,7 @@ This module contains articles about string operations. - [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case) - [Java String equalsIgnoreCase()](https://www.baeldung.com/java-string-equalsignorecase) - [Case-Insensitive String Matching in Java](https://www.baeldung.com/java-case-insensitive-string-matching) -- [L-Trim and R-Trim in Java](https://www.baeldung.com/l-trim-and-r-trim-in-java) - [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives) +- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) +- [Encode a String to UTF-8 in Java](https://www.baeldung.com/java-string-encode-utf-8) - More articles: [[<-- prev]](../core-java-string-operations) diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index 079556712e..a00ae80f13 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -64,6 +64,11 @@ jmh-generator-annprocess ${jmh-generator.version} + + commons-codec + commons-codec + ${commons-codec.version} + org.assertj @@ -113,6 +118,7 @@ 6.0.2.Final 3.0.0 2.2.6 + 1.14 diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encodetoutf8/StringEncodeUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encodetoutf8/StringEncodeUnitTest.java new file mode 100644 index 0000000000..a73104b234 --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encodetoutf8/StringEncodeUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.encodetoutf8; + +import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.codec.binary.StringUtils; +import org.junit.Test; + +public class StringEncodeUnitTest { + + @Test + public void givenGermanAsciiString_whenComparing_thenCompareNotEquals() { + String germanString = "Entwickeln Sie mit Vergnügen"; + byte[] germanBytes = germanString.getBytes(); + + String asciiEncodedString = new String(germanBytes, StandardCharsets.US_ASCII); + + assertNotEquals(germanString, asciiEncodedString); + } + + @Test + public void givenUsAsciiString_whenComparing_thenCompareNotEquals() { + String englishString = "Develop with pleasure"; + byte[] englishBytes = englishString.getBytes(); + + String asciiEncondedEnglishString = new String(englishBytes, StandardCharsets.US_ASCII); + + assertEquals(englishString, asciiEncondedEnglishString); + } + + /* + * ApacheCommonsCodecEncode + */ + @Test + public void givenSomeUnencodedString_whenApacheCommonsCodecEncode_thenCompareEquals() { + String rawString = "Entwickeln Sie mit Vergnügen"; + byte[] bytes = StringUtils.getBytesUtf8(rawString); + + String utf8EncodedString = StringUtils.newStringUtf8(bytes); + + assertEquals(rawString, utf8EncodedString); + } + + /* + * CoreJavaEncode + */ + @Test + public void givenSomeUnencodedString_whenCoreJavaEncode_thenCompareEquals() { + String rawString = "Entwickeln Sie mit Vergnügen"; + byte[] bytes = rawString.getBytes(StandardCharsets.UTF_8); + + String utf8EncodedString = new String(bytes, StandardCharsets.UTF_8); + + assertEquals(rawString, utf8EncodedString); + } + + /* + * Java7StandardCharsetsEncode + */ + @Test + public void givenSomeUnencodedString_whenJava7StandardCharsetsEncode_thenCompareEquals() { + String rawString = "Entwickeln Sie mit Vergnügen"; + ByteBuffer buffer = StandardCharsets.UTF_8.encode(rawString); + + String utf8EncodedString = StandardCharsets.UTF_8.decode(buffer) + .toString(); + + assertEquals(rawString, utf8EncodedString); + } +} diff --git a/pdf/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java similarity index 100% rename from pdf/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java diff --git a/pdf/src/test/resources/input.pdf b/core-java-modules/core-java-string-operations-2/src/test/resources/input.pdf similarity index 100% rename from pdf/src/test/resources/input.pdf rename to core-java-modules/core-java-string-operations-2/src/test/resources/input.pdf diff --git a/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java index f701ab2e45..dd8b3a420d 100644 --- a/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java @@ -38,6 +38,11 @@ public class AddingNewLineToString { System.out.println("6. Using System.getProperty(\"line.separator\")"); rhyme = line1 + System.getProperty("line.separator") + line2; System.out.println(rhyme); + + //7. Using %n + System.out.println("7. Using %n"); + rhyme = "Humpty Dumpty sat on a wall.%nHumpty Dumpty had a great fall."; + System.out.println(rhyme); System.out.println("***HTML to rendered in a browser***"); //1. Line break for HTML using
diff --git a/core-java-modules/core-java-strings/README.md b/core-java-modules/core-java-strings/README.md index 4a418db29f..5daae8394a 100644 --- a/core-java-modules/core-java-strings/README.md +++ b/core-java-modules/core-java-strings/README.md @@ -12,3 +12,4 @@ This module contains articles about strings in Java. - [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) - [Java Multi-line String](https://www.baeldung.com/java-multiline-string) - [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) +- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error) diff --git a/core-java-modules/core-java-strings/src/main/resources/config.properties b/core-java-modules/core-java-strings/src/main/resources/config.properties new file mode 100644 index 0000000000..8197c13543 --- /dev/null +++ b/core-java-modules/core-java-strings/src/main/resources/config.properties @@ -0,0 +1 @@ +string.too.long= StringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLong diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringtoolong/StringTooLongUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringtoolong/StringTooLongUnitTest.java new file mode 100644 index 0000000000..4035cadb83 --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringtoolong/StringTooLongUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.stringtoolong; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.commons.io.IOUtils; +import org.junit.Test; + +public class StringTooLongUnitTest { + @Test + public void whenDeclaringTooLongString_thenCompilationError() { + String stringTooLong = ""; + assertThat(stringTooLong).isNotEmpty(); + } + + @Test + public void whenStoringInFileTooLongString_thenNoCompilationError() throws IOException { + FileInputStream fis = new FileInputStream("src/test/resources/stringtoolong.txt"); + String stringTooLong = IOUtils.toString(fis, "UTF-8"); + assertThat(stringTooLong).isNotEmpty(); + } + + @Test + public void whenStoringInPropertiesString_thenNoCompilationError() throws IOException { + String sValue = null; + try (InputStream input = new FileInputStream("src/main/resources/config.properties")) { + Properties prop = new Properties(); + prop.load(input); + sValue = prop.getProperty("string.too.long"); + } + assertThat(sValue).isNotEmpty(); + } +} + \ No newline at end of file diff --git a/core-java-modules/core-java-strings/src/test/resources/stringtoolong.txt b/core-java-modules/core-java-strings/src/test/resources/stringtoolong.txt new file mode 100644 index 0000000000..6b2649aaa8 --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/resources/stringtoolong.txt @@ -0,0 +1 @@ + StringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLongStringTooLong \ No newline at end of file diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Borrower.java b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Borrower.java new file mode 100644 index 0000000000..62062aa7fc --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Borrower.java @@ -0,0 +1,23 @@ +package com.baeldung.objectclass; + +import lombok.Data; + +@Data +public class Borrower extends User { + + private double totalLoanAmount; + + public double requestLoan(double amount) { + totalLoanAmount = amount; + return totalLoanAmount; + } + + public double increaseLoan(double increaseBy) { + return totalLoanAmount + increaseBy; + } + + public double payLoan(double amount) { + return totalLoanAmount - amount; + } + +} diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Lender.java b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Lender.java new file mode 100644 index 0000000000..b45272cbb1 --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/Lender.java @@ -0,0 +1,20 @@ +package com.baeldung.objectclass; + +public class Lender extends User { + + private double totalInvestmentAmount; + + public double invest(double amount) { + totalInvestmentAmount = amount; + return totalInvestmentAmount; + } + + public double increaseInvestment(double increaseBy) { + return totalInvestmentAmount + increaseBy; + } + + public double collectDividends() { + return totalInvestmentAmount * 0.07; + } + +} diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/User.java b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/User.java new file mode 100644 index 0000000000..b1f3887f2f --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/objectclass/User.java @@ -0,0 +1,12 @@ +package com.baeldung.objectclass; + +import lombok.Data; + +@Data +public class User { + + private String firstName; + private String lastName; + + +} diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/objectclass/CreditAppUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/objectclass/CreditAppUnitTest.java new file mode 100644 index 0000000000..8330ddbac5 --- /dev/null +++ b/core-java-modules/core-java/src/test/java/com/baeldung/objectclass/CreditAppUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.objectclass; + +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.Test; + +public class CreditAppUnitTest { + + @Test + public void givenLender_whenInstanceOf_thenReturnTrue() { + User lender = new Lender(); + assertTrue(lender instanceof Lender); + assertTrue(lender instanceof User); + } + + @Test + public void givenUser_whenInstanceOfLender_thenDowncast() { + User user = new Lender(); + Lender lender = null; + + if(user instanceof Lender) { + lender = (Lender) user; + } + + assertNotNull(lender); + } + + @Test + public void givenUser_whenIsInstanceOfLender_thenDowncast() { + User user = new Lender(); + Lender lender = null; + + if(Lender.class.isInstance(user)) { + lender = (Lender) user; + } + + assertNotNull(lender); + } + + @Test + public void givenBorrower_whenLoanAmountIsDouble_thenRequestLoan() { + Borrower borrower = new Borrower(); + double amount = 100.0; + + //if(amount instanceof Double) // Compilation error, no autoboxing + if(Double.class.isInstance(amount)) { + borrower.requestLoan(amount); + } + assertEquals(100, borrower.getTotalLoanAmount()); + } + + @Test + public void givenBorrower_whenLoanAmountIsNotString_thenRequestLoan() { + Borrower borrower = new Borrower(); + Double amount = 100.0; + + //if(amount instanceof String) // Compilation error, incompatible operands + if(!String.class.isInstance(amount)) { + borrower.requestLoan(amount); + } + assertEquals(100, borrower.getTotalLoanAmount()); + } + + @Test + public void givenLender_whenGetClass_thenEqualsLenderType() { + User lender = new Lender(); + assertEquals(Lender.class, lender.getClass()); + assertNotEquals(User.class, lender.getClass()); + } + +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 326d4bb1c5..b7454cc737 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -31,10 +31,14 @@ core-java-annotations - core-java-arrays - core-java-arrays-2 - core-java-arrays-3 + core-java-arrays-sorting + core-java-arrays-guides + core-java-arrays-multidimensional + core-java-arrays-convert + core-java-arrays-operations-basic + core-java-arrays-operations-advanced + core-java-collections core-java-collections-2 core-java-collections-3 @@ -42,7 +46,10 @@ core-java-collections-list core-java-collections-list-2 core-java-collections-list-3 - core-java-collections-set + core-java-collections-maps + core-java-collections-maps-2 + core-java-collections-maps-3 + core-java-concurrency-2 core-java-concurrency-advanced @@ -66,6 +73,7 @@ core-java-io-2 core-java-io-apis core-java-io-conversions + core-java-io-conversions-2 core-java-jar core-java-jndi @@ -76,6 +84,7 @@ core-java-lang core-java-lang-2 core-java-lang-math + core-java-lang-math-2 core-java-lang-oop core-java-lang-oop-2 core-java-lang-oop-3 diff --git a/core-kotlin-modules/core-kotlin-collections/README.md b/core-kotlin-modules/core-kotlin-collections/README.md index bbea5869af..f0da2b4cfd 100644 --- a/core-kotlin-modules/core-kotlin-collections/README.md +++ b/core-kotlin-modules/core-kotlin-collections/README.md @@ -8,3 +8,4 @@ This module contains articles about core Kotlin collections. - [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api) - [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map) - [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection) +- [Collection Transformations in Kotlin](https://www.baeldung.com/kotlin-collection-transformations) diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/AssociateUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/AssociateUnitTest.kt new file mode 100644 index 0000000000..68f7040c4c --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/AssociateUnitTest.kt @@ -0,0 +1,48 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class AssociateUnitTest { + @Test + fun testToMap() { + val input = listOf(Pair("one", 1), Pair("two", 2)) + val map = input.toMap() + assertEquals(mapOf("one" to 1, "two" to 2), map) + } + + @Test + fun testAssociateWith() { + val inputs = listOf("Hi", "there") + val map = inputs.associateWith { k -> k.length } + assertEquals(mapOf("Hi" to 2, "there" to 5), map) + } + + @Test + fun testAssociateBy() { + val inputs = listOf("Hi", "there") + val map = inputs.associateBy { v -> v.length } + assertEquals(mapOf(2 to "Hi", 5 to "there"), map) + } + + @Test + fun testAssociate() { + val inputs = listOf("Hi", "there") + val map = inputs.associate { e -> Pair(e.toUpperCase(), e.reversed()) } + assertEquals(mapOf("HI" to "iH", "THERE" to "ereht"), map) + } + + @Test + fun testAssociateByDuplicateKeys() { + val inputs = listOf("one", "two") + val map = inputs.associateBy { v -> v.length } + assertEquals(mapOf(3 to "two"), map) + } + + @Test + fun testGroupBy() { + val inputs = listOf("one", "two", "three") + val map = inputs.groupBy { v -> v.length } + assertEquals(mapOf(3 to listOf("one", "two"), 5 to listOf("three")), map) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FilterUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FilterUnitTest.kt new file mode 100644 index 0000000000..591577e4f3 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FilterUnitTest.kt @@ -0,0 +1,43 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class FilterUnitTest { + @Test + fun testFilterWithLambda() { + val input = listOf(1, 2, 3, 4, 5) + val filtered = input.filter { it <= 3 } + assertEquals(listOf(1, 2, 3), filtered) + } + + @Test + fun testFilterWithMethodReference() { + val input = listOf(1, 2, 3, 4, 5) + val filtered = input.filter(this::isSmall) + assertEquals(listOf(1, 2, 3), filtered) + } + + @Test + fun testFilterNotWithMethodReference() { + val input = listOf(1, 2, 3, 4, 5) + val filtered = input.filterNot(this::isSmall) + assertEquals(listOf(4, 5), filtered) + } + + @Test + fun testFilterIndexed() { + val input = listOf(5, 4, 3, 2, 1) + val filtered = input.filterIndexed { index, element -> index < 3 } + assertEquals(listOf(5, 4, 3), filtered) + } + + @Test + fun testFilterNotNull() { + val nullable: List = listOf("Hello", null, "World") + val nonnull: List = nullable.filterNotNull() + assertEquals(listOf("Hello", "World"), nonnull) + } + + private fun isSmall(i: Int) = i <= 3 +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FlattenUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FlattenUnitTest.kt new file mode 100644 index 0000000000..69fbceb8e3 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FlattenUnitTest.kt @@ -0,0 +1,21 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class FlattenUnitTest { + @Test + fun testFlatten() { + val inputs = listOf("one", "two", "three") + val characters = inputs.map(String::toList) + val flattened = characters.flatten(); + assertEquals(listOf('o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e'), flattened) + } + + @Test + fun testFlatMap() { + val inputs = listOf("one", "two", "three") + val characters = inputs.flatMap(String::toList) + assertEquals(listOf('o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e'), characters) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/JoinToUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/JoinToUnitTest.kt new file mode 100644 index 0000000000..2ac0cdca50 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/JoinToUnitTest.kt @@ -0,0 +1,46 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class JoinToUnitTest { + @Test + fun testJoinToString() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val simpleString = inputs.joinToString() + assertEquals("Jan, Feb, Mar, Apr, May", simpleString) + + val detailedString = inputs.joinToString(separator = ",", prefix="Months: ", postfix=".") + assertEquals("Months: Jan,Feb,Mar,Apr,May.", detailedString) + } + + @Test + fun testJoinToStringLimits() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val simpleString = inputs.joinToString(limit = 3) + assertEquals("Jan, Feb, Mar, ...", simpleString) + } + + @Test + fun testJoinToStringTransform() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val simpleString = inputs.joinToString(transform = String::toUpperCase) + assertEquals("JAN, FEB, MAR, APR, MAY", simpleString) + } + + @Test + fun testJoinTo() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val output = StringBuilder() + output.append("My ") + .append(inputs.size) + .append(" elements: ") + inputs.joinTo(output) + + assertEquals("My 5 elements: Jan, Feb, Mar, Apr, May", output.toString()) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/MapUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/MapUnitTest.kt new file mode 100644 index 0000000000..e22fcbe903 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/MapUnitTest.kt @@ -0,0 +1,53 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class MapUnitTest { + @Test + fun testMapWithLambda() { + val input = listOf("one", "two", "three") + + val reversed = input.map { it.reversed() } + assertEquals(listOf("eno", "owt", "eerht"), reversed) + + val lengths = input.map { it.length } + assertEquals(listOf(3, 3, 5), lengths) + } + + @Test + fun testMapIndexed() { + val input = listOf(3, 2, 1) + val result = input.mapIndexed { index, value -> index * value } + assertEquals(listOf(0, 2, 2), result) + } + + @Test + fun testMapNotNull() { + val input = listOf(1, 2, 3, 4, 5) + val smallSquares = input.mapNotNull { + if (it <= 3) { + it * it + } else { + null + } + } + assertEquals(listOf(1, 4, 9), smallSquares) + } + + @Test + fun mapMapKeys() { + val inputs = mapOf("one" to 1, "two" to 2, "three" to 3) + + val uppercases = inputs.mapKeys { it.key.toUpperCase() } + assertEquals(mapOf("ONE" to 1, "TWO" to 2, "THREE" to 3), uppercases) + } + + @Test + fun mapMapValues() { + val inputs = mapOf("one" to 1, "two" to 2, "three" to 3) + + val squares = inputs.mapValues { it.value * it.value } + assertEquals(mapOf("one" to 1, "two" to 4, "three" to 9), squares) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ReduceUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ReduceUnitTest.kt new file mode 100644 index 0000000000..6821b7cdb9 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ReduceUnitTest.kt @@ -0,0 +1,22 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class ReduceUnitTest { + @Test + fun testJoinToStringAsReduce() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val result = inputs.reduce { acc, next -> "$acc, $next" } + assertEquals("Jan, Feb, Mar, Apr, May", result) + } + + @Test + fun testFoldToLength() { + val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") + + val result = inputs.fold(0) { acc, next -> acc + next.length } + assertEquals(15, result) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ZipUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ZipUnitTest.kt new file mode 100644 index 0000000000..66aeeceef4 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ZipUnitTest.kt @@ -0,0 +1,34 @@ +package com.baeldung.collections.transformations + +import org.junit.Assert.assertEquals +import org.junit.Test + +class ZipUnitTest { + @Test + fun testZip() { + val left = listOf("one", "two", "three") + val right = listOf(1, 2, 3) + val zipped = left.zip(right) + assertEquals (listOf(Pair("one", 1), Pair("two", 2), Pair("three", 3)), zipped) + } + + @Test + fun testZipShort() { + val left = listOf("one", "two") + val right = listOf(1, 2, 3) + val zipped = left.zip(right) + assertEquals (listOf(Pair("one", 1), Pair("two", 2)), zipped) + } + + @Test + fun testUnzip() { + val left = listOf("one", "two", "three") + val right = listOf(1, 2, 3) + val zipped = left.zip(right) + + val (newLeft, newRight) = zipped.unzip() + assertEquals(left, newLeft) + assertEquals(right, newRight) + } + +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt new file mode 100644 index 0000000000..7b263914c6 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt @@ -0,0 +1,59 @@ +package com.baeldung.foldvsreduce + +import org.junit.Test +import org.junit.jupiter.api.assertThrows +import java.lang.RuntimeException +import kotlin.test.assertEquals + +class FoldAndReduceTest { + + @Test + fun testReduceLimitations() { + val numbers: List = listOf(1, 2, 3) + val sum: Number = numbers.reduce { acc, next -> acc + next } + assertEquals(6, sum) + + val emptyList = listOf() + assertThrows { emptyList.reduce { acc, next -> acc + next } } + + // doesn't compile + // val sum = numbers.reduce { acc, next -> acc.toLong() + next.toLong()} + } + + @Test + fun testFold() { + + val numbers: List = listOf(1, 2, 3) + val sum: Int = numbers.fold(0, { acc, next -> acc + next }) + assertEquals(6, sum) + + //change result type + val sumLong: Long = numbers.fold(0L, { acc, next -> acc + next.toLong() }) + assertEquals(6L, sumLong) + + val emptyList = listOf() + val emptySum = emptyList.fold(0, { acc, next -> acc + next }) + assertEquals(0, emptySum) + + //power of changing result type + val (even, odd) = numbers.fold(Pair(listOf(), listOf()), { acc, next -> + if (next % 2 == 0) Pair(acc.first + next, acc.second) + else Pair(acc.first, acc.second + next) + }) + + assertEquals(listOf(2), even) + assertEquals(listOf(1, 3), odd) + } + + @Test + fun testVariationsOfFold() { + val numbers = listOf(1, 2, 3) + val reversed = numbers.foldRight(listOf(), { next, acc -> acc + next}) + assertEquals(listOf(3,2,1), reversed) + + val reversedIndexes = numbers.foldRightIndexed(listOf(), { i, _, acc -> acc + i }) + assertEquals(listOf(2,1,0), reversedIndexes) + } + + +} \ No newline at end of file diff --git a/core-kotlin-modules/pom.xml b/core-kotlin-modules/pom.xml index 24bdc189be..de41aecf73 100644 --- a/core-kotlin-modules/pom.xml +++ b/core-kotlin-modules/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.core-kotlin-modules core-kotlin-modules diff --git a/core-scala/README.md b/core-scala/README.md index 13929ff721..72b583c22b 100644 --- a/core-scala/README.md +++ b/core-scala/README.md @@ -1,8 +1,3 @@ -## Core Scala +### Relevant Articles: -This module contains articles about Scala's core features - -### Relevant Articles: - -- [Introduction to Scala](https://www.baeldung.com/scala-intro) -- [Regular Expressions in Scala](https://www.baeldung.com/scala/regular-expressions) +- [Pattern Matching in Scala](https://www.baeldung.com/scala/pattern-matching) diff --git a/core-scala/pom.xml b/core-scala/pom.xml index d72727dd39..8277b0f856 100644 --- a/core-scala/pom.xml +++ b/core-scala/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 core-scala 1.0-SNAPSHOT @@ -51,5 +53,5 @@ 2.12.7 3.3.2 - + diff --git a/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala b/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala deleted file mode 100644 index 7c1281e573..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.scala - -/** - * Sample code demonstrating the various control structured. - * - * @author Chandra Prakash - * - */ -object ControlStructuresDemo { - def gcd(x : Int, y : Int) : Int = { - if (y == 0) x else gcd(y, x % y) - } - - def gcdIter(x : Int, y : Int) : Int = { - var a = x - var b = y - while (b > 0) { - a = a % b - val t = a - a = b - b = t - } - a - } - - def rangeSum(a : Int, b : Int) = { - var sum = 0; - for (i <- a to b) { - sum += i - } - sum - } - - def factorial(a : Int) : Int = { - var result = 1; - var i = 1; - do { - result *= i - i = i + 1 - } while (i <= a) - result - } - -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/Employee.scala b/core-scala/src/main/scala/com/baeldung/scala/Employee.scala deleted file mode 100644 index 9291d958b3..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/Employee.scala +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.scala - -/** - * Sample Code demonstrating a class. - * - * @author Chandra Prakash - * - */ -class Employee(val name : String, - var salary : Int, - annualIncrement : Int = 20) { - - def incrementSalary() : Unit = { - salary += annualIncrement - } - - override def toString = - s"Employee(name=$name, salary=$salary)" -} - -/** - * A Trait which will make the toString return upper case value. - */ -trait UpperCasePrinter { - override def toString: String = super.toString toUpperCase -} - diff --git a/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala b/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala deleted file mode 100644 index b3f0ce09a5..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.scala - -object HelloWorld extends App { - println("Hello World!") - args foreach println -} diff --git a/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala b/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala deleted file mode 100644 index 02c41a5f8c..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.scala - -/** - * Sample higher order functions. - * - * @author Chandra Prakash - * - */ -object HigherOrderFunctions { - - def mapReduce(r : (Int, Int) => Int, - i : Int, - m : Int => Int, - a : Int, b : Int): Int = { - def iter(a : Int, result : Int) : Int = { - if (a > b) result - else iter(a + 1, r(m(a), result)) - } - iter(a, i) - } - - def whileLoop(condition : => Boolean)(body : => Unit) : Unit = - if (condition) { - body - whileLoop(condition)(body) - } -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala b/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala deleted file mode 100644 index f1a5722a4e..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.scala - -/** - * An abstract class for set of integers and its implementation. - * - * @author Chandra Prakash - * - */ -abstract class IntSet { - // add an element to the set - def incl(x : Int) : IntSet - - // whether an element belongs to the set - def contains(x : Int) : Boolean -} - -class EmptyIntSet extends IntSet { - - def contains(x : Int) : Boolean = false - - def incl(x : Int) = - new NonEmptyIntSet(x, this) -} - -class NonEmptyIntSet(val head : Int, val tail : IntSet) - extends IntSet { - - def contains(x : Int) : Boolean = - head == x || (tail contains x) - - def incl(x : Int) : IntSet = - if (this contains x) this - else new NonEmptyIntSet(x, this) -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/PatternMatching.scala b/core-scala/src/main/scala/com/baeldung/scala/PatternMatching.scala deleted file mode 100644 index 71458237d6..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/PatternMatching.scala +++ /dev/null @@ -1,137 +0,0 @@ -package com.baeldung.scala - -// Case Class -abstract class Animal - -case class Mammal(name: String, fromSea: Boolean) extends Animal - -case class Bird(name: String) extends Animal - -case class Fish(name: String) extends Animal - -// Sealed Class -sealed abstract class CardSuit - -case class Spike() extends CardSuit - -case class Diamond() extends CardSuit - -case class Heart() extends CardSuit - -case class Club() extends CardSuit - -object Person { - def apply(fullName: String) = fullName - - def unapply(fullName: String): Option[String] = { - if (!fullName.isEmpty) - Some(fullName.replaceAll("(?<=\\w)(\\w+)", ".")) - else - None - } -} - -class PatternMatching { - - def caseClassesPatternMatching(animal: Animal): String = { - animal match { - case Mammal(name, fromSea) => s"I'm a $name, a kind of mammal. Am I from the sea? $fromSea" - case Bird(name) => s"I'm a $name, a kind of bird" - case _ => "I'm an unknown animal" - } - } - - def constantsPatternMatching(constant: Any): String = { - constant match { - case 0 => "I'm equal to zero" - case 4.5d => "I'm a double" - case false => "I'm the contrary of true" - case _ => s"I'm unknown and equal to $constant" - } - } - - def sequencesPatternMatching(sequence: Any): String = { - sequence match { - case List(singleElement) => s"I'm a list with one element: $singleElement" - case List(_, _*) => s"I'm a list with one or multiple elements: $sequence" - case Vector(1, 2, _*) => s"I'm a vector: $sequence" - case _ => s"I'm an unrecognized sequence. My value: $sequence" - } - } - - def tuplesPatternMatching(tuple: Any): String = { - tuple match { - case (first, second) => s"I'm a tuple with two elements: $first & $second" - case (first, second, third) => s"I'm a tuple with three elements: $first & $second & $third" - case _ => s"Unrecognized pattern. My value: $tuple" - } - } - - def typedPatternMatching(any: Any): String = { - any match { - case string: String => s"I'm a string. My value: $string" - case integer: Int => s"I'm an integer. My value: $integer" - case _ => s"I'm from an unknown type. My value: $any" - } - } - - def regexPatterns(toMatch: String): String = { - val numeric = """([0-9]+)""".r - val alphabetic = """([a-zA-Z]+)""".r - val alphanumeric = """([a-zA-Z0-9]+)""".r - - toMatch match { - case numeric(value) => s"I'm a numeric with value $value" - case alphabetic(value) => s"I'm an alphabetic with value $value" - case alphanumeric(value) => s"I'm an alphanumeric with value $value" - case _ => s"I contain other characters than alphanumerics. My value $toMatch" - } - } - - def optionsPatternMatching(option: Option[String]): String = { - option match { - case Some(value) => s"I'm not an empty option. Value $value" - case None => "I'm an empty option" - } - } - - def patternGuards(toMatch: Any, maxLength: Int): String = { - toMatch match { - case list: List[Any] if (list.size <= maxLength) => "List is of acceptable size" - case list: List[Any] => "List has not an acceptable size" - case string: String if (string.length <= maxLength) => "String is of acceptable size" - case string: String => "String has not an acceptable size" - case _ => "Input is neither a List or a String" - } - } - - def sealedClass(cardSuit: CardSuit): String = { - cardSuit match { - case Spike() => "Card is spike" - case Club() => "Card is club" - case Heart() => "Card is heart" - case Diamond() => "Card is diamond" - } - } - - def extractors(person: Any): String = { - person match { - case Person(initials) => s"My initials are $initials" - case _ => "Could not extract initials" - } - } - - def closuresPatternMatching(list: List[Any]): List[Any] = { - list.collect { case i: Int if (i < 10) => i } - } - - def catchBlocksPatternMatching(exception: Exception): String = { - try { - throw exception - } catch { - case ex: IllegalArgumentException => "It's an IllegalArgumentException" - case ex: RuntimeException => "It's a RuntimeException" - case _ => "It's an unknown kind of exception" - } - } -} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/Utils.scala b/core-scala/src/main/scala/com/baeldung/scala/Utils.scala deleted file mode 100644 index 20bc413646..0000000000 --- a/core-scala/src/main/scala/com/baeldung/scala/Utils.scala +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.scala - -/** - * Some utility methods. - * - * @author Chandra Prakash - * - */ -object Utils { - def average(x : Double, y : Double): Double = (x + y) / 2 - - def randomLessThan(d : Double): Double = { - var random = 0d - do { - random = Math.random() - } while (random >= d) - random - } - - def power(x : Int, y : Int) : Int = { - def powNested(i : Int, accumulator : Int) : Int = { - if (i <= 0) accumulator - else powNested(i - 1, x * accumulator) - } - powNested(y, 1) - } - - def fibonacci(n : Int) : Int = n match { - case 0 | 1 => 1 - case x if x > 1 => - fibonacci(x - 1) + fibonacci(x - 2) - } -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala deleted file mode 100644 index 584038ee2c..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.scala - -import com.baeldung.scala.ControlStructuresDemo._ -import org.junit.Assert.assertEquals -import org.junit.Test - -class ControlStructuresDemoUnitTest { - @Test - def givenTwoIntegers_whenGcdCalled_thenCorrectValueReturned() = { - assertEquals(3, gcd(15, 27)) - } - - @Test - def givenTwoIntegers_whenGcdIterCalled_thenCorrectValueReturned() = { - assertEquals(3, gcdIter(15, 27)) - } - - @Test - def givenTwoIntegers_whenRangeSumcalled_thenCorrectValueReturned() = { - assertEquals(55, rangeSum(1, 10)) - } - - @Test - def givenPositiveInteger_whenFactorialInvoked_thenCorrectValueReturned() = { - assertEquals(720, factorial(6)) - } - - @Test - def whenFactorialOf0Invoked_then1Returned() = { - assertEquals(1, factorial(0)) - } - -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala deleted file mode 100644 index 0828752a8a..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.scala - -import org.junit.Assert.assertEquals -import org.junit.Test - -class EmployeeUnitTest { - - @Test - def whenEmployeeSalaryIncremented_thenCorrectSalary() = { - val employee = new Employee("John Doe", 1000) - employee.incrementSalary() - assertEquals(1020, employee.salary) - } - - @Test - def givenEmployee_whenToStringCalled_thenCorrectStringReturned() = { - val employee = new Employee("John Doe", 1000) - assertEquals("Employee(name=John Doe, salary=1000)", employee.toString) - } - - @Test - def givenEmployeeWithTrait_whenToStringCalled_thenCorrectStringReturned() = { - val employee = - new Employee("John Doe", 1000) with UpperCasePrinter - assertEquals("EMPLOYEE(NAME=JOHN DOE, SALARY=1000)", employee.toString) - } - -} - - diff --git a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsExamplesUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsExamplesUnitTest.scala deleted file mode 100644 index cb43266a48..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsExamplesUnitTest.scala +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.scala - -import org.junit.Assert.assertEquals -import org.junit.Test - - -class HigherOrderFunctionsExamplesUnitTest { - - @Test - def whenCallingMapWithAnonymousFunction_thenTransformationIsApplied() = { - val expected = Seq("sir Alex Ferguson", "sir Bobby Charlton", "sir Frank Lampard") - - val names = Seq("Alex Ferguson", "Bobby Charlton", "Frank Lampard") - val sirNames = names.map(name => "sir " + name) - - assertEquals(expected, sirNames) - } - - @Test - def whenCallingMapWithDefined_thenTransformationIsApplied() = { - val expected = Seq("sir Alex Ferguson", "sir Bobby Charlton", "sir Frank Lampard") - - val names = Seq("Alex Ferguson", "Bobby Charlton", "Frank Lampard") - - def prefixWithSir(name: String) = "sir " + name - val sirNames = names.map(prefixWithSir) - - assertEquals(expected, sirNames) - } - - @Test - def whenCallingFilter_thenUnecessaryElementsAreRemoved() = { - val expected = Seq("John O'Shea", "John Hartson") - - val names = Seq("John O'Shea", "Aiden McGeady", "John Hartson") - val johns = names.filter(name => name.matches("^John .*")) - - assertEquals(expected, johns) - } - - @Test - def whenCallingReduce_thenProperSumIsCalculated() = { - val expected = 2750 - - val earnings = Seq(1000, 1300, 450) - val sumEarnings = earnings.reduce((acc, x) => acc + x) - - assertEquals(expected, sumEarnings) - } - - @Test - def whenCallingFold_thenNumberOfWordsShouldBeCalculated() = { - val expected = 6 - - val strings = Seq("bunch of words", "just me", "it") - val sumEarnings = strings.foldLeft(0)((acc, x) => acc + x.split(" ").size) - - assertEquals(expected, sumEarnings) - } - - @Test - def whenCallingOwnHigherOrderFunction_thenProperFunctionIsReturned() = { - def mathOperation(name: String): (Int, Int) => Int = (x: Int, y: Int) => { - name match { - case "addition" => x + y - case "multiplication" => x * y - case "division" => x/y - case "subtraction" => x - y - } - } - - def add: (Int, Int) => Int = mathOperation("addition") - def mul: (Int, Int) => Int = mathOperation("multiplication") - def div: (Int, Int) => Int = mathOperation("division") - def sub: (Int, Int) => Int = mathOperation("subtraction") - - assertEquals(15, add(10, 5)) - assertEquals(50, mul(10, 5)) - assertEquals(2, div(10, 5)) - assertEquals(5, sub(10, 5)) - } -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala deleted file mode 100644 index 240c879d7f..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.scala - -import com.baeldung.scala.HigherOrderFunctions.mapReduce -import org.junit.Assert.assertEquals -import org.junit.Test - -class HigherOrderFunctionsUnitTest { - - @Test - def whenCalledWithSumAndSquareFunctions_thenCorrectValueReturned() = { - def square(x : Int) = x * x - - def sum(x : Int, y : Int) = x + y - - def sumSquares(a : Int, b : Int) = - mapReduce(sum, 0, square, a, b) - - assertEquals(385, sumSquares(1, 10)) - } - - @Test - def whenComputingSumOfSquaresWithAnonymousFunctions_thenCorrectValueReturned() = { - def sumSquares(a : Int, b : Int) = - mapReduce((x, y) => x + y, 0, x => x * x, a, b) - - assertEquals(385, sumSquares(1, 10)) - } - - @Test - def givenCurriedFunctions_whenInvoked_thenCorrectValueReturned() = { - // a curried function - def sum(f : Int => Int)(a : Int, - b : Int) : Int = - if (a > b) 0 else f(a) + sum(f)(a + 1, b) - - // another curried function - def mod(n : Int)(x : Int) = x % n - - // application of a curried function - assertEquals(1, mod(5)(6)) - - // partial application of curried function - // trailing underscore is required to make function type explicit - val sumMod5 = sum(mod(5)) _ - - assertEquals(10, sumMod5(6, 10)) - } -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala deleted file mode 100644 index ac27389d70..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.scala - -import org.junit.Assert.assertFalse -import org.junit.Test - -class IntSetUnitTest { - - @Test - def givenSetof1To10_whenContains11Called_thenFalse() = { - - // Set up a set containing integers 1 to 10. - val set1To10 = - Range(1, 10) - .foldLeft(new EmptyIntSet() : IntSet) { - (x, y) => x incl y - } - - assertFalse(set1To10 contains 11) - } - -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/PatternMatchingUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/PatternMatchingUnitTest.scala deleted file mode 100644 index 21a2f0e871..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/PatternMatchingUnitTest.scala +++ /dev/null @@ -1,208 +0,0 @@ -package com.baeldung.scala - -import java.io.FileNotFoundException - -import org.junit.Assert.assertEquals -import org.junit.Test - -class PatternMatchingUnitTest { - @Test - def whenAMammalIsGivenToTheMatchExpression_ThenItsRecognizedAsMammal(): Unit = { - val result = new PatternMatching().caseClassesPatternMatching(Mammal("Lion", fromSea = false)) - assertEquals("I'm a Lion, a kind of mammal. Am I from the sea? false", result) - } - - @Test - def whenABirdIsGivenToTheMatchExpression_ThenItsRecognizedAsBird(): Unit = { - val result = new PatternMatching().caseClassesPatternMatching(Bird("Pigeon")) - assertEquals("I'm a Pigeon, a kind of bird", result) - } - - @Test - def whenAnUnkownAnimalIsGivenToTheMatchExpression_TheDefaultClauseIsUsed(): Unit = { - val result = new PatternMatching().caseClassesPatternMatching(Fish("Tuna")) - assertEquals("I'm an unknown animal", result) - } - - @Test - def whenTheConstantZeroIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().constantsPatternMatching(0) - assertEquals("I'm equal to zero", result) - } - - @Test - def whenFourAndAHalfIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().constantsPatternMatching(4.5d) - assertEquals("I'm a double", result) - } - - @Test - def whenTheBooleanFalseIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().constantsPatternMatching(false) - assertEquals("I'm the contrary of true", result) - } - - @Test - def whenAnUnkownConstantIsPassed_ThenTheDefaultPatternIsUsed(): Unit = { - val result = new PatternMatching().constantsPatternMatching(true) - assertEquals("I'm unknown and equal to true", result) - } - - @Test - def whenASingleElementListIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(List("String")) - assertEquals("I'm a list with one element: String", result) - } - - @Test - def whenAMultipleElementsListIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(List("Multiple", "Elements")) - assertEquals("I'm a list with one or multiple elements: List(Multiple, Elements)", result) - } - - @Test - def whenAVectorBeginningWithOneAndTwoIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(Vector(1, 2, 3)) - assertEquals("I'm a vector: Vector(1, 2, 3)", result) - } - - @Test - def whenANotMatchingVectorIsPassed_ThenItShouldntMatchAndEnterTheDefaultClause(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(Vector(2, 1)) - assertEquals("I'm an unrecognized sequence. My value: Vector(2, 1)", result) - } - - @Test - def whenAnEmptyListIsPassed_ThenItShouldntMatchAndEnterTheDefaultClause(): Unit = { - val result = new PatternMatching().sequencesPatternMatching(List()) - assertEquals("I'm an unrecognized sequence. My value: List()", result) - } - - @Test - def whenATwoElementsTupleIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().tuplesPatternMatching(("First", "Second")) - assertEquals("I'm a tuple with two elements: First & Second", result) - } - - @Test - def whenAThreeElementsTupleIsPassed_ThenItMatchesTheCorrespondingPattern(): Unit = { - val result = new PatternMatching().tuplesPatternMatching(("First", "Second", "Third")) - assertEquals("I'm a tuple with three elements: First & Second & Third", result) - } - - @Test - def whenAnoterKindOfTupleIsPassed_ThenItShouldntMatchAndReturnTheDefaultPattern(): Unit = { - val result = new PatternMatching().tuplesPatternMatching(("First")) - assertEquals("Unrecognized pattern. My value: First", result) - } - - @Test - def whenAStringConsistingOfNumericsOnlyIsPassed_ThenItShouldMatchTheNumericRegex(): Unit = { - val result = new PatternMatching().regexPatterns("123") - assertEquals("I'm a numeric with value 123", result) - } - - @Test - def whenAStringConsistignOfAlphabeticsOnlyIsPassed_ThenItShouldMatchTheAlphabeticRegex(): Unit = { - val result = new PatternMatching().regexPatterns("abc") - assertEquals("I'm an alphabetic with value abc", result) - } - - @Test - def whenAStringConsistignOfAlphanumericsOnlyIsPassed_ThenItShouldMatchTheAlphanumericRegex(): Unit = { - val result = new PatternMatching().regexPatterns("abc123") - assertEquals("I'm an alphanumeric with value abc123", result) - } - - @Test - def whenAnotherTypeOfStringIsPassed_ThenItShouldntMatchAndReturnTheDefaultPattern(): Unit = { - val result = new PatternMatching().regexPatterns("abc_123") - assertEquals("I contain other characters than alphanumerics. My value abc_123", result) - } - - @Test - def whenAFilledOptionIsPassed_ThenItShouldMatchTheSomeClause(): Unit = { - val result = new PatternMatching().optionsPatternMatching(Option.apply("something")) - assertEquals("I'm not an empty option. Value something", result) - } - - @Test - def whenAnEmptyOptionIsPassed_ThenItShouldMatchTheNoneClause(): Unit = { - val result = new PatternMatching().optionsPatternMatching(Option.empty) - assertEquals("I'm an empty option", result) - } - - @Test - def whenAListWithAcceptedSizeIsPassed_ThenThePositiveMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards(List(1, 2), 3) - assertEquals("List is of acceptable size", result) - } - - @Test - def whenAListWithAnUnacceptedSizeIsPassed_ThenTheNegativeMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards(List(1, 2, 3, 4), 3) - assertEquals("List has not an acceptable size", result) - } - - @Test - def whenAStringWithAcceptedSizeIsPassed_ThenThePositiveMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards("OK", 3) - assertEquals("String is of acceptable size", result) - } - - @Test - def whenAStringWithAnUnacceptedSizeIsPassed_ThenTheNegativeMessageIsSent(): Unit = { - val result = new PatternMatching().patternGuards("Not OK", 3) - assertEquals("String has not an acceptable size", result) - } - - @Test - def whenAnObjectWhichIsNotAListOrAStringIsPassed_thenTheDefaultClauseIsUsed(): Unit = { - val result = new PatternMatching().patternGuards(1, 1) - assertEquals("Input is neither a List or a String", result) - } - - @Test - def whenACardSuitIsPassed_ThenTheCorrespondingMatchCaseClauseIsUsed(): Unit = { - assertEquals("Card is spike", new PatternMatching().sealedClass(Spike())) - assertEquals("Card is club", new PatternMatching().sealedClass(Club())) - assertEquals("Card is heart", new PatternMatching().sealedClass(Heart())) - assertEquals("Card is diamond", new PatternMatching().sealedClass(Diamond())) - } - - @Test - def whenAnObjectWithExtractorIsPassed_ThenTheExtractedValueIsUsedInTheCaseClause(): Unit = { - val person = Person("John Smith") - val result = new PatternMatching().extractors(person) - assertEquals("My initials are J. S.", result) - } - - @Test - def whenAnObjectWithExtractorIsPassed_AndTheValueIsEmpty_ThenTheDefaultCaseClauseIsUsed(): Unit = { - val person = Person("") - val result = new PatternMatching().extractors(person) - assertEquals("Could not extract initials", result) - } - - @Test - def whenAListOfRandomElementsIsPassed_ThenOnlyTheIntegersBelowTenAreReturned(): Unit = { - val input = List(1, 2, "5", 11, true) - val result = new PatternMatching().closuresPatternMatching(input) - assertEquals(List(1, 2), result) - } - - @Test - def whenAnExceptionIsPassed_ThenTheCorrespondingMessageIsReturned(): Unit = { - val pm = new PatternMatching() - - val iae = new IllegalArgumentException() - val re = new RuntimeException() - val fnfe = new FileNotFoundException() - - assertEquals("It's an IllegalArgumentException", pm.catchBlocksPatternMatching(iae)) - assertEquals("It's a RuntimeException", pm.catchBlocksPatternMatching(re)) - assertEquals("It's an unknown kind of exception", pm.catchBlocksPatternMatching(fnfe)) - } -} - - diff --git a/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala deleted file mode 100644 index e4995201d8..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.scala - -import com.baeldung.scala.Utils.{average, fibonacci, power, randomLessThan} -import org.junit.Assert.{assertEquals, assertTrue} -import org.junit.Test - -class UtilsUnitTest { - - @Test - def whenAverageCalled_thenCorrectValueReturned(): Unit = { - assertEquals(15.0, average(10, 20), 1e-5) - } - - @Test - def whenRandomLessThanInvokedWithANumber_thenARandomLessThanItReturned: Unit = { - val d = 0.1 - assertTrue(randomLessThan(d) < d) - } - - @Test - def whenPowerInvokedWith2And3_then8Returned: Unit = { - assertEquals(8, power(2, 3)) - } - - @Test - def whenFibonacciCalled_thenCorrectValueReturned: Unit = { - assertEquals(1, fibonacci(0)) - assertEquals(1, fibonacci(1)) - assertEquals(fibonacci(6), - fibonacci(4) + fibonacci(5)) - } -} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/regex/RegexUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/regex/RegexUnitTest.scala deleted file mode 100644 index 27ed9e1172..0000000000 --- a/core-scala/src/test/scala/com/baeldung/scala/regex/RegexUnitTest.scala +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.scala.regex - -import org.junit.Test -import org.junit.Assert.assertEquals - -class RegexUnitTest { - private val polishPostalCode = "([0-9]{2})\\-([0-9]{3})".r - private val timestamp = "([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{3})".r - private val timestampUnanchored = timestamp.unanchored - - @Test - def givenRegularExpression_whenCallingFindFirstIn_thenShouldFindCorrectMatches(): Unit = { - val postCode = polishPostalCode.findFirstIn("Warsaw 01-011, Jerusalem Avenue") - assertEquals(Some("01-011"), postCode) - } - - @Test - def givenRegularExpression_whenCallingFindFirstMatchIn_thenShouldFindCorrectMatches(): Unit = { - val postCodes = polishPostalCode.findFirstMatchIn("Warsaw 01-011, Jerusalem Avenue") - assertEquals(Some("011"), for (m <- postCodes) yield m.group(2)) - } - - @Test - def givenRegularExpression_whenCallingFindAllIn_thenShouldFindCorrectMatches(): Unit = { - val postCodes = polishPostalCode.findAllIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue") - .toList - assertEquals(List("01-011", "30-059"), postCodes) - - polishPostalCode.findAllIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue") - } - - @Test - def givenRegularExpression_whenCallingFindAlMatchlIn_thenShouldFindCorrectMatches(): Unit = { - val postCodes = polishPostalCode.findAllMatchIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue") - .toList - val postalDistricts = for (m <- postCodes) yield m.group(1) - assertEquals(List("01", "30"), postalDistricts) - } - - @Test - def givenRegularExpression_whenExtractingValues_thenShouldExtractCorrectValues(): Unit = { - val description = "11:34:01.411" match { - case timestamp(hour, minutes, _, _) => s"It's $minutes minutes after $hour" - } - - assertEquals("It's 34 minutes after 11", description) - } - - @Test - def givenUnanchoredRegularExpression_whenExtractingValues_thenShouldExtractCorrectValues(): Unit = { - val description = "Timestamp: 11:34:01.411 error appeared" match { - case timestampUnanchored(hour, minutes, _, _) => s"It's $minutes minutes after $hour" - } - - assertEquals("It's 34 minutes after 11", description) - } - - @Test - def givenRegularExpression_whenCallingReplaceAllIn_thenShouldReplaceText(): Unit = { - val minutes = timestamp.replaceAllIn("11:34:01.311", m => m.group(2)) - - assertEquals("34", minutes) - } - - @Test - def givenRegularExpression_whenCallingReplaceAllInWithMatcher_thenShouldReplaceText(): Unit = { - val secondsThatDayInTotal = timestamp.replaceAllIn("11:34:01.311", _ match { - case timestamp(hours, minutes, seconds, _) => s"$hours-$minutes" - }) - - assertEquals("11-34", secondsThatDayInTotal) - } -} diff --git a/couchbase/pom.xml b/couchbase/pom.xml index f4e98b32ba..34e2832e55 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 couchbase 0.1-SNAPSHOT diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index a011b6a121..e0f38199ec 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.pmd custom-pmd diff --git a/dagger/pom.xml b/dagger/pom.xml index 528a5383c6..e9410ceb63 100644 --- a/dagger/pom.xml +++ b/dagger/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 dagger dagger @@ -44,4 +46,4 @@ 2.16 - \ No newline at end of file + diff --git a/data-structures/pom.xml b/data-structures/pom.xml index 4468f3d21f..e2d2e23090 100644 --- a/data-structures/pom.xml +++ b/data-structures/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 data-structures 0.0.1-SNAPSHOT diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java index bb62714006..7469e8ba64 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -142,7 +142,7 @@ public class BinaryTree { nodes.add(node.left); } - if (node.left != null) { + if (node.right != null) { nodes.add(node.right); } } diff --git a/ddd-modules/infrastructure/pom.xml b/ddd-modules/infrastructure/pom.xml index 72ec263745..c301eaa92a 100644 --- a/ddd-modules/infrastructure/pom.xml +++ b/ddd-modules/infrastructure/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules.infrastructure infrastructure diff --git a/ddd-modules/mainapp/pom.xml b/ddd-modules/mainapp/pom.xml index ae1057f307..a048263d37 100644 --- a/ddd-modules/mainapp/pom.xml +++ b/ddd-modules/mainapp/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules.mainapp mainapp diff --git a/ddd-modules/ordercontext/pom.xml b/ddd-modules/ordercontext/pom.xml index 6a921d2408..abd166fb69 100644 --- a/ddd-modules/ordercontext/pom.xml +++ b/ddd-modules/ordercontext/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules.ordercontext ordercontext diff --git a/ddd-modules/pom.xml b/ddd-modules/pom.xml index 65bc204988..c6dd6e1f25 100644 --- a/ddd-modules/pom.xml +++ b/ddd-modules/pom.xml @@ -1,9 +1,11 @@ - + 4.0.0 com.baeldung.dddmodules - dddmodules + ddd-modules 1.0 ddd-modules pom diff --git a/ddd-modules/sharedkernel/pom.xml b/ddd-modules/sharedkernel/pom.xml index 3b5d8bb71f..a61f03a494 100644 --- a/ddd-modules/sharedkernel/pom.xml +++ b/ddd-modules/sharedkernel/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules.sharedkernel sharedkernel diff --git a/ddd-modules/shippingcontext/pom.xml b/ddd-modules/shippingcontext/pom.xml index 060f4fe5bf..2096923f90 100644 --- a/ddd-modules/shippingcontext/pom.xml +++ b/ddd-modules/shippingcontext/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.dddmodules.shippingcontext shippingcontext diff --git a/ddd/pom.xml b/ddd/pom.xml index f27f1d24a9..7f3c417b71 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.ddd ddd @@ -21,8 +23,8 @@ spring-boot-starter-data-mongodb
- org.springframework.boot - spring-boot-starter-data-cassandra + org.springframework.boot + spring-boot-starter-data-cassandra org.junit.jupiter @@ -97,4 +99,4 @@ 2.0.6.RELEASE - \ No newline at end of file + diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index c143b86ff8..c8fa18cbd4 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.deeplearning4j deeplearning4j diff --git a/disruptor/pom.xml b/disruptor/pom.xml index 94be78fad6..31fc28986b 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 disruptor 0.1.0-SNAPSHOT diff --git a/dozer/pom.xml b/dozer/pom.xml index e307354603..0fdf7f6fba 100644 --- a/dozer/pom.xml +++ b/dozer/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 dozer 1.0 diff --git a/drools/pom.xml b/drools/pom.xml index b4421ff2e3..e0a7b52938 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 drools drools diff --git a/dropwizard/pom.xml b/dropwizard/pom.xml index ddc9aa1949..c3e1a4e841 100644 --- a/dropwizard/pom.xml +++ b/dropwizard/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 dropwizard 0.0.1-SNAPSHOT @@ -48,8 +49,7 @@ - + com.baeldung.dropwizard.introduction.IntroductionApplication diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 9a7aceb9e5..cca1b3a3d1 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 dubbo dubbo diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 8c7e4c8c4c..5953195123 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.ethereum ethereum diff --git a/feign/pom.xml b/feign/pom.xml index 6dc8e7bafa..4b994be1f2 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.feign feign diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index 8f7d058db7..566eed95d8 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 flyway-cdi-extension 1.0-SNAPSHOT diff --git a/geotools/pom.xml b/geotools/pom.xml index 71489bdf94..46913daa69 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 geotools 0.0.1-SNAPSHOT diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml index 15f7f5c824..1e474b5dd0 100644 --- a/google-cloud/pom.xml +++ b/google-cloud/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 google-cloud 0.1-SNAPSHOT diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index 37e423b3af..6fdcae4f75 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 google-web-toolkit @@ -53,8 +54,7 @@ - + ${project.build.directory}/${project.build.finalName}/WEB-INF/classes @@ -76,8 +76,7 @@ com.baeldung.Google_web_toolkit Google_web_toolkit true - + ${maven.compiler.source} @@ -109,9 +108,8 @@ - + 1.8 1.8 diff --git a/gradle/gradle-employee-app/.gitignore b/gradle/gradle-employee-app/.gitignore new file mode 100644 index 0000000000..d347f664af --- /dev/null +++ b/gradle/gradle-employee-app/.gitignore @@ -0,0 +1,3 @@ +/.idea +/.gradle +/build diff --git a/gradle/gradle-employee-app/build.gradle b/gradle/gradle-employee-app/build.gradle new file mode 100644 index 0000000000..19b80c0c4a --- /dev/null +++ b/gradle/gradle-employee-app/build.gradle @@ -0,0 +1,38 @@ + +plugins { + id 'java-library' + id 'application' +} + +apply plugin: 'application' +mainClassName = 'employee.EmployeeApp' + +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +println 'This is executed during configuration phase' + +task configured { + println 'The project is configured' +} + +task wrapper(type: Wrapper){ + gradleVersion = '5.3.1' +} + +repositories { + jcenter() +} + +dependencies { + + compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.10' + testImplementation('junit:junit:4.13') + testRuntime('junit:junit:4.13') +} +test { + useJUnit() +} + diff --git a/gradle/gradle-employee-app/src/main/java/employee/Employee.java b/gradle/gradle-employee-app/src/main/java/employee/Employee.java new file mode 100644 index 0000000000..6940c8c28c --- /dev/null +++ b/gradle/gradle-employee-app/src/main/java/employee/Employee.java @@ -0,0 +1,9 @@ +package employee; + +public class Employee { + + String name; + String emailAddress; + int yearOfBirth; + +} \ No newline at end of file diff --git a/gradle/gradle-employee-app/src/main/java/employee/EmployeeApp.java b/gradle/gradle-employee-app/src/main/java/employee/EmployeeApp.java new file mode 100644 index 0000000000..48ef9f5d61 --- /dev/null +++ b/gradle/gradle-employee-app/src/main/java/employee/EmployeeApp.java @@ -0,0 +1,16 @@ +package employee; + +public class EmployeeApp { + + public static void main(String[] args){ + + Employee employee = new Employee(); + employee.name = "John"; + employee.emailAddress = "john@baeldung.com"; + employee.yearOfBirth = 1978; + System.out.println("Name: " + employee.name); + System.out.println("Email Address: " + employee.emailAddress); + System.out.println("Year Of Birth:" + employee.yearOfBirth); + } + +} diff --git a/gradle/gradle-employee-app/src/test/java/employee/EmployeeAppTest.java b/gradle/gradle-employee-app/src/test/java/employee/EmployeeAppTest.java new file mode 100644 index 0000000000..013bcc35b6 --- /dev/null +++ b/gradle/gradle-employee-app/src/test/java/employee/EmployeeAppTest.java @@ -0,0 +1,31 @@ +package employee; + +import employee.Employee; +import org.junit.*; +import static org.junit.Assert.*; + +public class EmployeeAppTest { + + @Test + public void testData(){ + + Employee testEmp = this.getEmployeeTest(); + + assertEquals(testEmp.name, "John"); + assertEquals(testEmp.emailAddress, "john@baeldung.com"); + assertEquals(testEmp.yearOfBirth, 1978); + + + } + + private Employee getEmployeeTest(){ + + Employee employee = new Employee(); + employee.name = "John"; + employee.emailAddress = "john@baeldung.com"; + employee.yearOfBirth = 1978; + + return employee; + } + +} \ No newline at end of file diff --git a/gradle/settings.gradle b/gradle/settings.gradle index f1d64de58a..59300f9281 100644 --- a/gradle/settings.gradle +++ b/gradle/settings.gradle @@ -1,10 +1,10 @@ rootProject.name = 'gradletutorial' - include 'greeting-library' include 'greeting-library-java' include 'greeter' include 'gradletaskdemo' include 'junit5' +include 'gradle-employee-app' println 'This will be executed during the initialization phase.' diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml index 793a02458a..30bfbf555a 100644 --- a/graphql/graphql-java/pom.xml +++ b/graphql/graphql-java/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.graphql graphql-java diff --git a/grpc/pom.xml b/grpc/pom.xml index c7ae111da3..5e1c0bb28b 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 grpc 0.0.1-SNAPSHOT diff --git a/gson/pom.xml b/gson/pom.xml index f2ed5509fa..0de9a6a533 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 gson 0.1-SNAPSHOT diff --git a/guava-collections-map/README.md b/guava-collections-map/README.md index b3ec5e2157..4f8743dcfb 100644 --- a/guava-collections-map/README.md +++ b/guava-collections-map/README.md @@ -9,4 +9,5 @@ This module contains articles about map collections in Guava - [Guide to Guava Multimap](https://www.baeldung.com/guava-multimap) - [Guide to Guava RangeMap](https://www.baeldung.com/guava-rangemap) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [Guide to Guava ClassToInstanceMap](https://www.baeldung.com/guava-class-to-instance-map) \ No newline at end of file +- [Guide to Guava ClassToInstanceMap](https://www.baeldung.com/guava-class-to-instance-map) +- [Using Guava’s MapMaker](https://www.baeldung.com/guava-mapmaker) diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java new file mode 100644 index 0000000000..165c5a9f8f --- /dev/null +++ b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java @@ -0,0 +1,20 @@ +package com.baeldung.guava.mapmaker; + +public class Profile { + private long id; + private String type; + + public Profile(long id, String type) { + this.id = id; + this.type = type; + } + + public long getId() { + return id; + } + + public String getName() { + return type; + } + +} diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java new file mode 100644 index 0000000000..a614f431f8 --- /dev/null +++ b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java @@ -0,0 +1,13 @@ +package com.baeldung.guava.mapmaker; + +public class Session { + private long id; + + public Session(long id) { + this.id = id; + } + + public long getId() { + return id; + } +} diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java new file mode 100644 index 0000000000..a7f0435049 --- /dev/null +++ b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java @@ -0,0 +1,20 @@ +package com.baeldung.guava.mapmaker; + +public class User { + private long id; + private String name; + + public User(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + +} diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java new file mode 100644 index 0000000000..754e3ac099 --- /dev/null +++ b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.guava.mapmaker; + +import com.google.common.collect.MapMaker; +import org.junit.Assert; +import org.junit.Test; + +import java.util.concurrent.ConcurrentMap; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertNotNull; + +public class GuavaMapMakerUnitTest { + @Test + public void whenCreateCaches_thenCreated() { + ConcurrentMap sessionCache = new MapMaker().makeMap(); + assertNotNull(sessionCache); + + ConcurrentMap profileCache = new MapMaker().makeMap(); + assertNotNull(profileCache); + + User userA = new User(1, "UserA"); + + sessionCache.put(userA, new Session(100)); + Assert.assertThat(sessionCache.size(), equalTo(1)); + + profileCache.put(userA, new Profile(1000, "Personal")); + Assert.assertThat(profileCache.size(), equalTo(1)); + } + + @Test + public void whenCreateCacheWithInitialCapacity_thenCreated() { + ConcurrentMap profileCache = new MapMaker().initialCapacity(100).makeMap(); + assertNotNull(profileCache); + } + + @Test + public void whenCreateCacheWithConcurrencyLevel_thenCreated() { + ConcurrentMap sessionCache = new MapMaker().concurrencyLevel(10).makeMap(); + assertNotNull(sessionCache); + } + + @Test + public void whenCreateCacheWithWeakKeys_thenCreated() { + ConcurrentMap sessionCache = new MapMaker().weakKeys().makeMap(); + assertNotNull(sessionCache); + } + + @Test + public void whenCreateCacheWithWeakValues_thenCreated() { + ConcurrentMap profileCache = new MapMaker().weakValues().makeMap(); + assertNotNull(profileCache); + } +} diff --git a/guava-collections/pom.xml b/guava-collections/pom.xml index 9002ac2b91..c6019362c5 100644 --- a/guava-collections/pom.xml +++ b/guava-collections/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 guava-collections 0.1.0-SNAPSHOT diff --git a/guava/README.md b/guava/README.md index c67a3604ea..9c650dbc1d 100644 --- a/guava/README.md +++ b/guava/README.md @@ -12,4 +12,5 @@ This module contains articles a Google Guava - [Guide to Mathematical Utilities in Guava](https://www.baeldung.com/guava-math) - [Bloom Filter in Java using Guava](https://www.baeldung.com/guava-bloom-filter) - [Quick Guide to the Guava RateLimiter](https://www.baeldung.com/guava-rate-limiter) - +- [Introduction to Guava Throwables](https://www.baeldung.com/guava-throwables) +- [Guava Cache](https://www.baeldung.com/guava-cache) diff --git a/guava/pom.xml b/guava/pom.xml index 3f07b77b0b..df6d57bd09 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 guava 0.1.0-SNAPSHOT diff --git a/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java b/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java new file mode 100644 index 0000000000..7d33b38a0e --- /dev/null +++ b/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.guava; + +import com.google.common.base.Throwables; +import org.junit.Test; + +import java.util.function.Supplier; + +public class ThrowablesUnitTest { + + @Test(expected = RuntimeException.class) + public void whenThrowable_shouldWrapItInRuntimeException() throws Exception { + try { + throwThrowable(Throwable::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + @Test(expected = Error.class) + public void whenError_shouldPropagateAsIs() throws Exception { + try { + throwThrowable(Error::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + @Test(expected = Exception.class) + public void whenException_shouldPropagateAsIs() throws Exception { + try { + throwThrowable(Exception::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + private void throwThrowable(Supplier exceptionSupplier) throws Throwable { + throw exceptionSupplier.get(); + } + +} diff --git a/guice/pom.xml b/guice/pom.xml index d119bbf78e..6bbad6dddc 100644 --- a/guice/pom.xml +++ b/guice/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.examples.guice guice diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml index 10234bb81f..287542be33 100644 --- a/hazelcast/pom.xml +++ b/hazelcast/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 hazelcast 0.0.1-SNAPSHOT @@ -32,7 +34,7 @@ - + 0.6 diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 8c505c9104..1cf8713b91 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java index a264dd52f2..924ec1162f 100644 --- a/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java +++ b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.jackson.date; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -8,6 +9,8 @@ import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; import java.util.Date; import java.util.TimeZone; @@ -30,7 +33,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; public class JacksonDateUnitTest { @Test - public void whenSerializingDateWithJackson_thenSerializedToNumber() throws JsonProcessingException, ParseException { + public void whenSerializingDateWithJackson_thenSerializedToTimestamp() throws JsonProcessingException, ParseException { final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); df.setTimeZone(TimeZone.getTimeZone("UTC")); @@ -61,6 +64,21 @@ public class JacksonDateUnitTest { final String result = mapper.writeValueAsString(event); assertThat(result, containsString("1970-01-01T02:30:00.000+00:00")); } + + @Test + public void whenDeserialisingZonedDateTimeWithDefaults_thenNotCorrect() + throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC")); + String converted = objectMapper.writeValueAsString(now); + + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(restored)); + } @Test public void whenSettingObjectMapperDateFormat_thenCorrect() throws JsonProcessingException, ParseException { diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml new file mode 100644 index 0000000000..3888623a7f --- /dev/null +++ b/java-collections-maps-3/pom.xml @@ -0,0 +1,43 @@ + + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + 4.0.0 + java-collections-maps-3 + 0.1.0-SNAPSHOT + java-collections-maps-3 + jar + + + + org.springframework + spring-core + ${spring.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + + + 4.1 + 3.6.1 + 5.2.5.RELEASE + + diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java new file mode 100644 index 0000000000..833807c692 --- /dev/null +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -0,0 +1,94 @@ +package com.baeldung.map.caseinsensitivekeys; + +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.junit.Test; +import org.springframework.util.LinkedCaseInsensitiveMap; +import java.util.Map; +import java.util.TreeMap; +import static org.junit.Assert.*; + +public class CaseInsensitiveMapUnitTest { + @Test + public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + assertEquals(1, treeMap.size()); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + Map commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(1, commonsHashMap.size()); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + assertEquals(1, linkedHashMap.size()); + } + + @Test + public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + assertEquals(2, treeMap.get("aBc").intValue()); + assertEquals(2, treeMap.get("ABc").intValue()); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + Map commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(2, commonsHashMap.get("aBc").intValue()); + assertEquals(2, commonsHashMap.get("ABc").intValue()); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + assertEquals(2, linkedHashMap.get("aBc").intValue()); + assertEquals(2, linkedHashMap.get("ABc").intValue()); + } + + @Test + public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 3); + treeMap.remove("aBC"); + + assertEquals(0, treeMap.size()); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + Map commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 3); + commonsHashMap.remove("aBC"); + + assertEquals(0, commonsHashMap.size()); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 3); + linkedHashMap.remove("aBC"); + + assertEquals(0, linkedHashMap.size()); + } +} diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml index a2d9443d67..f8d19b5750 100644 --- a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml +++ b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 app-auth-form-store-ldap app-auth-form-store-ldap @@ -12,10 +13,6 @@ java-ee-8-security-api 1.0-SNAPSHOT - - - 4.0.4 - @@ -52,4 +49,8 @@ + + 4.0.4 + + diff --git a/java-math-2/README.md b/java-math-2/README.md deleted file mode 100644 index ca809e8623..0000000000 --- a/java-math-2/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Java Math - -This module contains articles about math in Java. - -### Relevant articles: - -- [Basic Calculator in Java](https://www.baeldung.com/basic-calculator-in-java) -- More articles: [[<-- prev]](/../java-math) diff --git a/java-numbers-2/README.md b/java-numbers-2/README.md index ba9e14965d..1d996e32cc 100644 --- a/java-numbers-2/README.md +++ b/java-numbers-2/README.md @@ -13,7 +13,4 @@ This module contains articles about numbers in Java. - [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers) - [Finding the Least Common Multiple in Java](https://www.baeldung.com/java-least-common-multiple) - [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers) -- [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers-in-range) -- [Listing Numbers Within a Range in Java](https://www.baeldung.com/java-listing-numbers-within-a-range) -- [Fibonacci Series in Java](https://www.baeldung.com/java-fibonacci) -- More articles: [[<-- prev]](/../java-numbers) +- More articles: [[<-- prev]](/java-numbers) [[next -->]](/java-numbers-3) diff --git a/java-numbers-3/README.md b/java-numbers-3/README.md index 835b8b0b54..f818bdb675 100644 --- a/java-numbers-3/README.md +++ b/java-numbers-3/README.md @@ -1,5 +1,14 @@ +## Java Number Cookbooks and Examples + +This module contains articles about numbers in Java. + ### Relevant Articles: - [Generating Random Numbers](https://www.baeldung.com/java-generating-random-numbers) - [Convert Double to Long in Java](https://www.baeldung.com/java-convert-double-long) - [Check for null Before Calling Parse in Double.parseDouble](https://www.baeldung.com/java-check-null-parse-double) +- [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers-in-range) +- [Listing Numbers Within a Range in Java](https://www.baeldung.com/java-listing-numbers-within-a-range) +- [Fibonacci Series in Java](https://www.baeldung.com/java-fibonacci) +- [Guide to the Number Class in Java](https://www.baeldung.com/java-number-class) +- More articles: [[<-- prev]](/java-numbers-2) diff --git a/java-numbers-2/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java b/java-numbers-3/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java similarity index 96% rename from java-numbers-2/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java rename to java-numbers-3/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java index 943fcffa56..616f3ab28f 100644 --- a/java-numbers-2/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java +++ b/java-numbers-3/src/main/java/com/baeldung/fibonacci/FibonacciSeriesUtils.java @@ -1,7 +1,5 @@ package com.baeldung.fibonacci; -import static java.lang.Math.pow; - public class FibonacciSeriesUtils { public static int nthFibonacciTermRecursiveMethod(int n) { diff --git a/java-numbers-2/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java b/java-numbers-3/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java similarity index 100% rename from java-numbers-2/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java rename to java-numbers-3/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java diff --git a/java-numbers-2/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java b/java-numbers-3/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java similarity index 100% rename from java-numbers-2/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java rename to java-numbers-3/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java diff --git a/java-numbers-3/src/test/java/com/baeldung/abstractnumber/AbstractNumberUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/abstractnumber/AbstractNumberUnitTest.java new file mode 100644 index 0000000000..521f2d37a6 --- /dev/null +++ b/java-numbers-3/src/test/java/com/baeldung/abstractnumber/AbstractNumberUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.abstractnumber; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class AbstractNumberUnitTest { + + private final static double DOUBLE_VALUE = 9999.999; + private final static float FLOAT_VALUE = 101.99F; + private final static long LONG_VALUE = 1000L; + private final static int INTEGER_VALUE = 100; + private final static short SHORT_VALUE = 127; + private final static byte BYTE_VALUE = 120; + + @Test + public void givenDoubleValue_whenShortValueUsed_thenShortValueReturned() { + Double doubleValue = Double.valueOf(DOUBLE_VALUE); + assertEquals(9999, doubleValue.shortValue()); + } + + @Test + public void givenFloatValue_whenByteValueUsed_thenByteValueReturned() { + Float floatValue = Float.valueOf(FLOAT_VALUE); + assertEquals(101, floatValue.byteValue()); + } + + @Test + public void givenLongValue_whenInitValueUsed_thenInitValueReturned() { + Long longValue = Long.valueOf(LONG_VALUE); + assertEquals(1000, longValue.intValue()); + } + + @Test + public void givenIntegerValue_whenLongValueUsed_thenLongValueReturned() { + Integer integerValue = Integer.valueOf(INTEGER_VALUE); + assertEquals(100, integerValue.longValue()); + } + + @Test + public void givenShortValue_whenFloatValueUsed_thenFloatValueReturned() { + Short shortValue = Short.valueOf(SHORT_VALUE); + assertEquals(127.0F, shortValue.floatValue(), 0); + } + + @Test + public void givenByteValue_whenDoubleValueUsed_thenDoubleValueReturned() { + Byte byteValue = Byte.valueOf(BYTE_VALUE); + assertEquals(120.0, byteValue.doubleValue(), 0); + } + +} diff --git a/java-numbers-2/src/test/java/com/baeldung/fibonacci/FibonacciSeriesUtilsUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/fibonacci/FibonacciSeriesUtilsUnitTest.java similarity index 100% rename from java-numbers-2/src/test/java/com/baeldung/fibonacci/FibonacciSeriesUtilsUnitTest.java rename to java-numbers-3/src/test/java/com/baeldung/fibonacci/FibonacciSeriesUtilsUnitTest.java diff --git a/java-numbers-2/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java similarity index 100% rename from java-numbers-2/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java rename to java-numbers-3/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java diff --git a/java-numbers-2/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java similarity index 100% rename from java-numbers-2/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java rename to java-numbers-3/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java diff --git a/java-numbers/README.md b/java-numbers/README.md index eee6fceab1..f4b76c3c98 100644 --- a/java-numbers/README.md +++ b/java-numbers/README.md @@ -8,9 +8,9 @@ This module contains articles about numbers in Java. - [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger) - [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum) - [Java – Random Long, Float, Integer and Double](http://www.baeldung.com/java-generate-random-long-float-integer-double) -- [Using Math.sin with Degrees](https://www.baeldung.com/java-math-sin-degrees) - [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat) - [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root) - [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string) - [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order) +- [Using Math.sin with Degrees](https://www.baeldung.com/java-math-sin-degrees) - More articles: [[next -->]](/../java-numbers-2) diff --git a/jee-7/pom.xml b/jee-7/pom.xml index a2593e46a5..9077aae1a6 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -242,6 +242,28 @@ + + + org.codehaus.mojo + jaxws-maven-plugin + 2.6 + + + wsimport-from-jdk + + wsimport + + + + + + http://localhost:8888/ws/country?wsdl + + true + com.baeldung.soap.ws.client.generated + src/main/java + + diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Country.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Country.java new file mode 100644 index 0000000000..6a810b9afa --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Country.java @@ -0,0 +1,129 @@ + +package com.baeldung.soap.ws.client.generated; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; + +/** + *

Java class for country complex type. + * + *

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

+ * <complexType name="country">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="capital" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *         <element name="currency" type="{http://server.ws.soap.baeldung.com/}currency" minOccurs="0"/>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *         <element name="population" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "country", propOrder = { "capital", "currency", "name", "population" }) +public class Country { + + protected String capital; + @XmlSchemaType(name = "string") + protected Currency currency; + protected String name; + protected int population; + + /** + * Gets the value of the capital property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCapital() { + return capital; + } + + /** + * Sets the value of the capital property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCapital(String value) { + this.capital = value; + } + + /** + * Gets the value of the currency property. + * + * @return + * possible object is + * {@link Currency } + * + */ + public Currency getCurrency() { + return currency; + } + + /** + * Sets the value of the currency property. + * + * @param value + * allowed object is + * {@link Currency } + * + */ + public void setCurrency(Currency value) { + this.currency = value; + } + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the population property. + * + */ + public int getPopulation() { + return population; + } + + /** + * Sets the value of the population property. + * + */ + public void setPopulation(int value) { + this.population = value; + } + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryService.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryService.java new file mode 100644 index 0000000000..bda4a305a5 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryService.java @@ -0,0 +1,34 @@ + +package com.baeldung.soap.ws.client.generated; + +import javax.jws.WebMethod; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.jws.soap.SOAPBinding; +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.ws.Action; + +/** + * This class was generated by the JAX-WS RI. + * JAX-WS RI 2.3.2 + * Generated source version: 2.2 + * + */ +@WebService(name = "CountryService", targetNamespace = "http://server.ws.soap.baeldung.com/") +@SOAPBinding(style = SOAPBinding.Style.RPC) +@XmlSeeAlso({ ObjectFactory.class }) +public interface CountryService { + + /** + * + * @param arg0 + * @return + * returns com.baeldung.soap.ws.client.generated.Country + */ + @WebMethod + @WebResult(partName = "return") + @Action(input = "http://server.ws.soap.baeldung.com/CountryService/findByNameRequest", output = "http://server.ws.soap.baeldung.com/CountryService/findByNameResponse") + public Country findByName(@WebParam(name = "arg0", partName = "arg0") String arg0); + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryServiceImplService.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryServiceImplService.java new file mode 100644 index 0000000000..a6983938f5 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/CountryServiceImplService.java @@ -0,0 +1,91 @@ + +package com.baeldung.soap.ws.client.generated; + +import java.net.MalformedURLException; +import java.net.URL; +import javax.xml.namespace.QName; +import javax.xml.ws.Service; +import javax.xml.ws.WebEndpoint; +import javax.xml.ws.WebServiceClient; +import javax.xml.ws.WebServiceException; +import javax.xml.ws.WebServiceFeature; + +/** + * This class was generated by the JAX-WS RI. + * JAX-WS RI 2.2.9-b130926.1035 + * Generated source version: 2.2 + * + */ +@WebServiceClient(name = "CountryServiceImplService", targetNamespace = "http://server.ws.soap.baeldung.com/", wsdlLocation = "http://localhost:8888/ws/country?wsdl") +public class CountryServiceImplService extends Service { + + private final static URL COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION; + private final static WebServiceException COUNTRYSERVICEIMPLSERVICE_EXCEPTION; + private final static QName COUNTRYSERVICEIMPLSERVICE_QNAME = new QName("http://server.ws.soap.baeldung.com/", "CountryServiceImplService"); + + static { + URL url = null; + WebServiceException e = null; + try { + url = new URL("http://localhost:8888/ws/country?wsdl"); + } catch (MalformedURLException ex) { + e = new WebServiceException(ex); + } + COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION = url; + COUNTRYSERVICEIMPLSERVICE_EXCEPTION = e; + } + + public CountryServiceImplService() { + super(__getWsdlLocation(), COUNTRYSERVICEIMPLSERVICE_QNAME); + } + + public CountryServiceImplService(WebServiceFeature... features) { + super(__getWsdlLocation(), COUNTRYSERVICEIMPLSERVICE_QNAME, features); + } + + public CountryServiceImplService(URL wsdlLocation) { + super(wsdlLocation, COUNTRYSERVICEIMPLSERVICE_QNAME); + } + + public CountryServiceImplService(URL wsdlLocation, WebServiceFeature... features) { + super(wsdlLocation, COUNTRYSERVICEIMPLSERVICE_QNAME, features); + } + + public CountryServiceImplService(URL wsdlLocation, QName serviceName) { + super(wsdlLocation, serviceName); + } + + public CountryServiceImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { + super(wsdlLocation, serviceName, features); + } + + /** + * + * @return + * returns CountryService + */ + @WebEndpoint(name = "CountryServiceImplPort") + public CountryService getCountryServiceImplPort() { + return super.getPort(new QName("http://server.ws.soap.baeldung.com/", "CountryServiceImplPort"), CountryService.class); + } + + /** + * + * @param features + * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have their default values. + * @return + * returns CountryService + */ + @WebEndpoint(name = "CountryServiceImplPort") + public CountryService getCountryServiceImplPort(WebServiceFeature... features) { + return super.getPort(new QName("http://server.ws.soap.baeldung.com/", "CountryServiceImplPort"), CountryService.class, features); + } + + private static URL __getWsdlLocation() { + if (COUNTRYSERVICEIMPLSERVICE_EXCEPTION != null) { + throw COUNTRYSERVICEIMPLSERVICE_EXCEPTION; + } + return COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION; + } + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Currency.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Currency.java new file mode 100644 index 0000000000..8b9355edc5 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/Currency.java @@ -0,0 +1,37 @@ + +package com.baeldung.soap.ws.client.generated; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + +/** + *

Java class for currency. + * + *

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

+ *

+ * <simpleType name="currency">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="EUR"/>
+ *     <enumeration value="INR"/>
+ *     <enumeration value="USD"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "currency") +@XmlEnum +public enum Currency { + + EUR, INR, USD; + + public String value() { + return name(); + } + + public static Currency fromValue(String v) { + return valueOf(v); + } + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/ObjectFactory.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/ObjectFactory.java new file mode 100644 index 0000000000..241debe758 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/ObjectFactory.java @@ -0,0 +1,38 @@ + +package com.baeldung.soap.ws.client.generated; + +import javax.xml.bind.annotation.XmlRegistry; + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the com.baeldung.soap.ws.client.generated package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.soap.ws.client.generated + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link Country } + * + */ + public Country createCountry() { + return new Country(); + } + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/package-info.java b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/package-info.java new file mode 100644 index 0000000000..6df70b70f1 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/client/generated/package-info.java @@ -0,0 +1,2 @@ +@javax.xml.bind.annotation.XmlSchema(namespace = "http://server.ws.soap.baeldung.com/", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package com.baeldung.soap.ws.client.generated; diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/Country.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/Country.java new file mode 100644 index 0000000000..62ea4a22ed --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/Country.java @@ -0,0 +1,41 @@ +package com.baeldung.soap.ws.server; + +public class Country { + protected String name; + protected int population; + protected String capital; + protected Currency currency; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getPopulation() { + return population; + } + + public void setPopulation(int population) { + this.population = population; + } + + public String getCapital() { + return capital; + } + + public void setCapital(String capital) { + this.capital = capital; + } + + public Currency getCurrency() { + return currency; + } + + public void setCurrency(Currency currency) { + this.currency = currency; + } + +} \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryRepository.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryRepository.java new file mode 100644 index 0000000000..558f7c1293 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryRepository.java @@ -0,0 +1,43 @@ +package com.baeldung.soap.ws.server; + +import java.util.HashMap; +import java.util.Map; + +public class CountryRepository { + + private static final Map countries = new HashMap<>(); + + { + initData(); + } + + private final static void initData() { + Country usa = new Country(); + usa.setName("USA"); + usa.setCapital("Washington D.C."); + usa.setCurrency(Currency.USD); + usa.setPopulation(323947000); + + countries.put(usa.getName(), usa); + + Country india = new Country(); + india.setName("India"); + india.setCapital("New Delhi"); + india.setCurrency(Currency.INR); + india.setPopulation(1295210000); + + countries.put(india.getName(), india); + + Country france = new Country(); + france.setName("France"); + france.setCapital("Paris"); + france.setCurrency(Currency.EUR); + france.setPopulation(66710000); + + countries.put(france.getName(), france); + } + + public Country findCountry(String name) { + return countries.get(name); + } +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryService.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryService.java new file mode 100644 index 0000000000..e3f68a4e59 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryService.java @@ -0,0 +1,15 @@ +package com.baeldung.soap.ws.server; + +import javax.jws.WebMethod; +import javax.jws.WebService; +import javax.jws.soap.SOAPBinding; +import javax.jws.soap.SOAPBinding.Style; + +@WebService +@SOAPBinding(style=Style.RPC) +public interface CountryService { + + @WebMethod + Country findByName(String name); + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServiceImpl.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServiceImpl.java new file mode 100644 index 0000000000..a8c6250354 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServiceImpl.java @@ -0,0 +1,15 @@ +package com.baeldung.soap.ws.server; + +import javax.jws.WebService; + +@WebService(endpointInterface = "com.baeldung.soap.ws.server.CountryService") +public class CountryServiceImpl implements CountryService { + + private CountryRepository countryRepository = new CountryRepository(); + + @Override + public Country findByName(String name) { + return countryRepository.findCountry(name); + } + +} diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServicePublisher.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServicePublisher.java new file mode 100644 index 0000000000..e7c1c480f4 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/CountryServicePublisher.java @@ -0,0 +1,19 @@ +package com.baeldung.soap.ws.server; + +import javax.xml.ws.Endpoint; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class CountryServicePublisher { + + private static final Logger logger = LoggerFactory.getLogger(CountryServicePublisher.class); + + public static void main(String[] args) { + Endpoint endpoint = Endpoint.create(new CountryServiceImpl()); + endpoint.publish("http://localhost:8888/ws/country"); + + logger.info("Country web service ready to consume requests!"); + } +} \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/soap/ws/server/Currency.java b/jee-7/src/main/java/com/baeldung/soap/ws/server/Currency.java new file mode 100644 index 0000000000..d1b25a26c6 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/soap/ws/server/Currency.java @@ -0,0 +1,15 @@ +package com.baeldung.soap.ws.server; + +public enum Currency { + + EUR, INR, USD; + + public String value() { + return name(); + } + + public static Currency fromValue(String v) { + return valueOf(v); + } + +} diff --git a/jee-7/src/main/resources/country.xsd b/jee-7/src/main/resources/country.xsd new file mode 100644 index 0000000000..c94b6047f9 --- /dev/null +++ b/jee-7/src/main/resources/country.xsd @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java index 744bdfc8f5..c607efeb24 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java @@ -1,20 +1,17 @@ package com.baeldung.batch.understanding; -import static org.junit.jupiter.api.Assertions.*; -import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Properties; + import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; -import javax.batch.runtime.Metric; import javax.batch.runtime.StepExecution; -import com.baeldung.batch.understanding.BatchTestHelper; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Disabled; -@Disabled("Should be fixed in BAEL-3812") class CustomCheckPointUnitTest { @Test public void givenChunk_whenCustomCheckPoint_thenCommitCountIsThree() throws Exception { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java index 88b981df92..4b27e5f5ec 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.batch.understanding; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; @@ -13,9 +15,7 @@ import javax.batch.runtime.JobExecution; import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Disabled; -@Disabled("Should be fixed in BAEL-3812") class JobSequenceUnitTest { @Test public void givenTwoSteps_thenBatch_CompleteWithSuccess() throws Exception { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java index 3babf9b5aa..788b75eb3e 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java @@ -1,17 +1,16 @@ package com.baeldung.batch.understanding; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Properties; import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; -import java.util.Properties; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; -@Disabled("Should be fixed in BAEL-3812") class SimpleBatchLetUnitTest { @Test public void givenBatchLet_thenBatch_CompleteWithSuccess() throws Exception { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java index 5871143fa3..9010c365a2 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.batch.understanding; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Map; @@ -14,9 +15,7 @@ import javax.batch.runtime.Metric; import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Disabled; -@Disabled("Should be fixed in BAEL-3812") class SimpleChunkUnitTest { @Test public void givenChunk_thenBatch_CompletesWithSucess() throws Exception { diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java index c53561a0c0..bc410aec8d 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java @@ -1,19 +1,18 @@ package com.baeldung.batch.understanding; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import static org.junit.Assert.assertEquals; + +import java.util.List; +import java.util.Properties; import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; import javax.batch.runtime.StepExecution; -import java.util.List; -import java.util.Properties; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -@Disabled("Should be fixed in BAEL-3812") class SimpleErrorChunkUnitTest { @Test diff --git a/jee-7/src/test/java/com/baeldung/soap/ws/client/CountryClientLiveTest.java b/jee-7/src/test/java/com/baeldung/soap/ws/client/CountryClientLiveTest.java new file mode 100644 index 0000000000..ae423f9bdd --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/soap/ws/client/CountryClientLiveTest.java @@ -0,0 +1,39 @@ +package com.baeldung.soap.ws.client; + +import static org.junit.Assert.assertEquals; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.soap.ws.client.generated.CountryService; +import com.baeldung.soap.ws.client.generated.CountryServiceImplService; +import com.baeldung.soap.ws.client.generated.Currency; + +//Ensure that com.baeldung.soap.ws.server.CountryServicePublisher is running before executing this test +public class CountryClientLiveTest { + + private static CountryService countryService; + + @BeforeClass + public static void setup() { + CountryServiceImplService service = new CountryServiceImplService(); + countryService = service.getCountryServiceImplPort(); + } + + @Test + public void givenCountryService_whenCountryIndia_thenCapitalIsNewDelhi() { + assertEquals("New Delhi", countryService.findByName("India").getCapital()); + } + + @Test + public void givenCountryService_whenCountryFrance_thenPopulationCorrect() { + assertEquals(66710000, countryService.findByName("France").getPopulation()); + } + + @Test + public void givenCountryService_whenCountryUSA_thenCurrencyUSD() { + assertEquals(Currency.USD, countryService.findByName("USA").getCurrency()); + } + + +} diff --git a/jee-7/src/test/resources/jberet.properties b/jee-7/src/test/resources/jberet.properties new file mode 100644 index 0000000000..e8b9907de5 --- /dev/null +++ b/jee-7/src/test/resources/jberet.properties @@ -0,0 +1 @@ +db-url=jdbc:h2:mem:jberet-repo;DB_CLOSE_DELAY=-1 \ No newline at end of file diff --git a/jgit/pom.xml b/jgit/pom.xml index eef3c9b8e8..d960843868 100644 --- a/jgit/pom.xml +++ b/jgit/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - JGit + jgit 1.0-SNAPSHOT - JGit + jgit jar http://maven.apache.org diff --git a/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java similarity index 67% rename from jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java rename to jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java index ad34890996..bcfe615bc7 100644 --- a/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java +++ b/jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java @@ -10,10 +10,18 @@ import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertNotNull; -/** - * Tests which show issues with JGit that we reported upstream. - */ -public class JGitBugIntegrationTest { +public class JGitBugManualTest { + + /** + * This test case expects one git repository to be present in local file system. + * Currently this test uses the Baeldung repository i.e. the current checkout repository. + * It finds the repository by tracking back and scan file system to find .git folder in + * the file system. + * + * Before running the test case ensure that the .git folder is present. + * + * @throws IOException + */ @Test public void testRevWalkDisposeClosesReader() throws IOException { try (Repository repo = Helper.openJGitRepository()) { diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index 5eaf761921..233765e0f3 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -7,7 +7,7 @@ 0.0.1-SNAPSHOT war Bookstore - + jhipster-5 com.baeldung.jhipster @@ -982,7 +982,7 @@ com.github.eirslett - frontend-maven-plugin + frontend-maven-plugin ${frontend-maven-plugin.version} install-node-and-npm diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java index cd6a326c06..cd49135d63 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java @@ -26,7 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class UserMapperUnitTest { +public class UserMapperIntegrationTest { private static final String DEFAULT_LOGIN = "johndoe"; diff --git a/jhipster-5/pom.xml b/jhipster-5/pom.xml index cebbe25d8b..2a5132e50e 100644 --- a/jhipster-5/pom.xml +++ b/jhipster-5/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 073f12a922..aa238fafb5 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -30,6 +30,11 @@ org.springframework.boot spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + io.jsonwebtoken diff --git a/jmeter/pom.xml b/jmeter/pom.xml index 64642695ff..945210edd7 100644 --- a/jmeter/pom.xml +++ b/jmeter/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/jws/pom.xml b/jws/pom.xml index e6ab7e05ec..be42798fd1 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -14,26 +14,6 @@ 1.0.0-SNAPSHOT - - - OpenNMS Repository - http://repo.opennms.org/maven2/ - - - - - - javax.samples.jnlp - jnlp-servlet - ${jnlp-servlet.version} - - - javax.samples.jnlp - jnlp-jardiff - ${jnlp-jardiff.version} - - - ${project.artifactId} @@ -84,8 +64,6 @@ 3.0.2 - 1.6.0 - 1.6.0 diff --git a/kaniko/dockerfile b/kaniko/dockerfile new file mode 100644 index 0000000000..0290bf16ed --- /dev/null +++ b/kaniko/dockerfile @@ -0,0 +1,2 @@ +FROM ubuntu +ENTRYPOINT ["/bin/bash", "-c", "echo hello"] diff --git a/kaniko/pod.yaml b/kaniko/pod.yaml new file mode 100644 index 0000000000..17f9a81b6d --- /dev/null +++ b/kaniko/pod.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Pod +metadata: + name: kaniko +spec: + containers: + - name: kaniko + image: gcr.io/kaniko-project/executor:latest + args: ["--dockerfile=/workspace/dockerfile", + "--context=dir://workspace", + "--no-push"] + volumeMounts: + - name: dockerfile-storage + mountPath: /workspace + restartPolicy: Never + volumes: + - name: dockerfile-storage + persistentVolumeClaim: + claimName: dockerfile-claim diff --git a/kaniko/volume-claim.yaml b/kaniko/volume-claim.yaml new file mode 100644 index 0000000000..7a1abbf05c --- /dev/null +++ b/kaniko/volume-claim.yaml @@ -0,0 +1,11 @@ +kind: PersistentVolumeClaim +apiVersion: v1 +metadata: + name: dockerfile-claim +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 8Gi + storageClassName: local-storage diff --git a/kaniko/volume.yaml b/kaniko/volume.yaml new file mode 100644 index 0000000000..e44663ec5a --- /dev/null +++ b/kaniko/volume.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: PersistentVolume +metadata: + name: dockerfile + labels: + type: local +spec: + capacity: + storage: 10Gi + accessModes: + - ReadWriteOnce + storageClassName: local-storage + hostPath: + path: /home/docker/kaniko # Path to the local mount directory that was setup diff --git a/lagom/build.sbt b/lagom/build.sbt index 06927e3301..19aeccbd07 100644 --- a/lagom/build.sbt +++ b/lagom/build.sbt @@ -1,4 +1,4 @@ -organization in ThisBuild := "org.baeldung" +organization in ThisBuild := "com.baeldung" // the Scala version that will be used for cross-compiled libraries scalaVersion in ThisBuild := "2.11.8" diff --git a/lagom/greeting-api/src/main/java/org/baeldung/lagom/helloworld/greeting/api/GreetingService.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java similarity index 93% rename from lagom/greeting-api/src/main/java/org/baeldung/lagom/helloworld/greeting/api/GreetingService.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java index 93567f0185..e212c45437 100644 --- a/lagom/greeting-api/src/main/java/org/baeldung/lagom/helloworld/greeting/api/GreetingService.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.api; +package com.baeldung.lagom.helloworld.greeting.api; import static com.lightbend.lagom.javadsl.api.Service.named; import static com.lightbend.lagom.javadsl.api.Service.restCall; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java similarity index 94% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java index be9e713ec9..30d3930b75 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java similarity index 85% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java index 91fc74039d..125cf4bf38 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java @@ -1,9 +1,9 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import java.util.Optional; -import org.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; -import org.baeldung.lagom.helloworld.greeting.impl.GreetingEvent.ReceivedGreetingEvent; +import com.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; +import com.baeldung.lagom.helloworld.greeting.impl.GreetingEvent.ReceivedGreetingEvent; import com.lightbend.lagom.javadsl.persistence.PersistentEntity; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java similarity index 90% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java index e454f6cd1b..8800177add 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.lightbend.lagom.serialization.Jsonable; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java similarity index 85% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java index c28687291e..0c79b0d468 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java @@ -1,12 +1,12 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import org.baeldung.lagom.helloworld.greeting.api.GreetingService; -import org.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; -import org.baeldung.lagom.helloworld.weather.api.WeatherStats; +import com.baeldung.lagom.helloworld.greeting.api.GreetingService; +import com.baeldung.lagom.helloworld.greeting.impl.GreetingCommand.ReceivedGreetingCommand; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.weather.api.WeatherStats; import com.google.inject.Inject; import com.lightbend.lagom.javadsl.api.ServiceCall; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java similarity index 72% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java index 4813e91a7c..ba5142a5e6 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java @@ -1,7 +1,7 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; -import org.baeldung.lagom.helloworld.greeting.api.GreetingService; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.greeting.api.GreetingService; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; import com.google.inject.AbstractModule; import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; diff --git a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingState.java b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java similarity index 89% rename from lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingState.java rename to lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java index 125795601e..023c0510ae 100644 --- a/lagom/greeting-impl/src/main/java/org/baeldung/lagom/helloworld/greeting/impl/GreetingState.java +++ b/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.greeting.impl; +package com.baeldung.lagom.helloworld.greeting.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; diff --git a/lagom/greeting-impl/bin/application.conf b/lagom/greeting-impl/bin/application.conf index 1e78ce4a79..3fd21ae72b 100644 --- a/lagom/greeting-impl/bin/application.conf +++ b/lagom/greeting-impl/bin/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/greeting-impl/bin/classes/application.conf b/lagom/greeting-impl/bin/classes/application.conf index 1e78ce4a79..3fd21ae72b 100644 --- a/lagom/greeting-impl/bin/classes/application.conf +++ b/lagom/greeting-impl/bin/classes/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/greeting-impl/src/main/resources/application.conf b/lagom/greeting-impl/src/main/resources/application.conf index 1e78ce4a79..3fd21ae72b 100644 --- a/lagom/greeting-impl/src/main/resources/application.conf +++ b/lagom/greeting-impl/src/main/resources/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherService.java b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java similarity index 93% rename from lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherService.java rename to lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java index 888109322b..a0749222eb 100644 --- a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherService.java +++ b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.weather.api; +package com.baeldung.lagom.helloworld.weather.api; import static com.lightbend.lagom.javadsl.api.Service.named; import static com.lightbend.lagom.javadsl.api.Service.*; diff --git a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherStats.java b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java similarity index 93% rename from lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherStats.java rename to lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java index 23530a297d..aa04c5ad86 100644 --- a/lagom/weather-api/src/main/java/org/baeldung/lagom/helloworld/weather/api/WeatherStats.java +++ b/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java @@ -1,4 +1,4 @@ -package org.baeldung.lagom.helloworld.weather.api; +package com.baeldung.lagom.helloworld.weather.api; import java.util.Arrays; import java.util.Collections; diff --git a/lagom/weather-impl/bin/application.conf b/lagom/weather-impl/bin/application.conf index cf6cec2115..53d2dff8f2 100644 --- a/lagom/weather-impl/bin/application.conf +++ b/lagom/weather-impl/bin/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file diff --git a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java similarity index 67% rename from lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java rename to lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java index d7f97f9105..38e4b4d28f 100644 --- a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java +++ b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java @@ -1,9 +1,9 @@ -package org.baeldung.lagom.helloworld.weather.impl; +package com.baeldung.lagom.helloworld.weather.impl; import java.util.concurrent.CompletableFuture; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; -import org.baeldung.lagom.helloworld.weather.api.WeatherStats; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.weather.api.WeatherStats; import com.lightbend.lagom.javadsl.api.ServiceCall; diff --git a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java similarity index 78% rename from lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java rename to lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java index ac2834ff5c..85257ffa47 100644 --- a/lagom/weather-impl/src/main/java/org/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java +++ b/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java @@ -1,6 +1,6 @@ -package org.baeldung.lagom.helloworld.weather.impl; +package com.baeldung.lagom.helloworld.weather.impl; -import org.baeldung.lagom.helloworld.weather.api.WeatherService; +import com.baeldung.lagom.helloworld.weather.api.WeatherService; import com.google.inject.AbstractModule; import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; diff --git a/lagom/weather-impl/src/main/resources/application.conf b/lagom/weather-impl/src/main/resources/application.conf index cf6cec2115..53d2dff8f2 100644 --- a/lagom/weather-impl/src/main/resources/application.conf +++ b/lagom/weather-impl/src/main/resources/application.conf @@ -1 +1 @@ -play.modules.enabled += org.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file +play.modules.enabled += com.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file diff --git a/libraries-2/README.md b/libraries-2/README.md index eb45a3e426..edf513c6ee 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -14,11 +14,9 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [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) - [Key Value Store with Chronicle Map](https://www.baeldung.com/java-chronicle-map) - [Guide to MapDB](https://www.baeldung.com/mapdb) - [A Guide to Apache Mesos](https://www.baeldung.com/apache-mesos) - [JasperReports with Spring](https://www.baeldung.com/spring-jasper) -- [Jetty ReactiveStreams HTTP Client](https://www.baeldung.com/jetty-reactivestreams-http-client) - More articles [[<-- prev]](/libraries) diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 474ff563c2..3aa36c3f90 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -75,28 +75,7 @@ - - - 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 @@ -151,9 +130,6 @@ 2.1.4.RELEASE 0.28.3 1.1.0 - 3.14.2 - 2.8.5 - 3.14.2 4.1.2 6.6.0 5.1.9.RELEASE diff --git a/libraries-3/README.md b/libraries-3/README.md index 4b04edd818..922ce1bd1a 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -15,3 +15,6 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - [Introduction to the jcabi-aspects AOP Annotations Library](https://www.baeldung.com/java-jcabi-aspects) - [Introduction to Takes](https://www.baeldung.com/java-takes) +- [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) +- [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro) +- [Quick Guide to Spring Cloud Circuit Breaker](https://www.baeldung.com/spring-cloud-circuit-breaker) diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index 1286221223..a72dbcba50 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 + parent-modules + 1.0.0-SNAPSHOT @@ -24,39 +23,6 @@ lombok ${lombok.version} - - org.springframework.boot - spring-boot-starter-web - - - - net.sourceforge.barbecue - barbecue - ${barbecue.version} - - - - net.sf.barcode4j - barcode4j - ${barcode4j.version} - - - - com.google.zxing - core - ${zxing.version} - - - com.google.zxing - javase - ${zxing.version} - - - - com.github.kenglxn.qrgen - javase - ${qrgen.version} - com.github.rvesse airline @@ -89,11 +55,22 @@ takes ${takes.version} + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + org.apache.velocity velocity-engine-core ${velocity-engine-core.version} +<<<<<<< HEAD com.uber.nullaway nullaway @@ -111,6 +88,25 @@ error_prone_core 2.1.3 +======= + + com.uber.nullaway + nullaway + 0.3.0 + + + org.codehaus.plexus + plexus-compiler-javac-errorprone + 2.8 + + + + com.google.errorprone + error_prone_core + 2.1.3 + +>>>>>>> upstream/master @@ -119,7 +115,7 @@ https://jitpack.io - + libraries-3 @@ -147,12 +143,20 @@ +<<<<<<< HEAD org.apache.maven.plugins maven-compiler-plugin 3.5 +======= + + org.apache.maven.plugins + maven-compiler-plugin + 3.5 + +>>>>>>> upstream/master javac-with-errorprone true 1.8 @@ -168,7 +172,11 @@ +<<<<<<< HEAD -XepExcludedPaths:(.*)/test/.*|(.*)/streamex/.*|(.*)/jcabi/.* +======= + -XepExcludedPaths:(.*)/test/.*|(.*)/jcabi/.* +>>>>>>> upstream/master -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway @@ -240,10 +248,6 @@ 1.78 1.18.6 - 1.5-beta1 - 2.1 - 3.3.0 - 2.6.0 0.43 2.7.2 @@ -255,6 +259,8 @@ 1.9.2 1.19 + 4.4.13 + 4.5.12 2.2 1.6.0 diff --git a/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java b/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java index f3db1d2df9..1fab591cb0 100644 --- a/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java +++ b/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java @@ -1,7 +1,5 @@ package com.baeldung.nullaway; -import com.baeldung.distinct.Person; - public class NullAwayExample { /* diff --git a/libraries-3/src/main/java/com/baeldung/nullaway/Person.java b/libraries-3/src/main/java/com/baeldung/nullaway/Person.java new file mode 100644 index 0000000000..fcd88036a1 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/nullaway/Person.java @@ -0,0 +1,65 @@ +package com.baeldung.nullaway; + +public class Person { + int age; + String name; + String email; + + public Person(int age, String name, String email) { + super(); + this.age = age; + this.name = name; + this.email = email; + } + + public int getAge() { + return age; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [age="); + builder.append(age); + builder.append(", name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.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; + Person other = (Person) obj; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + return true; + } + +} diff --git a/libraries-concurrency/README.md b/libraries-concurrency/README.md new file mode 100644 index 0000000000..d1ffe81fa8 --- /dev/null +++ b/libraries-concurrency/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Intro to Coroutines with Quasar](https://www.baeldung.com/java-quasar-coroutines) diff --git a/libraries-concurrency/coroutines-with-quasar/pom.xml b/libraries-concurrency/coroutines-with-quasar/pom.xml new file mode 100644 index 0000000000..59241272e7 --- /dev/null +++ b/libraries-concurrency/coroutines-with-quasar/pom.xml @@ -0,0 +1,84 @@ + + 4.0.0 + coroutines-with-quasar + coroutines-with-quasar + + + com.baeldung + libraries-concurrency + 1.0.0-SNAPSHOT + + + + + co.paralleluniverse + quasar-core + 0.8.0 + + + co.paralleluniverse + quasar-actors + 0.8.0 + + + co.paralleluniverse + quasar-reactive-streams + 0.8.0 + + + + + + + maven-dependency-plugin + 3.1.2 + + + getClasspathFilenames + + properties + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.quasar.App + target/classes + java + + + -Dco.paralleluniverse.fibers.verifyInstrumentation=true + + + -javaagent:${co.paralleluniverse:quasar-core:jar} + + + -classpath + + + + com.baeldung.quasar.App + + + + + maven-compiler-plugin + 3.8.0 + + + org.apache.maven.plugins + maven-compiler-plugin + + 12 + 12 + + + + + diff --git a/libraries-concurrency/coroutines-with-quasar/src/main/java/com/baeldung/quasar/App.java b/libraries-concurrency/coroutines-with-quasar/src/main/java/com/baeldung/quasar/App.java new file mode 100644 index 0000000000..510877d1be --- /dev/null +++ b/libraries-concurrency/coroutines-with-quasar/src/main/java/com/baeldung/quasar/App.java @@ -0,0 +1,11 @@ +package com.baeldung.quasar; + +import co.paralleluniverse.fibers.Fiber; + +public class App { + public static void main(String[] args) { + new Fiber(() -> { + System.out.println("Inside fiber coroutine..."); + }).start(); + } +} diff --git a/libraries-concurrency/pom.xml b/libraries-concurrency/pom.xml new file mode 100644 index 0000000000..cb59b17674 --- /dev/null +++ b/libraries-concurrency/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + libraries-concurrency + libraries-concurrency + pom + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + + + \ No newline at end of file diff --git a/libraries-data-2/README.md b/libraries-data-2/README.md index 24618b5e37..f992186bd9 100644 --- a/libraries-data-2/README.md +++ b/libraries-data-2/README.md @@ -11,4 +11,7 @@ This module contains articles about libraries for data processing in Java. - [Guide to JMapper](https://www.baeldung.com/jmapper) - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) - [Intro to Derive4J](https://www.baeldung.com/derive4j) -More articles: [[<-- prev]](/../libraries-data) \ No newline at end of file +More articles: [[<-- prev]](/../libraries-data) + +##### Building the project +You can build the project from the command line using: *mvn clean install*, or in an IDE. If you have issues with the derive4j imports in your IDE, you have to add the folder: *target/generated-sources/annotations* to the project build path in your IDE. diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index e6106c0fe3..73c5452f77 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -128,6 +128,21 @@ ${awaitility.version} test + + org.rosuda.REngine + Rserve + ${rserve.version} + + + com.github.jbytecode + RCaller + ${rcaller.version} + + + org.renjin + renjin-script-engine + ${renjin.version} + @@ -137,6 +152,13 @@ http://repo.numericalmethod.com/maven/ default + + + + bedatadriven + bedatadriven public repo + https://nexus.bedatadriven.com/content/groups/public/ + @@ -153,6 +175,27 @@ 3.6.2 1.7.25 3.0.0 + RELEASE + 3.0 + 1.8.1 + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + com/baeldung/r/FastRMean.java + + + com/baeldung/r/FastRMeanUnitTest.java + + + + + + \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java b/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java new file mode 100644 index 0000000000..8348bfa403 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/FastRMean.java @@ -0,0 +1,33 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +/** + * FastR showcase. + * + * @author Donato Rimenti + */ +public class FastRMean { + + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + */ + public double mean(int[] values) { + Context polyglot = Context.newBuilder() + .allowAllAccess(true) + .build(); + String meanScriptContent = RUtils.getMeanScriptContent(); + polyglot.eval("R", meanScriptContent); + Value rBindings = polyglot.getBindings("R"); + Value rInput = rBindings.getMember("c") + .execute(values); + return rBindings.getMember("customMean") + .execute(rInput) + .asDouble(); + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java new file mode 100644 index 0000000000..99edb8c043 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RCallerMean.java @@ -0,0 +1,37 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import com.github.rcaller.rstuff.RCaller; +import com.github.rcaller.rstuff.RCallerOptions; +import com.github.rcaller.rstuff.RCode; + +/** + * RCaller showcase. + * + * @author Donato Rimenti + */ +public class RCallerMean { + + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + */ + public double mean(int[] values) throws IOException, URISyntaxException { + String fileContent = RUtils.getMeanScriptContent(); + RCode code = RCode.create(); + code.addRCode(fileContent); + code.addIntArray("input", values); + code.addRCode("result <- customMean(input)"); + RCaller caller = RCaller.create(code, RCallerOptions.create()); + caller.runAndReturnResult("result"); + return caller.getParser() + .getAsDoubleArray("result")[0]; + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java b/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java new file mode 100644 index 0000000000..a9393cdcc2 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RUtils.java @@ -0,0 +1,33 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Collectors; + +/** + * Utility class for loading the script.R content. + * + * @author Donato Rimenti + */ +public class RUtils { + + /** + * Loads the script.R and returns its content as a string. + * + * @return the script.R content as a string + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + */ + static String getMeanScriptContent() throws IOException, URISyntaxException { + URI rScriptUri = RUtils.class.getClassLoader() + .getResource("script.R") + .toURI(); + Path inputScript = Paths.get(rScriptUri); + return Files.lines(inputScript) + .collect(Collectors.joining()); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java new file mode 100644 index 0000000000..4576ec5fb4 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RenjinMean.java @@ -0,0 +1,36 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import javax.script.ScriptException; + +import org.renjin.script.RenjinScriptEngine; +import org.renjin.sexp.DoubleArrayVector; + +/** + * Renjin showcase. + * + * @author Donato Rimenti + */ +public class RenjinMean { + + /** + * Invokes the customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws IOException if any error occurs + * @throws URISyntaxException if any error occurs + * @throws ScriptException if any error occurs + */ + public double mean(int[] values) throws IOException, URISyntaxException, ScriptException { + RenjinScriptEngine engine = new RenjinScriptEngine(); + String meanScriptContent = RUtils.getMeanScriptContent(); + engine.put("input", values); + engine.eval(meanScriptContent); + DoubleArrayVector result = (DoubleArrayVector) engine.eval("customMean(input)"); + return result.asReal(); + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java b/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java new file mode 100644 index 0000000000..1aaa7fa847 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/r/RserveMean.java @@ -0,0 +1,30 @@ +package com.baeldung.r; + +import org.rosuda.REngine.REXPMismatchException; +import org.rosuda.REngine.REngineException; +import org.rosuda.REngine.Rserve.RConnection; + +/** + * Rserve showcase. + * + * @author Donato Rimenti + */ +public class RserveMean { + + /** + * Connects to the Rserve istance listening on 127.0.0.1:6311 and invokes the + * customMean R function passing the given values as arguments. + * + * @param values the input to the mean script + * @return the result of the R script + * @throws REngineException if any error occurs + * @throws REXPMismatchException if any error occurs + */ + public double mean(int[] values) throws REngineException, REXPMismatchException { + RConnection c = new RConnection(); + c.assign("input", values); + return c.eval("customMean(input)") + .asDouble(); + } + +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java new file mode 100644 index 0000000000..4e7426b75a --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/FastRMeanUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.r; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Test for {@link FastRMean}. + * + * @author Donato Rimenti + */ +@Ignore +public class FastRMeanUnitTest { + + /** + * Object to test. + */ + private FastRMean fastrMean = new FastRMean(); + + /** + * Test for {@link FastRMeanUnitTest#mean(int[])}. + */ + @Test + public void givenValues_whenMean_thenCorrect() { + int[] input = { 1, 2, 3, 4, 5 }; + double result = fastrMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java new file mode 100644 index 0000000000..ce6b3a4332 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/RCallerMeanIntegrationTest.java @@ -0,0 +1,37 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import javax.script.ScriptException; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Test for {@link RCallerMean}. + * + * @author Donato Rimenti + */ +@Ignore +public class RCallerMeanIntegrationTest { + + /** + * Object to test. + */ + private RCallerMean rcallerMean = new RCallerMean(); + + /** + * Test for {@link RCallerMeanIntegrationTest#mean(int[])}. + * + * @throws ScriptException if an error occurs + * @throws URISyntaxException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = rcallerMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java new file mode 100644 index 0000000000..f52d37d614 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/RenjinMeanUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.r; + +import java.io.IOException; +import java.net.URISyntaxException; + +import javax.script.ScriptException; + +import org.junit.Test; + +import org.junit.Assert; + +/** + * Test for {@link RenjinMean}. + * + * @author Donato Rimenti + */ +public class RenjinMeanUnitTest { + + /** + * Object to test. + */ + private RenjinMean renjinMean = new RenjinMean(); + + /** + * Test for {@link RenjinMeanUnitTest#mean(int[])}. + * + * @throws ScriptException if an error occurs + * @throws URISyntaxException if an error occurs + * @throws IOException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException, ScriptException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = renjinMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java b/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java new file mode 100644 index 0000000000..23d42bd8e9 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/r/RserveMeanIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.r; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.rosuda.REngine.REXPMismatchException; +import org.rosuda.REngine.REngineException; + +/** + * Test for {@link RserveMean}. + * + * @author Donato Rimenti + */ +@Ignore +public class RserveMeanIntegrationTest { + + /** + * Object to test. + */ + private RserveMean rserveMean = new RserveMean(); + + /** + * Test for {@link RserveMeanIntegrationTest#mean(int[])}. + * + * @throws REXPMismatchException if an error occurs + * @throws REngineException if an error occurs + */ + @Test + public void givenValues_whenMean_thenCorrect() throws REngineException, REXPMismatchException { + int[] input = { 1, 2, 3, 4, 5 }; + double result = rserveMean.mean(input); + Assert.assertEquals(3.0, result, 0.000001); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/resources/script.R b/libraries-data-2/src/test/resources/script.R new file mode 100644 index 0000000000..08f859cc3d --- /dev/null +++ b/libraries-data-2/src/test/resources/script.R @@ -0,0 +1,3 @@ +customMean <- function(vector) { + mean(vector) +} \ No newline at end of file diff --git a/libraries-http-2/README.md b/libraries-http-2/README.md new file mode 100644 index 0000000000..5ba45eb4a9 --- /dev/null +++ b/libraries-http-2/README.md @@ -0,0 +1,10 @@ +## HTTP + +This module contains articles about HTTP libraries. + +### Relevant Articles: + +- [Jetty ReactiveStreams HTTP Client](https://www.baeldung.com/jetty-reactivestreams-http-client) +- [Decode an OkHttp JSON Response](https://www.baeldung.com/okhttp-json-response) +- More articles [[<-- prev]](/libraries-http) + diff --git a/libraries-http-2/pom.xml b/libraries-http-2/pom.xml new file mode 100644 index 0000000000..c0a4f6455d --- /dev/null +++ b/libraries-http-2/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + libraries-http-2 + libraries-http-2 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + 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 + + + + + 3.14.2 + 2.8.5 + 3.14.2 + 2.9.8 + + + diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java similarity index 100% rename from libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java rename to libraries-http-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java b/libraries-http-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java similarity index 100% rename from libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java rename to libraries-http-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java diff --git a/libraries-http/README.md b/libraries-http/README.md index 1f065a9d4a..61b2904cee 100644 --- a/libraries-http/README.md +++ b/libraries-http/README.md @@ -14,3 +14,4 @@ This module contains articles about HTTP libraries. - [Creating REST Microservices with Javalin](https://www.baeldung.com/javalin-rest-microservices) - [A Quick Guide to Timeouts in OkHttp](https://www.baeldung.com/okhttp-timeouts) - [A Quick Guide to Post Requests with OkHttp](https://www.baeldung.com/okhttp-post) +- More articles [[next -->]](/libraries-http-2) diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index e287de4527..e02f766141 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -23,7 +23,9 @@ org.springframework.security.oauth spring-security-oauth2 + ${spring-boot.version} + org.springframework spring-web diff --git a/libraries-security/src/main/resources/Baeldung.p12 b/libraries-security/src/main/resources/Baeldung.p12 new file mode 100644 index 0000000000..65ec8bc8fe Binary files /dev/null and b/libraries-security/src/main/resources/Baeldung.p12 differ diff --git a/libraries-server/README.md b/libraries-server/README.md index d9e6b8b206..7e41f33a0c 100644 --- a/libraries-server/README.md +++ b/libraries-server/README.md @@ -13,3 +13,4 @@ This module contains articles about server libraries. - [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client) - [Guide to XMPP Smack Client](https://www.baeldung.com/xmpp-smack-chat-client) - [A Guide to NanoHTTPD](https://www.baeldung.com/nanohttpd) +- [HTTP/2 in Jetty](https://www.baeldung.com/jetty-http-2) diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index a849708cd8..eb9cb61e56 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -5,6 +5,7 @@ libraries-server 0.0.1-SNAPSHOT libraries-server + war com.baeldung @@ -105,12 +106,51 @@ + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.version} + + 8888 + quit + + -Xbootclasspath/p:${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn.version}/alpn-boot-${alpn.version}.jar + + ${basedir}/src/main/config/jetty.xml + + / + + + + + org.eclipse.jetty.http2 + http2-server + ${jetty.version} + + + org.eclipse.jetty + jetty-alpn-openjdk8-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlets + ${jetty.version} + + + + + 3.6.2 4.5.3 - 9.4.8.v20171121 + 9.4.27.v20200227 4.1.20.Final + 8.1.11.v20170118 8.5.24 4.3.1 1.2.0 diff --git a/libraries-server/src/main/config/jetty.xml b/libraries-server/src/main/config/jetty.xml new file mode 100644 index 0000000000..fd4a50382b --- /dev/null +++ b/libraries-server/src/main/config/jetty.xml @@ -0,0 +1,79 @@ + + + + + + + src/main/resources/keystore.jks + storepwd + src/main/resources/truststore.jks + storepwd + TLSv1.2 + + + + + + + + + + + + + + + + + http/1.1 + + + + + + + + + + + + 8443 + + + + + + + + + + + + + + + + + + alpn + + + + + h2,h2-17 + + + + + + + + + + + + 8444 + + + + \ No newline at end of file diff --git a/libraries-server/src/main/java/com/baeldung/jetty/http2/Http2JettyServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/http2/Http2JettyServlet.java new file mode 100644 index 0000000000..56b75c45d3 --- /dev/null +++ b/libraries-server/src/main/java/com/baeldung/jetty/http2/Http2JettyServlet.java @@ -0,0 +1,29 @@ +package com.baeldung.jetty.http2; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class Http2JettyServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.addHeader("Cache-control", "no-store, no-cache, must-revalidate"); + response.addDateHeader("Last-Modified", 0); + response.addDateHeader("Expires", 0); + + String requestPath = request.getRequestURI(); + InputStream input = getServletContext().getResourceAsStream(requestPath); + OutputStream output = response.getOutputStream(); + byte[] buffer = new byte[1024]; + int read; + while ((read = input.read(buffer)) >= 0) { + output.write(buffer, 0, read); + } + } + +} diff --git a/libraries-server/src/main/resources/keystore.jks b/libraries-server/src/main/resources/keystore.jks new file mode 100644 index 0000000000..428ba54776 Binary files /dev/null and b/libraries-server/src/main/resources/keystore.jks differ diff --git a/libraries-server/src/main/resources/truststore.jks b/libraries-server/src/main/resources/truststore.jks new file mode 100644 index 0000000000..839cb8c351 Binary files /dev/null and b/libraries-server/src/main/resources/truststore.jks differ diff --git a/libraries-server/src/main/webapp/WEB-INF/web.xml b/libraries-server/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..75d7e11c64 --- /dev/null +++ b/libraries-server/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,33 @@ + + + + + http2Jetty + com.baeldung.jetty.http2.Http2JettyServlet + + + http2Jetty + /images/* + + + + push + org.eclipse.jetty.servlets.PushCacheFilter + + ports + 8444 + + + maxAssociations + 32 + + + + push + /* + + + \ No newline at end of file diff --git a/libraries-server/src/main/webapp/http2.html b/libraries-server/src/main/webapp/http2.html new file mode 100644 index 0000000000..4563945a5e --- /dev/null +++ b/libraries-server/src/main/webapp/http2.html @@ -0,0 +1,14 @@ + + + + Baeldung HTTP/2 Client in Jetty + + +

HTTP/2 Demo

+
+ latest articles + rest with spring + weekly reviews +
+ + \ No newline at end of file diff --git a/libraries-server/src/main/webapp/images/homepage-latest_articles.jpg b/libraries-server/src/main/webapp/images/homepage-latest_articles.jpg new file mode 100644 index 0000000000..59e78e4560 Binary files /dev/null and b/libraries-server/src/main/webapp/images/homepage-latest_articles.jpg differ diff --git a/libraries-server/src/main/webapp/images/homepage-rest_with_spring.jpg b/libraries-server/src/main/webapp/images/homepage-rest_with_spring.jpg new file mode 100644 index 0000000000..43d9221e85 Binary files /dev/null and b/libraries-server/src/main/webapp/images/homepage-rest_with_spring.jpg differ diff --git a/libraries-server/src/main/webapp/images/homepage-weekly_reviews.jpg b/libraries-server/src/main/webapp/images/homepage-weekly_reviews.jpg new file mode 100644 index 0000000000..0d6d111911 Binary files /dev/null and b/libraries-server/src/main/webapp/images/homepage-weekly_reviews.jpg differ diff --git a/libraries-server/src/main/webapp/index.html b/libraries-server/src/main/webapp/index.html new file mode 100644 index 0000000000..2497893d82 --- /dev/null +++ b/libraries-server/src/main/webapp/index.html @@ -0,0 +1,12 @@ + + + + Baeldung: HTTP2 Client in Jetty + + +

HTTP/1.1

+
+

HTTP/2 Push

+
+ + \ No newline at end of file diff --git a/libraries-testing/README.md b/libraries-testing/README.md index 332debfe18..7098c10d28 100644 --- a/libraries-testing/README.md +++ b/libraries-testing/README.md @@ -11,3 +11,4 @@ This module contains articles about test libraries. - [Introduction to Awaitlity](https://www.baeldung.com/awaitlity-testing) - [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly) - [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide) +- [Introduction To DBUnit](https://www.baeldung.com/dbunit) diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index 3ffbb291a0..ad6c81a3d6 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -130,6 +130,27 @@ ${asciidoctor.version}
+ + org.dbunit + dbunit + ${dbunit.version} + test + + + + com.h2database + h2 + ${h2.version} + test + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + @@ -150,6 +171,16 @@ + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven-compiler-plugin.source} + ${maven-compiler-plugin.target} + + + @@ -166,6 +197,12 @@ 4.1.1 3.6.2 2.0.0.0 + 1.4.200 + 2.7.0 + 3.14.0 + 1.8 + 1.8 + 3.8.1 diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java b/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java new file mode 100644 index 0000000000..cc29d9c58a --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java @@ -0,0 +1,8 @@ +package com.baeldung.dbunit; + +public class ConnectionSettings { + public static final String JDBC_DRIVER = org.h2.Driver.class.getName(); + public static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:dbunit/schema.sql'"; + public static final String USER = "sa"; + public static final String PASSWORD = ""; +} diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java new file mode 100644 index 0000000000..93c7e9a456 --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -0,0 +1,168 @@ +package com.baeldung.dbunit; + +import org.dbunit.Assertion; +import org.dbunit.DataSourceBasedDBTestCase; +import org.dbunit.assertion.DiffCollectingFailureHandler; +import org.dbunit.assertion.Difference; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; +import org.h2.jdbcx.JdbcDataSource; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.platform.commons.logging.Logger; +import org.junit.platform.commons.logging.LoggerFactory; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import javax.sql.DataSource; +import java.io.InputStream; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; + +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static java.util.stream.Collectors.joining; +import static org.assertj.core.api.Assertions.assertThat; +import static org.dbunit.Assertion.assertEqualsIgnoreCols; + +@RunWith(JUnit4.class) +public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { + + private static final Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); + + @Override + protected DataSource getDataSource() { + JdbcDataSource dataSource = new JdbcDataSource(); + dataSource.setURL(JDBC_URL); + dataSource.setUser("sa"); + dataSource.setPassword(""); + return dataSource; + } + + @Override + protected IDataSet getDataSet() throws Exception { + try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(resourceAsStream); + } + } + + @Override + protected DatabaseOperation getSetUpOperation() { + return DatabaseOperation.REFRESH; + } + + @Override + protected DatabaseOperation getTearDownOperation() { + return DatabaseOperation.DELETE_ALL; + } + + @Before + public void setUp() throws Exception { + super.setUp(); + } + + @After + public void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void givenDataSet_whenSelect_thenFirstTitleIsGreyTShirt() throws SQLException { + final Connection connection = getDataSource().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test + public void givenDataSetEmptySchema_whenDataSetCreated_thenTablesAreEqual() throws Exception { + final IDataSet expectedDataSet = getDataSet(); + final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + final IDataSet databaseDataSet = getConnection().createDataSet(); + final ITable actualTable = databaseDataSet.getTable("CLIENTS"); + Assertion.assertEquals(expectedTable, actualTable); + } + + @Test + public void givenDataSet_whenInsert_thenTableHasNewClient() throws Exception { + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-user.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + final Connection conn = getDataSource().getConnection(); + + conn.createStatement() + .executeUpdate( + "INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); + final ITable actualData = getConnection() + .createQueryTable( + "result_name", + "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); + + assertEqualsIgnoreCols(expectedTable, actualData, new String[] { "id" }); + } + } + + @Test + public void givenDataSet_whenDelete_thenItemIsDeleted() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final InputStream is = DataSourceDBUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception { + final Connection connection = getConnection().getConnection(); + + try (final InputStream is = DataSourceDBUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenInsertUnexpectedData_thenFailOnAllUnexpectedValues() throws Exception { + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-multiple-failures.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = expectedDataSet.getTable("ITEMS"); + final Connection conn = getDataSource().getConnection(); + final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); + + conn.createStatement().executeUpdate( + "INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); + final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); + + Assertion.assertEquals(expectedTable, actualData, collectingHandler); + if (!collectingHandler.getDiffList().isEmpty()) { + String message = (String) collectingHandler + .getDiffList() + .stream() + .map(d -> formatDifference((Difference) d)).collect(joining("\n")); + logger.error(() -> message); + } + } + } + + private static String formatDifference(Difference diff) { + return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue(); + } +} diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java new file mode 100644 index 0000000000..6243af9676 --- /dev/null +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -0,0 +1,159 @@ +package com.baeldung.dbunit; + +import org.dbunit.Assertion; +import org.dbunit.IDatabaseTester; +import org.dbunit.JdbcDatabaseTester; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.filter.DefaultColumnFilter; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.operation.DatabaseOperation; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.InputStream; +import java.sql.Connection; +import java.sql.ResultSet; + +import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; +import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; +import static com.baeldung.dbunit.ConnectionSettings.USER; +import static org.assertj.core.api.Assertions.assertThat; +import static org.dbunit.Assertion.assertEquals; + +@RunWith(JUnit4.class) +public class OldSchoolDbUnitTest { + + private static IDatabaseTester tester = null; + + @BeforeClass + public static void setUp() throws Exception { + tester = initDatabaseTester(); + } + + private static IDatabaseTester initDatabaseTester() throws Exception { + final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + tester.setDataSet(initDataSet()); + tester.setSetUpOperation(DatabaseOperation.REFRESH); + tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); + return tester; + } + + private static IDataSet initDataSet() throws Exception { + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { + return new FlatXmlDataSetBuilder().build(is); + } + } + + @Before + public void setup() throws Exception { + tester.onSetup(); + } + + @After + public void tearDown() throws Exception { + tester.onTearDown(); + } + + @Test + public void givenDataSet_whenSelect_thenFirstTitleIsGreyTShirt() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + + assertThat(rs.next()).isTrue(); + assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); + } + + @Test + public void givenDataSet_whenInsert_thenGetResultsAreStillEqualIfIgnoringColumnsWithDifferentProduced() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + final String[] excludedColumns = { "id", "produced" }; + try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { + final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable( + expectedDataSet.getTable("ITEMS"), excludedColumns); + + connection.createStatement().executeUpdate( + "INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + final ITable actualTable = DefaultColumnFilter.excludedColumnsTable( + databaseDataSet.getTable("ITEMS"), excludedColumns); + + Assertion.assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenDelete_thenItemIsRemoved() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenDelete_thenItemIsRemovedAndResultsEqualIfProducedIsIgnored() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); + + assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + + assertEquals(expectedTable, actualTable); + } + } + + @Test + public void givenDataSet_whenUpdateWithNoProduced_thenItemHasNewName() throws Exception { + final Connection connection = tester.getConnection().getConnection(); + + try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[] { "produced" }); + + connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); + + final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("ITEMS"); + actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); + assertEquals(expectedTable, actualTable); + } + } + +} diff --git a/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java b/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java index ce9638c4af..822468e91f 100644 --- a/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java @@ -78,10 +78,10 @@ public class JsonAssertUnitTest { @Test public void givenArray_whenComparing_thenOrderMustMatchForStrict() throws JSONException { - String result = "[Alex, Barbera, Charlie, Xavier]"; - JSONAssert.assertEquals("[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.LENIENT); - JSONAssert.assertEquals("[Alex, Barbera, Charlie, Xavier]", result, JSONCompareMode.STRICT); - JSONAssert.assertNotEquals("[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.STRICT); + String result = "[Alex, Barbera, Charlie, Wolf]"; + JSONAssert.assertEquals("[Charlie, Alex, Wolf, Barbera]", result, JSONCompareMode.LENIENT); + JSONAssert.assertEquals("[Alex, Barbera, Charlie, Wolf]", result, JSONCompareMode.STRICT); + JSONAssert.assertNotEquals("[Charlie, Alex, Wolf, Barbera]", result, JSONCompareMode.STRICT); } @Test @@ -94,7 +94,7 @@ public class JsonAssertUnitTest { @Test public void whenComparingSizeOfArray_thenPass() throws JSONException { - String names = "{names:[Alex, Barbera, Charlie, Xavier]}"; + String names = "{names:[Alex, Barbera, Charlie, Wolf]}"; JSONAssert.assertEquals("{names:[4]}", names, new ArraySizeComparator(JSONCompareMode.LENIENT)); } diff --git a/libraries-testing/src/test/resources/dbunit/data.xml b/libraries-testing/src/test/resources/dbunit/data.xml new file mode 100644 index 0000000000..4865dec54c --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/data.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/expected-ignoring-registered_at.xml b/libraries-testing/src/test/resources/dbunit/expected-ignoring-registered_at.xml new file mode 100644 index 0000000000..ea57b6a961 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/expected-ignoring-registered_at.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/libraries-testing/src/test/resources/dbunit/expected-multiple-failures.xml b/libraries-testing/src/test/resources/dbunit/expected-multiple-failures.xml new file mode 100644 index 0000000000..ea57b6a961 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/expected-multiple-failures.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/libraries-testing/src/test/resources/dbunit/expected-user.xml b/libraries-testing/src/test/resources/dbunit/expected-user.xml new file mode 100644 index 0000000000..631dd84210 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/expected-user.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/libraries-testing/src/test/resources/dbunit/items.xml b/libraries-testing/src/test/resources/dbunit/items.xml new file mode 100644 index 0000000000..d13e93bbe0 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_delete.xml b/libraries-testing/src/test/resources/dbunit/items_exp_delete.xml new file mode 100644 index 0000000000..a6fa2b33e8 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_delete.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_delete_no_produced.xml b/libraries-testing/src/test/resources/dbunit/items_exp_delete_no_produced.xml new file mode 100644 index 0000000000..3e7f854f5f --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_delete_no_produced.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_rename.xml b/libraries-testing/src/test/resources/dbunit/items_exp_rename.xml new file mode 100644 index 0000000000..32f1d57cf6 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_rename.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml b/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml new file mode 100644 index 0000000000..4f14b17113 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/items_exp_rename_no_produced.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/schema.sql b/libraries-testing/src/test/resources/dbunit/schema.sql new file mode 100644 index 0000000000..c2a8d2d630 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/schema.sql @@ -0,0 +1,28 @@ +CREATE TABLE IF NOT EXISTS CLIENTS +( + `id` int AUTO_INCREMENT NOT NULL, + `first_name` varchar(100) NOT NULL, + `last_name` varchar(100) NOT NULL, + PRIMARY KEY (`id`) +); + +CREATE TABLE IF NOT EXISTS ITEMS +( + `id` int AUTO_INCREMENT NOT NULL, + `title` varchar(100) NOT NULL, + `produced` date, + `price` float, + PRIMARY KEY (`id`) +); + +CREATE TABLE IF NOT EXISTS PURCHASES +( + `id` int NOT NULL AUTO_INCREMENT, + `id_user` int NOT NULL, + `id_item` int NOT NULL, + `total_price` float NOT NULL, + `quantity` int(11) NOT NULL, + PRIMARY KEY (`id`), + FOREIGN KEY (`id_user`) REFERENCES CLIENTS (`id`) ON DELETE CASCADE, + FOREIGN KEY (`id_item`) REFERENCES ITEMS (`id`) ON DELETE CASCADE ON UPDATE CASCADE +); diff --git a/libraries-testing/src/test/resources/dbunit/users.xml b/libraries-testing/src/test/resources/dbunit/users.xml new file mode 100644 index 0000000000..f04943c4cc --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/users.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml b/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml new file mode 100644 index 0000000000..20a2f2f1a7 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/users_exp_delete.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml b/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml new file mode 100644 index 0000000000..1ab6cf53b8 --- /dev/null +++ b/libraries-testing/src/test/resources/dbunit/users_exp_rename.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/libraries/README.md b/libraries/README.md index f439033730..79ba8fe55d 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -45,5 +45,4 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Implementing a FTP-Client in Java](https://www.baeldung.com/java-ftp-client) - [Introduction to Functional Java](https://www.baeldung.com/java-functional-library) - [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library) -- [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - More articles [[next -->]](/libraries-2) diff --git a/libraries/pom.xml b/libraries/pom.xml index af300657b0..41bc2b9311 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -435,23 +435,6 @@ reflections ${reflections.version} - - com.uber.nullaway - nullaway - 0.3.0 - - - org.codehaus.plexus - plexus-compiler-javac-errorprone - 2.8 - - - - com.google.errorprone - error_prone_core - 2.1.3 - @@ -569,46 +552,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 3.5 - - javac-with-errorprone - true - 1.8 - 1.8 - true - - - com.uber.nullaway - nullaway - 0.3.0 - - - - - - -XepExcludedPaths:(.*)/test/.*|(.*)/streamex/.* - -XepOpt:NullAway:AnnotatedPackages=com.baeldung.nullaway - - - - - org.codehaus.plexus - plexus-compiler-javac-errorprone - 2.8 - - - - com.google.errorprone - error_prone_core - 2.1.3 - - - - diff --git a/linux-bash/command-line-arguments/src/main/bash/README.md b/linux-bash/command-line-arguments/src/main/bash/README.md new file mode 100644 index 0000000000..27d89fff99 --- /dev/null +++ b/linux-bash/command-line-arguments/src/main/bash/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [How to Use Command Line Arguments in a Bash Script](https://www.baeldung.com/linux/use-command-line-arguments-in-bash-script) diff --git a/linux-bash/functions/src/main/bash/README.md b/linux-bash/functions/src/main/bash/README.md new file mode 100644 index 0000000000..5fb6958b9d --- /dev/null +++ b/linux-bash/functions/src/main/bash/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Bash Functions in Linux](https://www.baeldung.com/linux/bash-functions) diff --git a/linux-bash/read/README.md b/linux-bash/read/README.md new file mode 100644 index 0000000000..56c1dd5b24 --- /dev/null +++ b/linux-bash/read/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Guide to the Linux read Command](https://www.baeldung.com/linux/read-command) diff --git a/linux-bash/text/README.md b/linux-bash/text/README.md index de99c1962a..20df2a33ec 100644 --- a/linux-bash/text/README.md +++ b/linux-bash/text/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/tr-manipulate-strings) +- [Linux Commands for Appending Multiple Lines to a File](https://www.baeldung.com/linux/appending-multiple-lines-to-file2) diff --git a/logging-modules/log-mdc/README.md b/logging-modules/log-mdc/README.md index 3841224824..0d516619ef 100644 --- a/logging-modules/log-mdc/README.md +++ b/logging-modules/log-mdc/README.md @@ -1,8 +1,8 @@ ### Relevant Articles: - TBD -- [Improved Java Logging with Mapped Diagnostic Context (MDC)](http://www.baeldung.com/mdc-in-log4j-2-logback) -- [Java Logging with Nested Diagnostic Context (NDC)](http://www.baeldung.com/java-logging-ndc-log4j) -- [Drools Using Rules from Excel Files](http://www.baeldung.com/drools-excel) +- [Improved Java Logging with Mapped Diagnostic Context (MDC)](https://www.baeldung.com/mdc-in-log4j-2-logback) +- [Java Logging with Nested Diagnostic Context (NDC)](https://www.baeldung.com/java-logging-ndc-log4j) +- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel) ### References diff --git a/lombok/src/main/README.md b/lombok/src/main/README.md new file mode 100644 index 0000000000..4092d8ce99 --- /dev/null +++ b/lombok/src/main/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Guide to the Linux wc Command](https://www.baeldung.com/linux/wc-command) diff --git a/machine-learning/pom.xml b/machine-learning/pom.xml index 24162b7b9c..99b7e33579 100644 --- a/machine-learning/pom.xml +++ b/machine-learning/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 machine-learning 1.0-SNAPSHOT @@ -13,23 +15,6 @@ 1.0.0-SNAPSHOT - - UTF-8 - 1.7 - 1.7 - 1.3.50 - 0.9.1 - 3.1.0 - 3.0.2 - 3.0.2 - 3.8.0 - 2.22.1 - 2.5.2 - 2.8.2 - 3.7.1 - 3.0.0 - - org.jetbrains.kotlin @@ -158,4 +143,21 @@ + + UTF-8 + 1.7 + 1.7 + 1.3.50 + 0.9.1 + 3.1.0 + 3.0.2 + 3.0.2 + 3.8.0 + 2.22.1 + 2.5.2 + 2.8.2 + 3.7.1 + 3.0.0 + + diff --git a/maven-all/maven-custom-plugin/usage-example/pom.xml b/maven-all/maven-custom-plugin/usage-example/pom.xml index bd2b16475e..ef6f08a3fb 100644 --- a/maven-all/maven-custom-plugin/usage-example/pom.xml +++ b/maven-all/maven-custom-plugin/usage-example/pom.xml @@ -1,18 +1,14 @@ - + 4.0.0 com.baeldung example 0.0.1-SNAPSHOT pom - - 3.9 - 4.12 - - org.apache.commons @@ -47,4 +43,9 @@ + + 3.9 + 4.12 + + diff --git a/maven-all/maven/README.md b/maven-all/maven/README.md index ced4a52703..c5f46ca184 100644 --- a/maven-all/maven/README.md +++ b/maven-all/maven/README.md @@ -7,7 +7,6 @@ have their own dedicated modules. - [Guide to the Core Maven Plugins](https://www.baeldung.com/core-maven-plugins) - [Maven Resources Plugin](https://www.baeldung.com/maven-resources-plugin) -- [Maven Compiler Plugin](https://www.baeldung.com/maven-compiler-plugin) - [Quick Guide to the Maven Surefire Plugin](https://www.baeldung.com/maven-surefire-plugin) - [The Maven Failsafe Plugin](https://www.baeldung.com/maven-failsafe-plugin) - [The Maven Verifier Plugin](https://www.baeldung.com/maven-verifier-plugin) diff --git a/maven-all/maven/custom-rule/README.md b/maven-all/maven/custom-rule/README.md deleted file mode 100644 index 44d43050e7..0000000000 --- a/maven-all/maven/custom-rule/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin) diff --git a/maven-all/versions-maven-plugin/original/README.md b/maven-all/versions-maven-plugin/original/README.md deleted file mode 100644 index 5652a9b7e4..0000000000 --- a/maven-all/versions-maven-plugin/original/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Use the Latest Version of a Dependency in Maven](https://www.baeldung.com/maven-dependency-latest-version) diff --git a/maven-archetype/src/main/resources/archetype-resources/pom.xml b/maven-archetype/src/main/resources/archetype-resources/pom.xml index 2a73687e2c..fc568349bc 100644 --- a/maven-archetype/src/main/resources/archetype-resources/pom.xml +++ b/maven-archetype/src/main/resources/archetype-resources/pom.xml @@ -1,23 +1,13 @@ - + 4.0.0 ${groupId} ${artifactId} ${version} war - - UTF-8 - 1.8 - 1.8 - false - ${liberty-plugin-version} - 9080 - 9443 - 2.0 - 2.1 - - ${artifactId} @@ -80,4 +70,16 @@ + + UTF-8 + 1.8 + 1.8 + false + ${liberty-plugin-version} + 9080 + 9443 + 2.0 + 2.1 + + diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml index cfa59bdc39..cf6ea85cb5 100644 --- a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 com.baeldung.userdaomodule userdaomodule @@ -14,11 +16,6 @@ 1.0 - - 1.0 - 1.0 - - com.baeldung.entitymodule @@ -37,4 +34,9 @@ + + 1.0 + 1.0 + + diff --git a/mesos-marathon/README.md b/mesos-marathon/README.md index 65b2361698..8e5b8e4974 100644 --- a/mesos-marathon/README.md +++ b/mesos-marathon/README.md @@ -6,4 +6,4 @@ This module contains articles about Marathon and Mesos. - [Simple Jenkins Pipeline with Marathon and Mesos](https://www.baeldung.com/jenkins-pipeline-with-marathon-mesos) - To run the pipeline, please modify the dockerise.sh file with your own useranema and password for docker login. + To run the pipeline, please modify the dockerise.sh file with your own username and password for docker login. diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml index 4fb819c434..42798bb209 100644 --- a/mesos-marathon/pom.xml +++ b/mesos-marathon/pom.xml @@ -7,9 +7,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java b/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java index 85331516f9..dfe944a316 100644 --- a/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java +++ b/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java @@ -3,8 +3,8 @@ package com.baeldung; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; diff --git a/netty/pom.xml b/netty/pom.xml new file mode 100644 index 0000000000..1a33eef92e --- /dev/null +++ b/netty/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + netty + 0.0.1-SNAPSHOT + netty + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + io.netty + netty-all + ${netty.version} + + + + org.conscrypt + conscrypt-openjdk-uber + 2.4.0 + + + + + + 4.1.48.Final + + + \ No newline at end of file diff --git a/netty/src/main/java/com/baeldung/netty/http2/Http2Util.java b/netty/src/main/java/com/baeldung/netty/http2/Http2Util.java new file mode 100644 index 0000000000..62b6d4c4ed --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/Http2Util.java @@ -0,0 +1,135 @@ +package com.baeldung.netty.http2; + +import static io.netty.handler.logging.LogLevel.INFO; + +import java.security.cert.CertificateException; + +import javax.net.ssl.SSLException; + +import com.baeldung.netty.http2.client.Http2ClientResponseHandler; +import com.baeldung.netty.http2.client.Http2SettingsHandler; +import com.baeldung.netty.http2.server.Http2ServerResponseHandler; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPipeline; +import io.netty.handler.codec.http.DefaultFullHttpRequest; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpHeaderValues; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpScheme; +import io.netty.handler.codec.http.HttpVersion; +import io.netty.handler.codec.http2.DefaultHttp2Connection; +import io.netty.handler.codec.http2.DelegatingDecompressorFrameListener; +import io.netty.handler.codec.http2.Http2Connection; +import io.netty.handler.codec.http2.Http2FrameCodecBuilder; +import io.netty.handler.codec.http2.Http2FrameLogger; +import io.netty.handler.codec.http2.Http2SecurityUtil; +import io.netty.handler.codec.http2.HttpConversionUtil; +import io.netty.handler.codec.http2.HttpToHttp2ConnectionHandler; +import io.netty.handler.codec.http2.HttpToHttp2ConnectionHandlerBuilder; +import io.netty.handler.codec.http2.InboundHttp2ToHttpAdapterBuilder; +import io.netty.handler.ssl.ApplicationProtocolConfig; +import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol; +import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior; +import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior; +import io.netty.handler.ssl.ApplicationProtocolNames; +import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.SslProvider; +import io.netty.handler.ssl.SupportedCipherSuiteFilter; +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import io.netty.handler.ssl.util.SelfSignedCertificate; + +public class Http2Util { + public static SslContext createSSLContext(boolean isServer) throws SSLException, CertificateException { + + SslContext sslCtx; + + SelfSignedCertificate ssc = new SelfSignedCertificate(); + + if (isServer) { + sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) + .sslProvider(SslProvider.JDK) + .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) + .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, + SelectorFailureBehavior.NO_ADVERTISE, + SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) + .build(); + } else { + sslCtx = SslContextBuilder.forClient() + .sslProvider(SslProvider.JDK) + .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, + SelectorFailureBehavior.NO_ADVERTISE, + SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2)) + .build(); + } + return sslCtx; + + } + + public static ApplicationProtocolNegotiationHandler getServerAPNHandler() { + ApplicationProtocolNegotiationHandler serverAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) { + + @Override + protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { + if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { + ctx.pipeline() + .addLast(Http2FrameCodecBuilder.forServer() + .build(), new Http2ServerResponseHandler()); + return; + } + throw new IllegalStateException("Protocol: " + protocol + " not supported"); + } + }; + return serverAPNHandler; + + } + + public static ApplicationProtocolNegotiationHandler getClientAPNHandler(int maxContentLength, Http2SettingsHandler settingsHandler, Http2ClientResponseHandler responseHandler) { + final Http2FrameLogger logger = new Http2FrameLogger(INFO, Http2Util.class); + final Http2Connection connection = new DefaultHttp2Connection(false); + + HttpToHttp2ConnectionHandler connectionHandler = new HttpToHttp2ConnectionHandlerBuilder() + .frameListener(new DelegatingDecompressorFrameListener(connection, new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength) + .propagateSettings(true) + .build())) + .frameLogger(logger) + .connection(connection) + .build(); + + ApplicationProtocolNegotiationHandler clientAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) { + @Override + protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { + if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { + ChannelPipeline p = ctx.pipeline(); + p.addLast(connectionHandler); + p.addLast(settingsHandler, responseHandler); + return; + } + ctx.close(); + throw new IllegalStateException("Protocol: " + protocol + " not supported"); + } + }; + + return clientAPNHandler; + + } + + public static FullHttpRequest createGetRequest(String host, int port) { + FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.valueOf("HTTP/2.0"), HttpMethod.GET, "/", Unpooled.EMPTY_BUFFER); + request.headers() + .add(HttpHeaderNames.HOST, new String(host + ":" + port)); + request.headers() + .add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), HttpScheme.HTTPS); + request.headers() + .add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); + request.headers() + .add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); + return request; + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientInitializer.java b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientInitializer.java new file mode 100644 index 0000000000..d50240fcb2 --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientInitializer.java @@ -0,0 +1,46 @@ +package com.baeldung.netty.http2.client; + +import com.baeldung.netty.http2.Http2Util; + +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.socket.SocketChannel; +import io.netty.handler.ssl.SslContext; + +public class Http2ClientInitializer extends ChannelInitializer { + + private final SslContext sslCtx; + private final int maxContentLength; + private Http2SettingsHandler settingsHandler; + private Http2ClientResponseHandler responseHandler; + private String host; + private int port; + + public Http2ClientInitializer(SslContext sslCtx, int maxContentLength, String host, int port) { + this.sslCtx = sslCtx; + this.maxContentLength = maxContentLength; + this.host = host; + this.port = port; + } + + @Override + public void initChannel(SocketChannel ch) throws Exception { + + settingsHandler = new Http2SettingsHandler(ch.newPromise()); + responseHandler = new Http2ClientResponseHandler(); + + if (sslCtx != null) { + ChannelPipeline pipeline = ch.pipeline(); + pipeline.addLast(sslCtx.newHandler(ch.alloc(), host, port)); + pipeline.addLast(Http2Util.getClientAPNHandler(maxContentLength, settingsHandler, responseHandler)); + } + } + + public Http2SettingsHandler getSettingsHandler() { + return settingsHandler; + } + + public Http2ClientResponseHandler getResponseHandler() { + return responseHandler; + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientResponseHandler.java b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientResponseHandler.java new file mode 100644 index 0000000000..4e17155bbc --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientResponseHandler.java @@ -0,0 +1,128 @@ +package com.baeldung.netty.http2.client; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.handler.codec.http2.HttpConversionUtil; +import io.netty.util.CharsetUtil; + +public class Http2ClientResponseHandler extends SimpleChannelInboundHandler { + + private final Logger logger = LoggerFactory.getLogger(Http2ClientResponseHandler.class); + private final Map streamidMap; + + public Http2ClientResponseHandler() { + streamidMap = new HashMap(); + } + + public MapValues put(int streamId, ChannelFuture writeFuture, ChannelPromise promise) { + return streamidMap.put(streamId, new MapValues(writeFuture, promise)); + } + + public String awaitResponses(long timeout, TimeUnit unit) { + + Iterator> itr = streamidMap.entrySet() + .iterator(); + + String response = null; + + while (itr.hasNext()) { + Entry entry = itr.next(); + ChannelFuture writeFuture = entry.getValue() + .getWriteFuture(); + + if (!writeFuture.awaitUninterruptibly(timeout, unit)) { + throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey()); + } + if (!writeFuture.isSuccess()) { + throw new RuntimeException(writeFuture.cause()); + } + ChannelPromise promise = entry.getValue() + .getPromise(); + + if (!promise.awaitUninterruptibly(timeout, unit)) { + throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey()); + } + if (!promise.isSuccess()) { + throw new RuntimeException(promise.cause()); + } + logger.info("---Stream id: " + entry.getKey() + " received---"); + response = entry.getValue().getResponse(); + + itr.remove(); + } + + return response; + + } + + @Override + protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { + Integer streamId = msg.headers() + .getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); + if (streamId == null) { + logger.error("HttpResponseHandler unexpected message received: " + msg); + return; + } + + MapValues value = streamidMap.get(streamId); + + if (value == null) { + logger.error("Message received for unknown stream id " + streamId); + ctx.close(); + } else { + ByteBuf content = msg.content(); + if (content.isReadable()) { + int contentLength = content.readableBytes(); + byte[] arr = new byte[contentLength]; + content.readBytes(arr); + String response = new String(arr, 0, contentLength, CharsetUtil.UTF_8); + logger.info("Response from Server: "+ (response)); + value.setResponse(response); + } + + value.getPromise() + .setSuccess(); + } + } + + public static class MapValues { + ChannelFuture writeFuture; + ChannelPromise promise; + String response; + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } + + public MapValues(ChannelFuture writeFuture2, ChannelPromise promise2) { + this.writeFuture = writeFuture2; + this.promise = promise2; + } + + public ChannelFuture getWriteFuture() { + return writeFuture; + } + + public ChannelPromise getPromise() { + return promise; + } + + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/client/Http2SettingsHandler.java b/netty/src/main/java/com/baeldung/netty/http2/client/Http2SettingsHandler.java new file mode 100644 index 0000000000..93841187c7 --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/client/Http2SettingsHandler.java @@ -0,0 +1,30 @@ +package com.baeldung.netty.http2.client; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http2.Http2Settings; + +import java.util.concurrent.TimeUnit; + +public class Http2SettingsHandler extends SimpleChannelInboundHandler { + private final ChannelPromise promise; + + public Http2SettingsHandler(ChannelPromise promise) { + this.promise = promise; + } + + public void awaitSettings(long timeout, TimeUnit unit) throws Exception { + if (!promise.awaitUninterruptibly(timeout, unit)) { + throw new IllegalStateException("Timed out waiting for settings"); + } + } + + @Override + protected void channelRead0(ChannelHandlerContext ctx, Http2Settings msg) throws Exception { + promise.setSuccess(); + + ctx.pipeline() + .remove(this); + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/server/Http2Server.java b/netty/src/main/java/com/baeldung/netty/http2/server/Http2Server.java new file mode 100644 index 0000000000..a8e9e59953 --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/server/Http2Server.java @@ -0,0 +1,59 @@ +package com.baeldung.netty.http2.server; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.netty.http2.Http2Util; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; +import io.netty.handler.ssl.SslContext; + +public final class Http2Server { + + private static final int PORT = 8443; + private static final Logger logger = LoggerFactory.getLogger(Http2Server.class); + + public static void main(String[] args) throws Exception { + SslContext sslCtx = Http2Util.createSSLContext(true); + + EventLoopGroup group = new NioEventLoopGroup(); + try { + ServerBootstrap b = new ServerBootstrap(); + b.option(ChannelOption.SO_BACKLOG, 1024); + b.group(group) + .channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + if (sslCtx != null) { + ch.pipeline() + .addLast(sslCtx.newHandler(ch.alloc()), Http2Util.getServerAPNHandler()); + } + } + + }); + + Channel ch = b.bind(PORT) + .sync() + .channel(); + + logger.info("HTTP/2 Server is listening on https://127.0.0.1:" + PORT + '/'); + + ch.closeFuture() + .sync(); + } finally { + group.shutdownGracefully(); + } + } + +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/server/Http2ServerResponseHandler.java b/netty/src/main/java/com/baeldung/netty/http2/server/Http2ServerResponseHandler.java new file mode 100644 index 0000000000..24c66f15bb --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/server/Http2ServerResponseHandler.java @@ -0,0 +1,52 @@ +package com.baeldung.netty.http2.server; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http2.DefaultHttp2DataFrame; +import io.netty.handler.codec.http2.DefaultHttp2Headers; +import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; +import io.netty.handler.codec.http2.Http2Headers; +import io.netty.handler.codec.http2.Http2HeadersFrame; +import io.netty.util.CharsetUtil; + +@Sharable +public class Http2ServerResponseHandler extends ChannelDuplexHandler { + + static final ByteBuf RESPONSE_BYTES = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8)); + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + super.exceptionCaught(ctx, cause); + cause.printStackTrace(); + ctx.close(); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof Http2HeadersFrame) { + Http2HeadersFrame msgHeader = (Http2HeadersFrame) msg; + if (msgHeader.isEndStream()) { + ByteBuf content = ctx.alloc() + .buffer(); + content.writeBytes(RESPONSE_BYTES.duplicate()); + + Http2Headers headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText()); + ctx.write(new DefaultHttp2HeadersFrame(headers).stream(msgHeader.stream())); + ctx.write(new DefaultHttp2DataFrame(content, true).stream(msgHeader.stream())); + } + + } else { + super.channelRead(ctx, msg); + } + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + +} diff --git a/netty/src/main/resources/logback.xml b/netty/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/netty/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/netty/src/test/java/com/baeldung/netty/Http2ClientLiveTest.java b/netty/src/test/java/com/baeldung/netty/Http2ClientLiveTest.java new file mode 100644 index 0000000000..6b9a53a1b3 --- /dev/null +++ b/netty/src/test/java/com/baeldung/netty/Http2ClientLiveTest.java @@ -0,0 +1,91 @@ +package com.baeldung.netty; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.netty.http2.Http2Util; +import com.baeldung.netty.http2.client.Http2ClientInitializer; +import com.baeldung.netty.http2.client.Http2ClientResponseHandler; +import com.baeldung.netty.http2.client.Http2SettingsHandler; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.ssl.SslContext; + +//Ensure the server class - Http2Server.java is already started before running this test +public class Http2ClientLiveTest { + + private static final Logger logger = LoggerFactory.getLogger(Http2ClientLiveTest.class); + + private static final String HOST = "127.0.0.1"; + private static final int PORT = 8443; + private SslContext sslCtx; + private Channel channel; + + @Before + public void setup() throws Exception { + sslCtx = Http2Util.createSSLContext(false); + } + + @Test + public void whenRequestSent_thenHelloWorldReceived() throws Exception { + + EventLoopGroup workerGroup = new NioEventLoopGroup(); + Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE, HOST, PORT); + + try { + Bootstrap b = new Bootstrap(); + b.group(workerGroup); + b.channel(NioSocketChannel.class); + b.option(ChannelOption.SO_KEEPALIVE, true); + b.remoteAddress(HOST, PORT); + b.handler(initializer); + + channel = b.connect() + .syncUninterruptibly() + .channel(); + + logger.info("Connected to [" + HOST + ':' + PORT + ']'); + + Http2SettingsHandler http2SettingsHandler = initializer.getSettingsHandler(); + http2SettingsHandler.awaitSettings(60, TimeUnit.SECONDS); + + logger.info("Sending request(s)..."); + + FullHttpRequest request = Http2Util.createGetRequest(HOST, PORT); + + Http2ClientResponseHandler responseHandler = initializer.getResponseHandler(); + int streamId = 3; + + responseHandler.put(streamId, channel.write(request), channel.newPromise()); + channel.flush(); + String response = responseHandler.awaitResponses(60, TimeUnit.SECONDS); + + assertEquals("Hello World", response); + + logger.info("Finished HTTP/2 request(s)"); + + } finally { + workerGroup.shutdownGracefully(); + } + + } + + @After + public void cleanup() { + channel.close() + .syncUninterruptibly(); + } +} diff --git a/ninja/pom.xml b/ninja/pom.xml index afb1d509b8..9b80dc26c8 100644 --- a/ninja/pom.xml +++ b/ninja/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 ninja @@ -10,19 +12,34 @@ http://www.ninjaframework.org - - 6.5.0 - 9.4.18.v20190429 - 3.3.4 - 2.1.3 - 1.4.186 - 3.2 - 1.8 - 1.8 - 1.3.1 - 2.8.2 - 2.2 - + + + org.webjars + bootstrap + ${bootstrap.version} + + + org.webjars + jquery + ${jquery.version} + + + com.h2database + h2 + ${h2.version} + + + org.ninjaframework + ninja-standalone + ${ninja.version} + + + org.ninjaframework + ninja-test-utilities + ${ninja.version} + test + + @@ -131,10 +148,8 @@ - - + + ninja.standalone.NinjaJetty @@ -161,32 +176,19 @@ - - - org.webjars - bootstrap - ${bootstrap.version} - - - org.webjars - jquery - ${jquery.version} - - - com.h2database - h2 - ${h2.version} - - - org.ninjaframework - ninja-standalone - ${ninja.version} - - - org.ninjaframework - ninja-test-utilities - ${ninja.version} - test - - + + + 6.5.0 + 9.4.18.v20190429 + 3.3.4 + 2.1.3 + 1.4.186 + 3.2 + 1.8 + 1.8 + 1.3.1 + 2.8.2 + 2.2 + + \ No newline at end of file diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 6e9e90a6d3..c7bb11b1d5 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -81,7 +81,7 @@ 3.3.0 1.0.22.RELEASE - 2.2.2.RELEASE + 2.2.6.RELEASE diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 27f355bfad..c75655ebc8 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -31,8 +31,8 @@ - 5.2.2.RELEASE - 5.2.1.RELEASE + 5.2.5.RELEASE + 5.2.3.RELEASE \ No newline at end of file diff --git a/patterns/solid/src/main/java/com/baeldung/s/TextManipulator.java b/patterns/solid/src/main/java/com/baeldung/s/TextManipulator.java new file mode 100644 index 0000000000..a6b32a0ff9 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/s/TextManipulator.java @@ -0,0 +1,35 @@ +package com.baeldung.s; + +public class TextManipulator { + private String text; + + public TextManipulator(String text) { + this.text = text; + } + + public String getText() { + return text; + } + + public void appendText(String newText) { + text = text.concat(newText); + } + + public void findWordAndReplace(String word, String replacementWord) { + if (text.contains(word)) { + text = text.replace(word, replacementWord); + } else System.out.println("Word you want to replace is not found in the text"); + } + + public void findWordAndDelete(String word) { + if (text.contains(word)) { + text = text.replace(word, ""); + } else System.out.println("Word you want to delete is not found in the text"); + } + + /* + * Bad practice when implementing SRP principle, not in the scope of this class + public void printText() { + System.out.println(textManipulator.getText()); + }*/ +} diff --git a/patterns/solid/src/main/java/com/baeldung/s/TextPrinter.java b/patterns/solid/src/main/java/com/baeldung/s/TextPrinter.java new file mode 100644 index 0000000000..d6a413e7ac --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/s/TextPrinter.java @@ -0,0 +1,23 @@ +package com.baeldung.s; + +import java.util.Arrays; + +public class TextPrinter { + TextManipulator textManipulator; + + public TextPrinter(TextManipulator textManipulator) { + this.textManipulator = textManipulator; + } + + public void printText() { + System.out.println(textManipulator.getText()); + } + + public void printOutEachWordOfText() { + System.out.println(Arrays.toString(textManipulator.getText().split(" "))); + } + + public void printRangeOfCharacters(int startingIndex, int endIndex) { + System.out.println(textManipulator.getText().substring(startingIndex, endIndex)); + } +} diff --git a/pdf/pom.xml b/pdf/pom.xml index 88836c5ce9..d148aa1670 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -13,12 +13,6 @@ - - commons-codec - commons-codec - ${commons-codec.version} - - org.apache.pdfbox pdfbox-tools @@ -86,7 +80,6 @@ 3.15 1.8 3.15 - 1.14 diff --git a/persistence-modules/flyway/pom.xml b/persistence-modules/flyway/pom.xml index 01b3dab6ee..f2e393abbf 100644 --- a/persistence-modules/flyway/pom.xml +++ b/persistence-modules/flyway/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -63,7 +63,7 @@ - 5.0.2 + 5.2.3 5.0.2 diff --git a/persistence-modules/flyway/src/main/resources/application.properties b/persistence-modules/flyway/src/main/resources/application.properties index 4d339eca5c..cee75fa4d9 100644 --- a/persistence-modules/flyway/src/main/resources/application.properties +++ b/persistence-modules/flyway/src/main/resources/application.properties @@ -1 +1 @@ -#flyway.enabled=false \ No newline at end of file +#spring.flyway.enabled=false \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/README.md b/persistence-modules/hibernate-annotations/README.md new file mode 100644 index 0000000000..393cf82bfd --- /dev/null +++ b/persistence-modules/hibernate-annotations/README.md @@ -0,0 +1,10 @@ +## Hibernate Annotations + +This module contains articles about Annotations used in Hibernate. + +### Relevant Articles: +- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types) +- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) +- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) +- [Hibernate One to Many Annotation Tutorial](https://www.baeldung.com/hibernate-one-to-many) +- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) diff --git a/persistence-modules/hibernate5-2/pom.xml b/persistence-modules/hibernate-annotations/pom.xml similarity index 64% rename from persistence-modules/hibernate5-2/pom.xml rename to persistence-modules/hibernate-annotations/pom.xml index 15d42b3244..5367921f31 100644 --- a/persistence-modules/hibernate5-2/pom.xml +++ b/persistence-modules/hibernate-annotations/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - hibernate5-2 + hibernate-annotations 0.1-SNAPSHOT - hibernate5-2 + hibernate-annotations jar Hibernate tutorial illustrating the use of named parameters @@ -20,32 +20,6 @@ hibernate-core ${hibernate-core.version} - - org.springframework.boot - spring-boot-starter-web - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-thymeleaf - ${spring-boot.version} - - - org.springframework.boot - spring-boot-starter-data-jpa - ${spring-boot.version} - - - com.zaxxer - HikariCP - - - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - com.h2database @@ -58,7 +32,32 @@ commons-lang3 ${commons.lang3.version} + + + org.hibernate + hibernate-testing + ${hibernate-core.version} + + + + org.hibernate + hibernate-spatial + ${hibernate-core.version} + + + org.opengeo + geodb + ${geodb.version} + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + 5.4.7.Final @@ -69,6 +68,7 @@ 5.4.7.Final 1.4.200 3.8.1 + 0.9 diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..afe2aeac89 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,73 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.joincolumn.Email; +import com.baeldung.hibernate.joincolumn.Office; +import com.baeldung.hibernate.joincolumn.OfficeAddress; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); + metadataSources.addAnnotatedClass(Email.class); + metadataSources.addAnnotatedClass(Office.class); + metadataSources.addAnnotatedClass(OfficeAddress.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/Salary.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/Group.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/Group.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/User.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java rename to persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java diff --git a/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-annotations/src/main/resources/logback.xml b/persistence-modules/hibernate-annotations/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate-annotations/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/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java rename to persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties rename to persistence-modules/hibernate-annotations/src/test/resources/hibernate-spatial.properties diff --git a/persistence-modules/hibernate5-2/src/test/resources/log4j.xml b/persistence-modules/hibernate-annotations/src/test/resources/log4j.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/test/resources/log4j.xml rename to persistence-modules/hibernate-annotations/src/test/resources/log4j.xml diff --git a/persistence-modules/hibernate5-2/src/test/resources/log4j2.xml b/persistence-modules/hibernate-annotations/src/test/resources/log4j2.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/test/resources/log4j2.xml rename to persistence-modules/hibernate-annotations/src/test/resources/log4j2.xml diff --git a/persistence-modules/hibernate5-2/src/test/resources/logback.xml b/persistence-modules/hibernate-annotations/src/test/resources/logback.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/test/resources/logback.xml rename to persistence-modules/hibernate-annotations/src/test/resources/logback.xml diff --git a/persistence-modules/hibernate-annotations/src/test/resources/profile.png b/persistence-modules/hibernate-annotations/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-annotations/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-enterprise/README.md b/persistence-modules/hibernate-enterprise/README.md new file mode 100644 index 0000000000..c5606d0970 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/README.md @@ -0,0 +1,12 @@ +## Hibernate Enterprise + +This module contains articles about enterprise concerns such as Multitenancy, Errors, Exceptions, Logging and more in Hibernate. + +### Relevant articles: + +- [Introduction to Hibernate Spatial](https://www.baeldung.com/hibernate-spatial) +- [A Guide to Multitenancy in Hibernate 5](https://www.baeldung.com/hibernate-5-multitenancy) +- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) +- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) +- [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) +- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/pom.xml b/persistence-modules/hibernate-enterprise/pom.xml new file mode 100644 index 0000000000..060cb4c904 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + hibernate-enterprise + 0.0.1-SNAPSHOT + hibernate-enterprise + + + com.baeldung + persistence-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-spatial + ${hibernate.version} + + + org.opengeo + geodb + ${geodb.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 0.9 + + + diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..ddeb1c42ea --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,72 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(PointEntity.class); + metadataSources.addAnnotatedClass(PolygonEntity.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/HibernateUtil.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/exception/Product.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernate/logging/Employee.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernate/logging/Employee.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java new file mode 100644 index 0000000000..736abde866 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -0,0 +1,43 @@ +package com.baeldung.hibernate.pojo; + +import com.vividsolutions.jts.geom.Point; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class PointEntity { + + @Id + @GeneratedValue + private Long id; + + @Column(columnDefinition="BINARY(2048)") + private Point point; + + public PointEntity() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Point getPoint() { + return point; + } + + public void setPoint(Point point) { + this.point = point; + } + + @Override + public String toString() { + return "PointEntity{" + "id=" + id + ", point=" + point + '}'; + } +} diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java new file mode 100644 index 0000000000..69208c8cd4 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo; + +import com.vividsolutions.jts.geom.Polygon; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class PolygonEntity { + + @Id + @GeneratedValue + private Long id; + + private Polygon polygon; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Polygon getPolygon() { + return polygon; + } + + public void setPolygon(Polygon polygon) { + this.polygon = polygon; + } + + @Override + public String toString() { + return "PolygonEntity{" + "id=" + id + ", polygon=" + polygon + '}'; + } +} diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java rename to persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernateparameters/Event.java diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml b/persistence-modules/hibernate-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml diff --git a/persistence-modules/hibernate5-2/src/main/resources/hibernate-logging.cfg.xml b/persistence-modules/hibernate-enterprise/src/main/resources/hibernate-logging.cfg.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/main/resources/hibernate-logging.cfg.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/hibernate-logging.cfg.xml diff --git a/persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml b/persistence-modules/hibernate-enterprise/src/main/resources/hibernate.cfg.xml similarity index 100% rename from persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml rename to persistence-modules/hibernate-enterprise/src/main/resources/hibernate.cfg.xml diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql b/persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/logback.xml b/persistence-modules/hibernate-enterprise/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/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/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/aggregatefunctions/AggregateFunctionsIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/logging/HibernateLoggingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java similarity index 100% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java rename to persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-multitenancy.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-multitenancy.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb1.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb1.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb2.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-database-mydb2.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-exception.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-schema-multitenancy.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate-schema-multitenancy.properties diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties new file mode 100644 index 0000000000..1657c838e3 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties @@ -0,0 +1,14 @@ +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.spatial.dialect.h2geodb.GeoDBDialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties rename to persistence-modules/hibernate-enterprise/src/test/resources/hibernate.properties diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-enterprise/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/profile.png b/persistence-modules/hibernate-enterprise/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-enterprise/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-jpa/README.md b/persistence-modules/hibernate-jpa/README.md new file mode 100644 index 0000000000..fb48f975bc --- /dev/null +++ b/persistence-modules/hibernate-jpa/README.md @@ -0,0 +1,16 @@ +## Hibernate JPA + +This module contains articles specific to use of Hibernate as a JPA implementation, such as Locking, Bootstrapping, One-to-One Relationship, Persistence Context, and more. + +### Relevant articles: + +- [JPA Attribute Converters](https://www.baeldung.com/jpa-attribute-converters) +- [Pessimistic Locking in JPA](https://www.baeldung.com/jpa-pessimistic-locking) +- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) +- [Optimistic Locking in JPA](https://www.baeldung.com/jpa-optimistic-locking) +- [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) +- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) +- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) +- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) +- [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) +- [Quick Guide to EntityManager#getReference()](https://www.baeldung.com/jpa-entity-manager-get-reference) diff --git a/persistence-modules/hibernate-jpa/pom.xml b/persistence-modules/hibernate-jpa/pom.xml new file mode 100644 index 0000000000..07b1ee1c51 --- /dev/null +++ b/persistence-modules/hibernate-jpa/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + hibernate-jpa + 0.0.1-SNAPSHOT + hibernate-jpa + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-thymeleaf + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + + com.zaxxer + HikariCP + + + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-spatial + ${hibernate.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk-jmh.version} + + + org.postgresql + postgresql + ${postgresql.version} + + + + + 5.3.7.Final + 8.0.13 + 42.2.11 + 2.2.3 + 3.8.0 + 1.21 + 2.1.7.RELEASE + + + diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..cf59fe4855 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,89 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; +import com.baeldung.hibernate.pessimisticlocking.Individual; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; +import com.baeldung.hibernate.pojo.Person; +import com.baeldung.hibernate.pojo.Post; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Person.class); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(Individual.class); + metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class); + metadataSources.addAnnotatedClass(PessimisticLockingStudent.class); + metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); + metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); + metadataSources.addAnnotatedClass(Post.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java new file mode 100644 index 0000000000..1de8de0327 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.entitymanager.getreference; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Game { + + @Id + private Long id; + + private String name; + + public Game() { + } + + public Game(Long id, String name) { + 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/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java new file mode 100644 index 0000000000..459a3a00ad --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.entitymanager.getreference; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Player { + + @Id + private Long id; + + private String name; + + @ManyToOne + private Game game; + + public Player() { + } + + public Player(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchService.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java similarity index 93% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java index c2f276472e..18fa2a41db 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java @@ -1,6 +1,5 @@ package com.baeldung.hibernate.onetoone; -import com.baeldung.hibernate.customtypes.LocalDateStringType; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; @@ -33,7 +32,6 @@ public class HibernateUtil { } Metadata metadata = metadataSources.getMetadataBuilder() - .applyBasicType(LocalDateStringType.INSTANCE) .build(); return metadata.getSessionFactoryBuilder() diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java new file mode 100644 index 0000000000..5fae7f6a97 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java @@ -0,0 +1,52 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "MOVIE") +public class Movie { + + @Id + private Long id; + + private String movieName; + + private Integer releaseYear; + + private String language; + + public String getMovieName() { + return movieName; + } + + public void setMovieName(String movieName) { + this.movieName = movieName; + } + + public Integer getReleaseYear() { + return releaseYear; + } + + public void setReleaseYear(Integer releaseYear) { + this.releaseYear = releaseYear; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java new file mode 100644 index 0000000000..335fe73f75 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/PersonName.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.pojo; + +import java.io.Serializable; + +public class PersonName implements Serializable { + + private static final long serialVersionUID = 7883094644631050150L; + + private String name; + + private String surname; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } + +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java new file mode 100644 index 0000000000..25e51e35d0 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java @@ -0,0 +1,59 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "posts") +public class Post { + + @Id + @GeneratedValue + private int id; + + private String title; + + private String body; + + public Post() { } + + public Post(String title, String body) { + this.title = title; + this.body = body; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + @Override + public String toString() { + return "Post{" + + "id=" + id + + ", title='" + title + '\'' + + ", body='" + body + '\'' + + '}'; + } +} diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/transaction/PostService.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/PersistenceContextDemoApplication.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/entity/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/entity/User.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java similarity index 100% rename from persistence-modules/hibernate5-2/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java rename to persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/create-db.sql b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/create-db.sql new file mode 100644 index 0000000000..7074b603f6 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/create-db.sql @@ -0,0 +1,3 @@ +create table Game (id bigint not null, name varchar(255), primary key (id)); +create table Player (id bigint not null, name varchar(255), game_id bigint, primary key (id)); +alter table Player add constraint FKohr86afuapoujklti79wo27aa foreign key (game_id) references Game(id); \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/data.sql b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/data.sql new file mode 100644 index 0000000000..1e83082801 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/data.sql @@ -0,0 +1,5 @@ +insert into Game (id, name) values (1, 'Game 1'); +insert into Game (id, name) values (2, 'Game 2'); +insert into Player (game_id, name, id) values (null, 'Player 1', 1); +insert into Player (game_id, name, id) values (null, 'Player 2', 2); +insert into Player (game_id, name, id) values (null, 'Player 3', 3); \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/drop-db.sql b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/drop-db.sql new file mode 100644 index 0000000000..275324fcae --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/drop-db.sql @@ -0,0 +1,2 @@ +drop table if exists Player; +drop table if exists Game; \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..c2d5bf59ab --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,103 @@ + + + + Hibernate EntityManager Demo + com.baeldung.hibernate.pojo.Movie + true + + + + + + + + + + + + EntityManager getReference persistence unit + com.baeldung.hibernate.entitymanager.getreference.Game + com.baeldung.hibernate.entitymanager.getreference.Player + true + + + + + + + + + + + + + + + + + + + EntityManager getReference persistence unit + com.baeldung.hibernate.entitymanager.getreference.Game + com.baeldung.hibernate.entitymanager.getreference.Player + true + + + + + + + + + + + + + + + + + + + + + + + + + EntityManager getReference persistence unit + com.baeldung.hibernate.entitymanager.getreference.Game + com.baeldung.hibernate.entitymanager.getreference.Player + true + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/init_database.sql b/persistence-modules/hibernate-jpa/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/src/main/resources/logback.xml b/persistence-modules/hibernate-jpa/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate-jpa/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/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java new file mode 100644 index 0000000000..e8e6aeed7c --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java @@ -0,0 +1,194 @@ +package com.baeldung.hibernate.entitymanager.getreference; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import org.junit.jupiter.api.*; +import org.slf4j.LoggerFactory; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class GetReferenceH2IntegrationTest { + + private static EntityManagerFactory entityManagerFactory; + private static EntityManager entityManager; + + private static final PrintStream SystemOut = System.out; + private static OutputStream output; + + @BeforeAll + public static void setup() { + // close some specific loggers so that we can clearly see Hibernate: SQL queries + ((Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.type.descriptor.sql")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.stat")).setLevel(Level.OFF); + + entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitymanager.game_player_h2"); + entityManager = entityManagerFactory.createEntityManager(); + entityManager.getTransaction().begin(); + + entityManager.persist(new Game(1L, "Game 1")); + entityManager.persist(new Game(2L, "Game 2")); + entityManager.persist(new Player(1L, "Player 1")); + entityManager.persist(new Player(2L, "Player 2")); + entityManager.persist(new Player(3L, "Player 3")); + + entityManager.getTransaction().commit(); + entityManager.clear(); + entityManager.close(); + } + + private void runInTransaction(Runnable task) { + // We create new persistence context for each test method to discard Hibernate first level cache. + // So that we can see the behavior of getReference() method in a non-cached environment. + entityManager = entityManagerFactory.createEntityManager(); + entityManager.getTransaction().begin(); + task.run(); + entityManager.getTransaction().commit(); + // In any case, we use clear() and close() to make all the managed entities detached and cleared. + // So, we can be sure we test always on a clear persistence context. + entityManager.clear(); + entityManager.close(); + } + + @BeforeEach + public void beforeEach() { + // stubbing System.out printStream + output = new ByteArrayOutputStream(); + System.setOut(new PrintStream(output)); + } + + @AfterEach + public void afterEach() { + System.setOut(SystemOut); + // we print to see original output after each test method + System.out.print(output.toString()); + } + + @AfterAll + public static void tearDown() { + entityManagerFactory.close(); + } + + @Test + public void whenUsingFindMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.find(Game.class, 1L); + game1.setName("Game Updated 1"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.getReference(Game.class, 1L); + game1.setName("Game Updated 2"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player2 = entityManager.find(Player.class, 2L); + entityManager.remove(player2); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player3 = entityManager.getReference(Player.class, 3L); + entityManager.remove(player3); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToUpdatePlayersGame_thenExecutesSelectForGame() { + + runInTransaction((() -> { + Game game1 = entityManager.find(Game.class, 1L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game1); + + entityManager.persist(player1); + })); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdatePlayersGame_thenDoesNotExecuteSelectForGame() { + + runInTransaction(() -> { + Game game2 = entityManager.getReference(Game.class, 2L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game2); + + entityManager.persist(player1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + +} diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java new file mode 100644 index 0000000000..2b7c5e8119 --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java @@ -0,0 +1,185 @@ +package com.baeldung.hibernate.entitymanager.getreference; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import org.junit.jupiter.api.*; +import org.slf4j.LoggerFactory; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * We need to have a running MySQL instance and a schema named "baeldung" ready in order to execute this integration test + */ +public class GetReferenceMySQLManualTest { + + private static EntityManagerFactory entityManagerFactory; + private static EntityManager entityManager; + + private static final PrintStream SystemOut = System.out; + private static OutputStream output; + + @BeforeAll + public static void setup() { + // close some specific loggers so that we can clearly see Hibernate: SQL queries + ((Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.type.descriptor.sql")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.stat")).setLevel(Level.OFF); + + entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitymanager.game_player_mysql"); + } + + private void runInTransaction(Runnable task) { + // We create new persistence context for each test method to discard Hibernate first level cache. + // So that we can see the behavior of getReference() method in a non-cached environment. + entityManager = entityManagerFactory.createEntityManager(); + entityManager.getTransaction().begin(); + task.run(); + entityManager.getTransaction().commit(); + // In any case, we use clear() and close() to make all the managed entities detached and cleared. + // So, we can be sure we test always on a clear persistence context. + entityManager.clear(); + entityManager.close(); + } + + @BeforeEach + public void beforeEach() { + // stubbing System.out printStream + output = new ByteArrayOutputStream(); + System.setOut(new PrintStream(output)); + } + + @AfterEach + public void afterEach() { + System.setOut(SystemOut); + // we print to see original output after each test method + System.out.print(output.toString()); + } + + @AfterAll + public static void tearDown() { + entityManagerFactory.close(); + } + + @Test + public void whenUsingFindMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.find(Game.class, 1L); + game1.setName("Game Updated 1"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.getReference(Game.class, 1L); + game1.setName("Game Updated 2"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player2 = entityManager.find(Player.class, 2L); + entityManager.remove(player2); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player3 = entityManager.getReference(Player.class, 3L); + entityManager.remove(player3); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToUpdatePlayersGame_thenExecutesSelectForGame() { + + runInTransaction((() -> { + Game game1 = entityManager.find(Game.class, 1L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game1); + + entityManager.persist(player1); + })); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdatePlayersGame_thenDoesNotExecuteSelectForGame() { + + runInTransaction(() -> { + Game game2 = entityManager.getReference(Game.class, 2L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game2); + + entityManager.persist(player1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + +} diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java new file mode 100644 index 0000000000..17f6b10b8a --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java @@ -0,0 +1,185 @@ +package com.baeldung.hibernate.entitymanager.getreference; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import org.junit.jupiter.api.*; +import org.slf4j.LoggerFactory; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * We need to have a running PostgreSQL instance in order to execute this integration test + */ +public class GetReferencePostgreSQLManualTest { + + private static EntityManagerFactory entityManagerFactory; + private static EntityManager entityManager; + + private static final PrintStream SystemOut = System.out; + private static OutputStream output; + + @BeforeAll + public static void setup() { + // close some specific loggers so that we can clearly see Hibernate: SQL queries + ((Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.type.descriptor.sql")).setLevel(Level.OFF); + ((Logger) LoggerFactory.getLogger("org.hibernate.stat")).setLevel(Level.OFF); + + entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitymanager.game_player_postgresql"); + } + + private void runInTransaction(Runnable task) { + // We create new persistence context for each test method to discard Hibernate first level cache. + // So that we can see the behavior of getReference() method in a non-cached environment. + entityManager = entityManagerFactory.createEntityManager(); + entityManager.getTransaction().begin(); + task.run(); + entityManager.getTransaction().commit(); + // In any case, we use clear() and close() to make all the managed entities detached and cleared. + // So, we can be sure we test always on a clear persistence context. + entityManager.clear(); + entityManager.close(); + } + + @BeforeEach + public void beforeEach() { + // stubbing System.out printStream + output = new ByteArrayOutputStream(); + System.setOut(new PrintStream(output)); + } + + @AfterEach + public void afterEach() { + System.setOut(SystemOut); + // we print to see original output after each test method + System.out.print(output.toString()); + } + + @AfterAll + public static void tearDown() { + entityManagerFactory.close(); + } + + @Test + public void whenUsingFindMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.find(Game.class, 1L); + game1.setName("Game Updated 1"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdateGame_thenExecutesSelectForGame() { + + runInTransaction(() -> { + Game game1 = entityManager.getReference(Game.class, 1L); + game1.setName("Game Updated 2"); + + entityManager.persist(game1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: update Game set name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player2 = entityManager.find(Player.class, 2L); + entityManager.remove(player2); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToDeletePlayer_thenExecutesSelectForPlayer() { + + runInTransaction(() -> { + Player player3 = entityManager.getReference(Player.class, 3L); + entityManager.remove(player3); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: delete from Player where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingFindMethodToUpdatePlayersGame_thenExecutesSelectForGame() { + + runInTransaction((() -> { + Game game1 = entityManager.find(Game.class, 1L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game1); + + entityManager.persist(player1); + })); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n"); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + + @Test + public void whenUsingGetReferenceMethodToUpdatePlayersGame_thenDoesNotExecuteSelectForGame() { + + runInTransaction(() -> { + Game game2 = entityManager.getReference(Game.class, 2L); + + Player player1 = entityManager.find(Player.class, 1L); + player1.setGame(game2); + + entityManager.persist(player1); + }); + + StringBuilder expected = new StringBuilder(); + expected.append("Hibernate: select "); + expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, "); + expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ "); + expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n"); + expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n"); + + assertEquals(expected.toString(), output.toString()); + } + +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java diff --git a/persistence-modules/hibernate5-2/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5-2/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java rename to persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-namedquery.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties rename to persistence-modules/hibernate-jpa/src/test/resources/hibernate-namedquery.properties diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties similarity index 100% rename from persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties rename to persistence-modules/hibernate-jpa/src/test/resources/hibernate-pessimistic-locking.properties diff --git a/persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties b/persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-jpa/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +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 + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-jpa/src/test/resources/profile.png b/persistence-modules/hibernate-jpa/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-jpa/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 5bbdeecbea..b5d0cb2f99 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -7,5 +7,9 @@ This module contains articles about Object-relational Mapping (ORM) with Hiberna - [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) -- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) +- [Dynamic Mapping with Hibernate](https://www.baeldung.com/hibernate-dynamic-mapping) +- [Hibernate Inheritance Mapping](https://www.baeldung.com/hibernate-inheritance) +- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) +- [Hibernate – Mapping Date and Time](https://www.baeldung.com/hibernate-date-time) +- [Mapping LOB Data in Hibernate](https://www.baeldung.com/hibernate-lob) +- [FetchMode in Hibernate](https://www.baeldung.com/hibernate-fetchmode) diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index ac7952fa2b..4eabc5d298 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -51,15 +51,28 @@ ${moneta.version} pom + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + commons-io + commons-io + ${commons-io.version} + + - 5.3.10.Final + 5.4.12.Final 3.8.0 6.0.16.Final 3.0.1-b11 1.0.3 1.3 + 3.9 + 2.6 diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 7de13db8d3..fbd8bd487b 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,21 +1,48 @@ package com.baeldung.hibernate; -import org.hibernate.SessionFactory; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.service.ServiceRegistry; - import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.Properties; -public class HibernateUtil { +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.Phone; +import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.inheritance.Animal; +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.MyProduct; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; +import com.baeldung.hibernate.pojo.inheritance.Vehicle; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; private HibernateUtil() { } + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(""); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + if(propertyFileName.equals("")) propertyFileName = null; + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + public static SessionFactory getSessionFactory(Strategy strategy) { return buildSessionFactory(strategy); } @@ -40,6 +67,35 @@ public class HibernateUtil { } } + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Employee.class); + metadataSources.addAnnotatedClass(Phone.class); + metadataSources.addAnnotatedClass(EntityDescription.class); + metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(Animal.class); + metadataSources.addAnnotatedClass(Bag.class); + metadataSources.addAnnotatedClass(Book.class); + metadataSources.addAnnotatedClass(Car.class); + metadataSources.addAnnotatedClass(MyEmployee.class); + metadataSources.addAnnotatedClass(MyProduct.class); + metadataSources.addAnnotatedClass(Pen.class); + metadataSources.addAnnotatedClass(Pet.class); + metadataSources.addAnnotatedClass(Vehicle.class); + + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + private static ServiceRegistry configureServiceRegistry() throws IOException { Properties properties = getProperties(); @@ -51,7 +107,7 @@ public class HibernateUtil { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() - .getResource("hibernate.properties"); + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java new file mode 100644 index 0000000000..e9732b2b67 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java @@ -0,0 +1,87 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.*; + +import javax.persistence.Entity; +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Where(clause = "deleted = false") +@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int")) +@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit") +public class Employee implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private long grossIncome; + + private int taxInPercents; + + private boolean deleted; + + public long getTaxJavaWay() { + return grossIncome * taxInPercents / 100; + } + + @Formula("grossIncome * taxInPercents / 100") + private long tax; + + @OneToMany + @JoinColumn(name = "employee_id") + @Where(clause = "deleted = false") + private Set phones = new HashSet<>(0); + + public Employee() { + } + + public Employee(long grossIncome, int taxInPercents) { + this.grossIncome = grossIncome; + this.taxInPercents = taxInPercents; + } + + public Integer getId() { + return id; + } + + public long getGrossIncome() { + return grossIncome; + } + + public int getTaxInPercents() { + return taxInPercents; + } + + public long getTax() { + return tax; + } + + public void setId(Integer id) { + this.id = id; + } + + public void setGrossIncome(long grossIncome) { + this.grossIncome = grossIncome; + } + + public void setTaxInPercents(int taxInPercents) { + this.taxInPercents = taxInPercents; + } + + public boolean getDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public Set getPhones() { + return phones; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java new file mode 100644 index 0000000000..131bb73a80 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java @@ -0,0 +1,55 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.Any; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class EntityDescription implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private String description; + + @Any( + metaDef = "EntityDescriptionMetaDef", + metaColumn = @Column(name = "entity_type") + ) + @JoinColumn(name = "entity_id") + private Serializable entity; + + public EntityDescription() { + } + + public EntityDescription(String description, Serializable entity) { + this.description = description; + this.entity = entity; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Serializable getEntity() { + return entity; + } + + public void setEntity(Serializable entity) { + this.entity = entity; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java new file mode 100644 index 0000000000..607269a267 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Result.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +public class Result { + private String employeeName; + + private String departmentName; + + public Result(String employeeName, String departmentName) { + this.employeeName = employeeName; + this.departmentName = departmentName; + } + + public Result() { + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } + + public String getDepartmentName() { + return departmentName; + } + + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java new file mode 100644 index 0000000000..f3fe095cae --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java @@ -0,0 +1,195 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.*; +import java.io.Serializable; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.*; +import java.util.Calendar; + +@Entity +public class TemporalValues implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @Basic + private java.sql.Date sqlDate; + + @Basic + private java.sql.Time sqlTime; + + @Basic + private java.sql.Timestamp sqlTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Date utilDate; + + @Basic + @Temporal(TemporalType.TIME) + private java.util.Date utilTime; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Date utilTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Calendar calendarDate; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Calendar calendarTimestamp; + + @Basic + private java.time.LocalDate localDate; + + @Basic + private java.time.LocalTime localTime; + + @Basic + private java.time.OffsetTime offsetTime; + + @Basic + private java.time.Instant instant; + + @Basic + private java.time.LocalDateTime localDateTime; + + @Basic + private java.time.OffsetDateTime offsetDateTime; + + @Basic + private java.time.ZonedDateTime zonedDateTime; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(Date sqlDate) { + this.sqlDate = sqlDate; + } + + public Time getSqlTime() { + return sqlTime; + } + + public void setSqlTime(Time sqlTime) { + this.sqlTime = sqlTime; + } + + public Timestamp getSqlTimestamp() { + return sqlTimestamp; + } + + public void setSqlTimestamp(Timestamp sqlTimestamp) { + this.sqlTimestamp = sqlTimestamp; + } + + public java.util.Date getUtilDate() { + return utilDate; + } + + public void setUtilDate(java.util.Date utilDate) { + this.utilDate = utilDate; + } + + public java.util.Date getUtilTime() { + return utilTime; + } + + public void setUtilTime(java.util.Date utilTime) { + this.utilTime = utilTime; + } + + public java.util.Date getUtilTimestamp() { + return utilTimestamp; + } + + public void setUtilTimestamp(java.util.Date utilTimestamp) { + this.utilTimestamp = utilTimestamp; + } + + public Calendar getCalendarDate() { + return calendarDate; + } + + public void setCalendarDate(Calendar calendarDate) { + this.calendarDate = calendarDate; + } + + public Calendar getCalendarTimestamp() { + return calendarTimestamp; + } + + public void setCalendarTimestamp(Calendar calendarTimestamp) { + this.calendarTimestamp = calendarTimestamp; + } + + public LocalDate getLocalDate() { + return localDate; + } + + public void setLocalDate(LocalDate localDate) { + this.localDate = localDate; + } + + public LocalTime getLocalTime() { + return localTime; + } + + public void setLocalTime(LocalTime localTime) { + this.localTime = localTime; + } + + public OffsetTime getOffsetTime() { + return offsetTime; + } + + public void setOffsetTime(OffsetTime offsetTime) { + this.offsetTime = offsetTime; + } + + public Instant getInstant() { + return instant; + } + + public void setInstant(Instant instant) { + this.instant = instant; + } + + public LocalDateTime getLocalDateTime() { + return localDateTime; + } + + public void setLocalDateTime(LocalDateTime localDateTime) { + this.localDateTime = localDateTime; + } + + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } + + public void setOffsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + } + + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } + + public void setZonedDateTime(ZonedDateTime zonedDateTime) { + this.zonedDateTime = zonedDateTime; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java new file mode 100644 index 0000000000..17ffe9b7e1 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.pojo.generator; + +import java.io.Serializable; +import java.util.Properties; +import java.util.stream.Stream; + +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.id.Configurable; +import org.hibernate.id.IdentifierGenerator; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.type.Type; + +public class MyGenerator implements IdentifierGenerator, Configurable { + + private String prefix; + + @Override + public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException { + + String query = String.format("select %s from %s", + session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(), + obj.getClass().getSimpleName()); + + Stream ids = session.createQuery(query).stream(); + + Long max = ids.map(o -> o.replace(prefix + "-", "")) + .mapToLong(Long::parseLong) + .max() + .orElse(0L); + + return prefix + "-" + (max + 1); + } + + @Override + public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException { + prefix = properties.getProperty("prefix"); + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java new file mode 100644 index 0000000000..6fe7f915fc --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.JOINED) +public class Animal { + + @Id + private long animalId; + + private String species; + + public Animal() {} + + public Animal(long animalId, String species) { + this.animalId = animalId; + this.species = species; + } + + public long getAnimalId() { + return animalId; + } + + public void setAnimalId(long animalId) { + this.animalId = animalId; + } + + public String getSpecies() { + return species; + } + + public void setSpecies(String species) { + this.species = species; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java new file mode 100644 index 0000000000..fa6e1b4bef --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.hibernate.annotations.Polymorphism; +import org.hibernate.annotations.PolymorphismType; + +@Entity +@Polymorphism(type = PolymorphismType.EXPLICIT) +public class Bag implements Item { + + @Id + private long bagId; + + private String type; + + public Bag(long bagId, String type) { + this.bagId = bagId; + this.type = type; + } + + public long getBagId() { + return bagId; + } + + public void setBagId(long bagId) { + this.bagId = bagId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java new file mode 100644 index 0000000000..36ca8dd77c --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("1") +public class Book extends MyProduct { + private String author; + + public Book() { + } + + public Book(long productId, String name, String author) { + super(productId, name); + this.author = author; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java new file mode 100644 index 0000000000..49d1f7749a --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class Car extends Vehicle { + private String engine; + + public Car() { + } + + public Car(long vehicleId, String manufacturer, String engine) { + super(vehicleId, manufacturer); + this.engine = engine; + } + + public String getEngine() { + return engine; + } + + public void setEngine(String engine) { + this.engine = engine; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java new file mode 100644 index 0000000000..9656030736 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java @@ -0,0 +1,5 @@ +package com.baeldung.hibernate.pojo.inheritance; + +public interface Item { + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java new file mode 100644 index 0000000000..9a6bce16cf --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java @@ -0,0 +1,22 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class MyEmployee extends Person { + private String company; + + public MyEmployee(long personId, String name, String company) { + super(personId, name); + this.company = company; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java new file mode 100644 index 0000000000..13f04d8904 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +import org.hibernate.annotations.DiscriminatorFormula; + +@Entity +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "product_type", discriminatorType = DiscriminatorType.INTEGER) +// @DiscriminatorFormula("case when author is not null then 1 else 2 end") +public class MyProduct { + @Id + private long productId; + + private String name; + + public MyProduct() { + } + + public MyProduct(long productId, String name) { + super(); + this.productId = productId; + this.name = name; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java new file mode 100644 index 0000000000..32b77e52af --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("2") +public class Pen extends MyProduct { + private String color; + + public Pen() { + } + + public Pen(long productId, String name, String color) { + super(productId, name); + this.color = color; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java new file mode 100644 index 0000000000..99084b88af --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; + +@MappedSuperclass +public class Person { + + @Id + private long personId; + + private String name; + + public Person() { + } + + public Person(long personId, String name) { + this.personId = personId; + this.name = name; + } + + public long getPersonId() { + return personId; + } + + public void setPersonId(long personId) { + this.personId = personId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java new file mode 100644 index 0000000000..870b3cd684 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.PrimaryKeyJoinColumn; + +@Entity +@PrimaryKeyJoinColumn(name = "petId") +public class Pet extends Animal { + private String name; + + public Pet() { + } + + public Pet(long animalId, String species, String name) { + super(animalId, species); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java new file mode 100644 index 0000000000..b2a920573e --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) +public class Vehicle { + @Id + private long vehicleId; + + private String manufacturer; + + public Vehicle() { + } + + public Vehicle(long vehicleId, String manufacturer) { + this.vehicleId = vehicleId; + this.manufacturer = manufacturer; + } + + public long getVehicleId() { + return vehicleId; + } + + public void setVehicleId(long vehicleId) { + this.vehicleId = vehicleId; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + +} diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java new file mode 100644 index 0000000000..992cda7c1d --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java @@ -0,0 +1,9 @@ +@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int", + metaValues = { + @MetaValue(value = "Employee", targetEntity = Employee.class), + @MetaValue(value = "Phone", targetEntity = Phone.class) + }) +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.AnyMetaDef; +import org.hibernate.annotations.MetaValue; \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java diff --git a/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties b/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +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 + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-mapping/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-mapping/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping/src/test/resources/profile.png b/persistence-modules/hibernate-mapping/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-mapping/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate-queries/README.md b/persistence-modules/hibernate-queries/README.md new file mode 100644 index 0000000000..61d94e32de --- /dev/null +++ b/persistence-modules/hibernate-queries/README.md @@ -0,0 +1,10 @@ +## Hibernate Queries + +This module contains articles about use of Queries in Hibernate. + +### Relevant articles: + +- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel) +- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) +- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) +- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml new file mode 100644 index 0000000000..a439ded9df --- /dev/null +++ b/persistence-modules/hibernate-queries/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + hibernate-queries + 0.0.1-SNAPSHOT + hibernate-queries + + + com.baeldung + persistence-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-spatial + ${hibernate.version} + + + org.opengeo + geodb + ${geodb.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + ch.vorburger.mariaDB4j + mariaDB4j + ${mariaDB4j.version} + + + org.hibernate + hibernate-testing + ${hibernate.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk-jmh.version} + + + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + + + + 5.3.7.Final + 6.0.6 + 2.2.3 + 3.8.0 + 0.9 + 1.21 + + + diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..58724e690c --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,73 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.customtypes.LocalDateStringType; +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .applyBasicType(LocalDateStringType.INSTANCE) + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java new file mode 100644 index 0000000000..56be9e693f --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.type.LocalDateType; +import org.hibernate.type.descriptor.WrapperOptions; +import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; +import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; +import org.hibernate.type.descriptor.java.MutabilityPlan; + +import java.time.LocalDate; + +public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor { + + public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); + + public LocalDateStringJavaDescriptor() { + super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE); + } + + @Override + public String toString(LocalDate value) { + return LocalDateType.FORMATTER.format(value); + } + + @Override + public LocalDate fromString(String string) { + return LocalDate.from(LocalDateType.FORMATTER.parse(string)); + } + + @Override + public X unwrap(LocalDate value, Class type, WrapperOptions options) { + + if (value == null) + return null; + + if (String.class.isAssignableFrom(type)) + return (X) LocalDateType.FORMATTER.format(value); + + throw unknownUnwrap(type); + } + + @Override + public LocalDate wrap(X value, WrapperOptions options) { + if (value == null) + return null; + + if(String.class.isInstance(value)) + return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value)); + + throw unknownWrap(value.getClass()); + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java new file mode 100644 index 0000000000..c8d37073e8 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.customtypes; + +import org.hibernate.dialect.Dialect; +import org.hibernate.type.AbstractSingleColumnStandardBasicType; +import org.hibernate.type.DiscriminatorType; +import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor; +import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; + +import java.time.LocalDate; + +public class LocalDateStringType extends AbstractSingleColumnStandardBasicType implements DiscriminatorType { + + public static final LocalDateStringType INSTANCE = new LocalDateStringType(); + + public LocalDateStringType() { + super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); + } + + @Override + public String getName() { + return "LocalDateString"; + } + + @Override + public LocalDate stringToObject(String xml) throws Exception { + return fromString(xml); + } + + @Override + public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception { + return '\'' + toString(value) + '\''; + } + +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java similarity index 100% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java rename to persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..474eeb7a44 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + Hibernate EntityManager Demo + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/main/resources/init_database.sql b/persistence-modules/hibernate-queries/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/main/resources/logback.xml b/persistence-modules/hibernate-queries/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate-queries/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/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java similarity index 100% rename from persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java diff --git a/persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/hibernate-customtypes.properties @@ -0,0 +1,14 @@ +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 + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties new file mode 100644 index 0000000000..457f965347 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/hibernate-namedquery.properties @@ -0,0 +1,9 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql' +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 \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/hibernate.properties b/persistence-modules/hibernate-queries/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +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 + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate-queries/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate-queries/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/profile.png b/persistence-modules/hibernate-queries/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate-queries/src/test/resources/profile.png differ diff --git a/persistence-modules/hibernate5-2/README.md b/persistence-modules/hibernate5-2/README.md deleted file mode 100644 index 330708f6d3..0000000000 --- a/persistence-modules/hibernate5-2/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Hibernate 5 - -This module contains articles about Hibernate 5. - -### Relevant Articles: -- [Hibernate Error “Not all named parameters have been set”](https://www.baeldung.com/hibernate-error-named-parameters-not-set) -- [FetchMode in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-fetchmode) -- [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) -- [FetchMode in Hibernate](https://www.baeldung.com/hibernate-fetchmode) -- [Various Logging Levels in Hibernate](https://www.baeldung.com/hibernate-logging-levels) -- [[<-- Prev]](/hibernate5) diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index d1bfe897f6..bd437c80eb 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -1,41 +1,15 @@ ## Hibernate 5 -This module contains articles about Hibernate 5. +This module contains articles about Hibernate 5. Let's not add more articles here, we should not be creating a -2 out of it. Please add to other existing hibernate-* modules, or create a new one. ### Relevant articles: -- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) -- [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers) -- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time) -- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance) -- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy) -- [Introduction to Hibernate Spatial](http://www.baeldung.com/hibernate-spatial) -- [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor) -- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters) -- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) -- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) -- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) -- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) -- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking) +- [An Overview of Identifiers in Hibernate](https://www.baeldung.com/hibernate-identifiers) +- [Hibernate Interceptors](https://www.baeldung.com/hibernate-interceptor) - [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle) -- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) -- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) - [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy) - [Proxy in Hibernate load() Method](https://www.baeldung.com/hibernate-proxy-load-method) -- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types) -- [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions) -- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) - [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api) -- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel) - [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager) -- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) -- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) -- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) -- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) -- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) -- [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) -- [[Next -->]](/hibernate5-2) \ No newline at end of file +- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) \ No newline at end of file diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index ffeff5ee4a..7f04abc09f 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -77,7 +77,7 @@ - 5.3.7.Final + 5.4.12.Final 6.0.6 2.2.3 3.8.0 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 137fc4f0bd..11a59c9cf0 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -12,25 +12,13 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; -import com.baeldung.hibernate.customtypes.LocalDateStringType; -import com.baeldung.hibernate.customtypes.OfficeEmployee; import com.baeldung.hibernate.entities.DeptEmployee; -import com.baeldung.hibernate.joincolumn.Email; -import com.baeldung.hibernate.joincolumn.Office; -import com.baeldung.hibernate.joincolumn.OfficeAddress; -import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; -import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; -import com.baeldung.hibernate.pessimisticlocking.Individual; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; -import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; import com.baeldung.hibernate.pojo.Course; import com.baeldung.hibernate.pojo.Employee; import com.baeldung.hibernate.pojo.EntityDescription; import com.baeldung.hibernate.pojo.OrderEntry; import com.baeldung.hibernate.pojo.OrderEntryIdClass; import com.baeldung.hibernate.pojo.OrderEntryPK; -import com.baeldung.hibernate.pojo.Person; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.PointEntity; import com.baeldung.hibernate.pojo.PolygonEntity; @@ -88,7 +76,6 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(MyEmployee.class); metadataSources.addAnnotatedClass(MyProduct.class); metadataSources.addAnnotatedClass(Pen.class); - metadataSources.addAnnotatedClass(Person.class); metadataSources.addAnnotatedClass(Animal.class); metadataSources.addAnnotatedClass(Pet.class); metadataSources.addAnnotatedClass(Vehicle.class); @@ -96,26 +83,11 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Bag.class); metadataSources.addAnnotatedClass(PointEntity.class); metadataSources.addAnnotatedClass(PolygonEntity.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class); - metadataSources.addAnnotatedClass(Individual.class); - metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class); - metadataSources.addAnnotatedClass(PessimisticLockingStudent.class); - metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); metadataSources.addAnnotatedClass(DeptEmployee.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); - metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); - metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); - metadataSources.addAnnotatedClass(OfficeEmployee.class); metadataSources.addAnnotatedClass(Post.class); - metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); - metadataSources.addAnnotatedClass(Email.class); - metadataSources.addAnnotatedClass(Office.class); - metadataSources.addAnnotatedClass(OfficeAddress.class); Metadata metadata = metadataSources.getMetadataBuilder() - .applyBasicType(LocalDateStringType.INSTANCE) .build(); return metadata.getSessionFactoryBuilder() diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java index 736abde866..7a88a8bedc 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -1,12 +1,13 @@ package com.baeldung.hibernate.pojo; -import com.vividsolutions.jts.geom.Point; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import org.locationtech.jts.geom.Point; + @Entity public class PointEntity { diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java index 69208c8cd4..3144a88a16 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -1,11 +1,11 @@ package com.baeldung.hibernate.pojo; -import com.vividsolutions.jts.geom.Polygon; - import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import org.locationtech.jts.geom.Polygon; + @Entity public class PolygonEntity { diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 54879fb321..091efaeff4 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -18,6 +18,12 @@ cassandra-driver-core ${cassandra-driver-core.version} true + + + com.google.guava + guava + + diff --git a/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml b/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml new file mode 100644 index 0000000000..59687444d0 --- /dev/null +++ b/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml @@ -0,0 +1,51 @@ +cluster_name: 'Test Cluster' +hinted_handoff_enabled: true +max_hint_window_in_ms: 10800000 +hinted_handoff_throttle_in_kb: 1024 +max_hints_delivery_threads: 2 +hints_directory: target/embeddedCassandra/hints +authenticator: AllowAllAuthenticator +authorizer: AllowAllAuthorizer +permissions_validity_in_ms: 2000 +partitioner: RandomPartitioner +data_file_directories: + - target/embeddedCassandra/data +commitlog_directory: target/embeddedCassandra/commitlog +cdc_raw_directory: target/embeddedCassandra/cdc +disk_failure_policy: stop +key_cache_size_in_mb: +key_cache_save_period: 14400 +row_cache_size_in_mb: 0 +row_cache_save_period: 0 +saved_caches_directory: target/embeddedCassandra/saved_caches +commitlog_sync: periodic +commitlog_sync_period_in_ms: 10000 +commitlog_segment_size_in_mb: 32 +concurrent_reads: 32 +concurrent_writes: 32 +trickle_fsync: false +trickle_fsync_interval_in_kb: 10240 +thrift_framed_transport_size_in_mb: 15 +thrift_max_message_length_in_mb: 16 +incremental_backups: false +snapshot_before_compaction: false +auto_snapshot: false +column_index_size_in_kb: 64 +compaction_throughput_mb_per_sec: 16 +read_request_timeout_in_ms: 5000 +range_request_timeout_in_ms: 10000 +write_request_timeout_in_ms: 2000 +cas_contention_timeout_in_ms: 1000 +truncate_request_timeout_in_ms: 60000 +request_timeout_in_ms: 10000 +cross_node_timeout: false +endpoint_snitch: SimpleSnitch +dynamic_snitch_update_interval_in_ms: 100 +dynamic_snitch_reset_interval_in_ms: 600000 +dynamic_snitch_badness_threshold: 0.1 +request_scheduler: org.apache.cassandra.scheduler.NoScheduler +index_interval: 128 +seed_provider: + - class_name: org.apache.cassandra.locator.SimpleSeedProvider + parameters: + - seeds: "127.0.0.1" diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index a8539e644f..5c3c448b03 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -10,3 +10,4 @@ This module contains articles about MongoDB in Java. - [Geospatial Support in MongoDB](https://www.baeldung.com/mongodb-geospatial-support) - [Introduction to Morphia – Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia) - [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) +- [MongoDB BSON to JSON](https://www.baeldung.com/bson-to-json) 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 index 172c916ad9..4ed2ab8580 100644 --- 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 @@ -1,5 +1,7 @@ package com.baeldung.morphia.domain; +import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; @@ -29,28 +31,13 @@ public class Book { private double cost; @Reference private Set companionBooks; + @Property + private LocalDateTime publishDate; 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; @@ -60,6 +47,71 @@ public class Book { this.companionBooks = new HashSet<>(); } + // Getters and setters ... + public String getIsbn() { + return isbn; + } + + public Book setIsbn(String isbn) { + this.isbn = isbn; + return this; + } + + public String getTitle() { + return title; + } + + public Book setTitle(String title) { + this.title = title; + return this; + } + + public String getAuthor() { + return author; + } + + public Book setAuthor(String author) { + this.author = author; + return this; + } + + public Publisher getPublisher() { + return publisher; + } + + public Book setPublisher(Publisher publisher) { + this.publisher = publisher; + return this; + } + + public double getCost() { + return cost; + } + + public Book setCost(double cost) { + this.cost = cost; + return this; + } + + public LocalDateTime getPublishDate() { + return publishDate; + } + + public Book setPublishDate(LocalDateTime publishDate) { + this.publishDate = publishDate; + return this; + } + + public Set getCompanionBooks() { + return companionBooks; + } + + public Book addCompanionBooks(Book book) { + if (companionBooks != null) + this.companionBooks.add(book); + return this; + } + @Override public String toString() { return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]"; @@ -113,4 +165,4 @@ public class Book { return true; } -} \ No newline at end of file +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java new file mode 100644 index 0000000000..e382ea4ab2 --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java @@ -0,0 +1,142 @@ +package com.baeldung.bsontojson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.bson.Document; +import org.bson.json.Converter; +import org.bson.json.JsonMode; +import org.bson.json.JsonWriterSettings; +import org.bson.json.StrictJsonWriter; +import org.bson.types.ObjectId; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.morphia.domain.Book; +import com.baeldung.morphia.domain.Publisher; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoDatabase; + +import dev.morphia.Datastore; +import dev.morphia.Morphia; + +public class BsonToJsonIntegrationTest { + + private static final String DB_NAME = "library"; + private static Datastore datastore; + + @BeforeClass + public static void setUp() { + Morphia morphia = new Morphia(); + morphia.mapPackage("com.baeldung.morphia"); + datastore = morphia.createDatastore(new MongoClient(), DB_NAME); + datastore.ensureIndexes(); + + datastore.save(new Book() + .setIsbn("isbn") + .setTitle("title") + .setAuthor("author") + .setCost(3.95) + .setPublisher(new Publisher(new ObjectId("fffffffffffffffffffffffa"),"publisher")) + .setPublishDate(LocalDateTime.parse("2020-01-01T18:13:32Z", DateTimeFormatter.ISO_DATE_TIME)) + .addCompanionBooks(new Book().setIsbn("isbn2"))); + } + + @AfterClass + public static void tearDown() { + datastore.delete(datastore.createQuery(Book.class)); + } + + @Test + public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": {\"$date\": 1577898812000}}"; + + assertNotNull(json); + + assertEquals(expectedJson, json); + } + + + @Test + public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(JsonWriterSettings + .builder() + .outputMode(JsonMode.RELAXED) + .build()); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}"; + + assertNotNull(json); + + assertEquals(expectedJson, json); + } + + @Test + public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(JsonWriterSettings + .builder() + .dateTimeConverter(new JsonDateTimeConverter()) + .build()); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": \"2020-01-01T17:13:32Z\"}"; + + assertEquals(expectedJson, json); + + } + +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java new file mode 100644 index 0000000000..46023e363f --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java @@ -0,0 +1,30 @@ +package com.baeldung.bsontojson; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.TimeZone; + +import org.bson.json.Converter; +import org.bson.json.StrictJsonWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JsonDateTimeConverter implements Converter { + + private static final Logger LOGGER = LoggerFactory.getLogger(JsonDateTimeConverter.class); + static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT + .withZone(ZoneId.of("UTC")); + + @Override + public void convert(Long value, StrictJsonWriter writer) { + try { + Instant instant = new Date(value).toInstant(); + String s = DATE_TIME_FORMATTER.format(instant); + writer.writeString(s); + } catch (Exception e) { + LOGGER.error(String.format("Fail to convert offset %d to JSON date", value), e); + } + } +} diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 15b62d5d77..ec7f0bcec2 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -21,9 +21,12 @@ flyway hbase hibernate5 - hibernate5-2 hibernate-mapping hibernate-ogm + hibernate-annotations + hibernate-jpa + hibernate-queries + hibernate-enterprise influxdb java-cassandra java-cockroachdb @@ -69,6 +72,7 @@ spring-jpa spring-persistence-simple + spring-persistence-simple-2 diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml index 55197ad560..70ff8d6a87 100644 --- a/persistence-modules/r2dbc/pom.xml +++ b/persistence-modules/r2dbc/pom.xml @@ -6,7 +6,7 @@ com.baeldung.examples.r2dbc r2dbc-example 0.0.1-SNAPSHOT - r2dbc-example + r2dbc Sample R2DBC Project diff --git a/persistence-modules/sirix/pom.xml b/persistence-modules/sirix/pom.xml index d8e065ec2f..0f114966f7 100644 --- a/persistence-modules/sirix/pom.xml +++ b/persistence-modules/sirix/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 io.sirix - core-api-tutorial + sirix 1.0-SNAPSHOT core-api-tutorial jar diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index 048dd45c7f..9f456fa8af 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -43,7 +43,12 @@ org.springframework.boot - spring-boot-starter-jdbc + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa @@ -82,6 +87,23 @@ spring-boot-starter-test test + + + com.mchange + c3p0 + ${c3p0.version} + + + + org.apache.commons + commons-dbcp2 + + + + org.apache.tomcat + tomcat-jdbc + + @@ -90,12 +112,30 @@ org.springframework.boot spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java + com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java + + + com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java + com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java + + + 3.9.1 2.1.8.RELEASE + 0.9.5.2 diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplication.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplication.java new file mode 100644 index 0000000000..fa7f884112 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.oracle.pooling; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import lombok.extern.slf4j.Slf4j; + +@SpringBootApplication +@Slf4j +public class SpringOraclePoolingApplication implements CommandLineRunner{ + + @Autowired + private DataSource dataSource; + + public static void main(String[] args) { + SpringApplication.run(SpringOraclePoolingApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + log.info("Connection Polling datasource : "+ dataSource); + + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/C3P0Configuration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/C3P0Configuration.java new file mode 100644 index 0000000000..f357924807 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/C3P0Configuration.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling.configuration; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import com.mchange.v2.c3p0.ComboPooledDataSource; + +@Configuration +@Profile("c3p0") +public class C3P0Configuration { + + @Bean + public DataSource dataSource() throws SQLException { + ComboPooledDataSource dataSource = new ComboPooledDataSource(); + dataSource.setUser("books"); + dataSource.setPassword("books"); + dataSource.setJdbcUrl("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1"); + dataSource.setMinPoolSize(5); + dataSource.setMaxPoolSize(10); + return dataSource; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java new file mode 100644 index 0000000000..9cf7e27c99 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.oracle.pooling.configuration; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import oracle.jdbc.pool.OracleDataSource; + +@Configuration +@Profile("oracle") +public class OracleConfiguration { + + @Bean + public DataSource dataSource() throws SQLException { + OracleDataSource dataSource = new OracleDataSource(); + dataSource.setUser("books"); + dataSource.setPassword("books"); + dataSource.setURL("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1"); + dataSource.setFastConnectionFailoverEnabled(true); + dataSource.setImplicitCachingEnabled(true); + // Only with clients prior to v11.2 + // dataSource.setConnectionCachingEnabled(true); + return dataSource; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java new file mode 100644 index 0000000000..b4c1544149 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.oracle.pooling.configuration; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import oracle.ucp.jdbc.PoolDataSource; +import oracle.ucp.jdbc.PoolDataSourceFactory; + +@Configuration +@Profile("oracle-ucp") +public class OracleUCPConfiguration { + + @Bean + public DataSource dataSource() throws SQLException { + PoolDataSource dataSource = PoolDataSourceFactory.getPoolDataSource(); + dataSource.setUser("books"); + dataSource.setPassword("books"); + dataSource.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource"); + dataSource.setURL("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1"); + + dataSource.setFastConnectionFailoverEnabled(true); + dataSource.setInitialPoolSize(5); + dataSource.setMinPoolSize(5); + dataSource.setMaxPoolSize(10); + return dataSource; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/controller/BookstoreController.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/controller/BookstoreController.java new file mode 100644 index 0000000000..49b998bfb9 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/controller/BookstoreController.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.oracle.pooling.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.spring.oracle.pooling.entity.Book; +import com.baeldung.spring.oracle.pooling.exception.BookstoreException; +import com.baeldung.spring.oracle.pooling.repository.BookRepository; + +@RestController +@RequestMapping("/books") +public class BookstoreController { + + @Autowired + private BookRepository repository; + + @GetMapping(value = "/hello") + public String sayHello() { + return "Hello"; + } + + @GetMapping("/all") + public List findAll() { + return repository.findAll(); + } + + @PostMapping("/create") + public Book newBook(@RequestBody Book newBook) { + return repository.save(newBook); + } + + @GetMapping("/get/{id}") + public Book findOne(@PathVariable Long id) throws BookstoreException { + return repository.findById(id) + .orElseThrow(BookstoreException::new); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java new file mode 100644 index 0000000000..fb2c3fcf6a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.oracle.pooling.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + + public Book() { + } + + public Book(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Book [id=" + id + ", name=" + name + "]"; + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/exception/BookstoreException.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/exception/BookstoreException.java new file mode 100644 index 0000000000..d2fb399ab3 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/exception/BookstoreException.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.oracle.pooling.exception; + +public class BookstoreException extends Exception{ + + /** + * + */ + private static final long serialVersionUID = 1L; + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/repository/BookRepository.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/repository/BookRepository.java new file mode 100644 index 0000000000..a50a1b24a4 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/repository/BookRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.oracle.pooling.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.spring.oracle.pooling.entity.Book; + +public interface BookRepository extends JpaRepository{ + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties b/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties new file mode 100644 index 0000000000..9a1c7fc89d --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties @@ -0,0 +1,27 @@ +logging.level.root=INFO + +# OracleDB connection settings +spring.datasource.url=jdbc:oracle:thin:@//localhost:11521/ORCLPDB1 +spring.datasource.username=books +spring.datasource.password=books +spring.datasource.driver-class-name=oracle.jdbc.OracleDriver + +# Comment this line for standard Spring Boot default choosing algorithm +#spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource + +# HikariCP settings +spring.datasource.hikari.minimumIdle=5 +spring.datasource.hikari.maximumPoolSize=20 +spring.datasource.hikari.idleTimeout=30000 +spring.datasource.hikari.maxLifetime=2000000 +spring.datasource.hikari.connectionTimeout=30000 +spring.datasource.hikari.poolName=HikariPoolBooks + +# Tomcat settings +spring.datasource.tomcat.maxActive=15 +spring.datasource.tomcat.minIdle=5 + +# JPA settings +spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect +spring.jpa.hibernate.use-new-id-generator-mappings=false +spring.jpa.hibernate.ddl-auto=create \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml b/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml index 8b13789179..4b792fd5dc 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml @@ -1 +1,9 @@ - +# Available profiles +# - none for no profile +# - oracle-pooling-basic - Oracle database with HikariCP. Loads configuration from application-oracle-pooling-basic.properties +# - oracle - Uses OracleDataSource. This profile also needs "oracle-pooling-basic" +# - oracle-ucp - Uses PoolDataSource. This profile also needs "oracle-pooling-basic" +# - c3p0 - Uses ComboPooledDataSource. This profile also needs "oracle-pooling-basic" +spring: + profiles: + active: none \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java index e4b623ee2b..93083f6c4c 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java @@ -5,10 +5,8 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import org.jdbi.v3.core.Jdbi; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -24,7 +22,7 @@ import com.baeldung.boot.jdbi.service.CarMakerService; import lombok.extern.slf4j.Slf4j; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = {SpringBootJdbiApplication.class, JdbiConfiguration.class}) @Slf4j public class SpringBootJdbiApplicationUnitTest { diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationC3P0LiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationC3P0LiveTest.java new file mode 100644 index 0000000000..5a2d3f2d29 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationC3P0LiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import javax.sql.DataSource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles({"oracle-pooling-basic", "c3p0"}) +public class SpringOraclePoolingApplicationC3P0LiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenC3p0Configuration_thenBuildsComboPooledDataSource() { + assertTrue(dataSource instanceof com.mchange.v2.c3p0.ComboPooledDataSource); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationHikariCPLiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationHikariCPLiveTest.java new file mode 100644 index 0000000000..ab8fc1e121 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationHikariCPLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import javax.sql.DataSource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles("oracle-pooling-basic") +public class SpringOraclePoolingApplicationHikariCPLiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenHikariCPConfiguration_thenBuildsHikariCP() { + assertTrue(dataSource instanceof com.zaxxer.hikari.HikariDataSource); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java new file mode 100644 index 0000000000..229375dadd --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import javax.sql.DataSource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles({"oracle-pooling-basic", "oracle"}) +public class SpringOraclePoolingApplicationOracleLiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenOracleConfiguration_thenBuildsOracleDataSource() { + assertTrue(dataSource instanceof oracle.jdbc.pool.OracleDataSource); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java new file mode 100644 index 0000000000..4fb6aa6bae --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import javax.sql.DataSource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles({"oracle-pooling-basic", "oracle-ucp"}) +public class SpringOraclePoolingApplicationOracleUCPLiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenOracleUCPConfiguration_thenBuildsOraclePoolDataSource() { + assertTrue(dataSource instanceof oracle.ucp.jdbc.PoolDataSource); + } + +} diff --git a/persistence-modules/spring-boot-persistence-h2/README.md b/persistence-modules/spring-boot-persistence-h2/README.md index a0f9c67a33..d11ec1f409 100644 --- a/persistence-modules/spring-boot-persistence-h2/README.md +++ b/persistence-modules/spring-boot-persistence-h2/README.md @@ -1,4 +1,5 @@ ### Relevant Articles: - [Access the Same In-Memory H2 Database in Multiple Spring Boot Applications](https://www.baeldung.com/spring-boot-access-h2-database-multiple-apps) - [Spring Boot With H2 Database](https://www.baeldung.com/spring-boot-h2-database) -- [Hibernate @NotNull vs @Column(nullable = false)](https://www.baeldung.com/hibernate-notnull-vs-nullable) \ No newline at end of file +- [Hibernate @NotNull vs @Column(nullable = false)](https://www.baeldung.com/hibernate-notnull-vs-nullable) +- [Quick Guide to Hibernate enable_lazy_load_no_trans Property](https://www.baeldung.com/hibernate-lazy-loading-workaround) diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties index b5fb841685..1055806ecf 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties @@ -5,6 +5,7 @@ spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.h2.console.enabled=true spring.h2.console.path=/h2-console +spring.datasource.data=data-trans.sql logging.level.org.hibernate.SQL=INFO logging.level.org.hibernate.type=TRACE diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties index 04579e1dae..77aacf0d77 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties @@ -5,6 +5,7 @@ spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.h2.console.enabled=true spring.h2.console.path=/h2-console +spring.datasource.data=data-trans.sql logging.level.org.hibernate.SQL=INFO logging.level.org.hibernate.type=TRACE diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql b/persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql similarity index 100% rename from persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql rename to persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql diff --git a/persistence-modules/spring-data-dynamodb/pom.xml b/persistence-modules/spring-data-dynamodb/pom.xml index fceceb40ba..377e35b635 100644 --- a/persistence-modules/spring-data-dynamodb/pom.xml +++ b/persistence-modules/spring-data-dynamodb/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -19,7 +19,7 @@ org.springframework.data spring-data-releasetrain - Hopper-SR10 + Lovelace-SR16 pom import @@ -174,7 +174,7 @@ com.baeldung.Application 4.3.4.RELEASE 4.5.2 - 4.4.1 + 5.1.0 1.11.64 3.3.7-1 1.0.392 diff --git a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java index 9278c0a12e..7e97e6b383 100644 --- a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java +++ b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java @@ -44,8 +44,8 @@ public class DynamoDBConfig { return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey); } - @Bean(name = "mvcHandlerMappingIntrospector") - public HandlerMappingIntrospector mvcHandlerMappingIntrospector() { + @Bean(name = "mvcHandlerMappingIntrospectorCustom") + public HandlerMappingIntrospector mvcHandlerMappingIntrospectorCustom() { return new HandlerMappingIntrospector(context); } } diff --git a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java index da47f033b6..6e8b493c3b 100644 --- a/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java +++ b/persistence-modules/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.dynamodb.repositories; -import com.baeldung.spring.data.dynamodb.model.ProductInfo; +import java.util.Optional; + import org.socialsignin.spring.data.dynamodb.repository.EnableScan; import org.springframework.data.repository.CrudRepository; -import java.util.List; +import com.baeldung.spring.data.dynamodb.model.ProductInfo; @EnableScan public interface ProductInfoRepository extends CrudRepository { - List findById(String id); + Optional findById(String id); } diff --git a/persistence-modules/spring-data-jpa-4/create.sql b/persistence-modules/spring-data-jpa-4/create.sql new file mode 100644 index 0000000000..1bbe1640a7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/create.sql @@ -0,0 +1,2 @@ +create table PERSON (ID int8 not null, FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (ID)) +create table person (id int8 not null, first_name varchar(255), last_name varchar(255), primary key (id)) diff --git a/persistence-modules/spring-data-jpa-4/pom.xml b/persistence-modules/spring-data-jpa-4/pom.xml index 8a476012c7..71fc21527f 100644 --- a/persistence-modules/spring-data-jpa-4/pom.xml +++ b/persistence-modules/spring-data-jpa-4/pom.xml @@ -33,6 +33,11 @@ mysql-connector-java + + org.postgresql + postgresql + + com.h2database h2 diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java new file mode 100644 index 0000000000..cfb6e67c2c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java @@ -0,0 +1,35 @@ +package com.baeldung.namingstrategy; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + @Id + private Long id; + + private String firstName; + + private String lastName; + + public Person() {} + + public Person(Long id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public Long id() { + return id; + } + + public String firstName() { + return firstName; + } + + public String lastName() { + return lastName; + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java new file mode 100644 index 0000000000..3c7c25bbcb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.namingstrategy; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PersonRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java new file mode 100644 index 0000000000..16b01e50e3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class QuotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toLowerCase(), true); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java new file mode 100644 index 0000000000..3cb62aa5a2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class QuotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toUpperCase(), true); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java new file mode 100644 index 0000000000..f223015db8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java @@ -0,0 +1,7 @@ +package com.baeldung.namingstrategy; + +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringDataJpaNamingConventionApplication { +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java new file mode 100644 index 0000000000..69e96aee27 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class UnquotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toLowerCase(), false); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java new file mode 100644 index 0000000000..cb87af10f4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class UnquotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toUpperCase(), false); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..71a4dbda3f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,81 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-lower-case-naming-strategy.properties") +class QuotedLowerCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..6b1c984600 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties") +class QuotedLowerCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..f819327a5c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-upper-case-naming-strategy.properties") +class QuotedUpperCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..bd23b81b4b --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,81 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") +class QuotedUpperCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..1850fea173 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("spring-physical-naming-strategy.properties") +class SpringPhysicalNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..e26ebb148d --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("spring-physical-naming-strategy-on-postgres.properties") +class SpringPhysicalNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..6311c42e93 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,86 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-lower-case-naming-strategy.properties") +class UnquotedLowerCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..033a213cf5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") +class UnquotedLowerCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..7af8001854 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-upper-case-naming-strategy.properties") +class UnquotedUpperCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..0151e7ece4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties") +class UnquotedUpperCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..04b29de41f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-lower-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties new file mode 100644 index 0000000000..6643c12c8a --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:quoted-lower-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..36898d5b4f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-upper-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties new file mode 100644 index 0000000000..6d56d58749 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:quoted-upper-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..706b12b1b6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/spring-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties new file mode 100644 index 0000000000..c9a0c6f24c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:spring-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..b22472bd8f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-lower-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties new file mode 100644 index 0000000000..8083515b4b --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:unquoted-lower-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..da03a0d7b5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-upper-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties new file mode 100644 index 0000000000..d1b63e008c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:unquoted-upper-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java index 9bbc571aee..4e87c24614 100644 --- a/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ b/persistence-modules/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java @@ -16,8 +16,7 @@ public class MovieDatabaseNeo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { - org.neo4j.ogm.config.Configuration config = new Builder().uri(URL).build(); - return config; + return new Builder().uri(URL).build(); } @Bean diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index c3c8fa7b9f..6d7526a13b 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -9,6 +9,7 @@ This module contains articles about Hibernate 5 with Spring. - [JPA Criteria Queries](https://www.baeldung.com/hibernate-criteria-queries) - [Introduction to Hibernate Search](https://www.baeldung.com/hibernate-search) - [@DynamicUpdate with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-dynamicupdate) -- [Hibernate Second-Level Cache](https://www.baeldung.com/hibernate-second-level-cache) -- [Deleting Objects with Hibernate](https://www.baeldung.com/delete-with-hibernate) -- [Spring, Hibernate and a JNDI Datasource](https://www.baeldung.com/spring-persistence-jpa-jndi-datasource) +- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) +- [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) +- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) +- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index 31877255b2..7d95e0f342 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -8,6 +8,7 @@ import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; +import org.junit.Ignore; import org.junit.Test; import com.baeldung.hibernate.criteria.model.Item; @@ -24,6 +25,7 @@ public class HibernateCriteriaIntegrationTest { final private ApplicationView av = new ApplicationView(); @Test + @Ignore public void testPerformanceOfCriteria() { assertFalse(av.checkIfCriteriaTimeLower()); } diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index cfa13ca3b0..a5a72a9b7e 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -9,7 +9,6 @@ This module contains articles about Spring with Hibernate 4 - [Stored Procedures with Hibernate](https://www.baeldung.com/stored-procedures-with-hibernate-tutorial) - [Hibernate: save, persist, update, merge, saveOrUpdate](https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) - [Eager/Lazy Loading In Hibernate](https://www.baeldung.com/hibernate-lazy-eager-loading) -- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate) - [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) ### Quick Start diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java new file mode 100644 index 0000000000..7aef08b2ce --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java @@ -0,0 +1,19 @@ +package com.baeldung.hibernate.audit; + +import java.util.Optional; + +import org.springframework.data.domain.AuditorAware; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +public class AuditorAwareImpl implements AuditorAware { + + @Override + public String getCurrentAuditor() { + return Optional.ofNullable(SecurityContextHolder.getContext()) + .map(e -> e.getAuthentication()) + .map(Authentication::getName) + .orElse(null); + } + +} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java index b7cf0fadf2..6ae133ca7a 100644 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -23,6 +23,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; +import com.baeldung.hibernate.audit.AuditorAwareImpl; import com.baeldung.persistence.dao.IBarAuditableDao; import com.baeldung.persistence.dao.IBarDao; import com.baeldung.persistence.dao.IFooAuditableDao; @@ -46,7 +47,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") -@EnableJpaAuditing +@EnableJpaAuditing(auditorAwareRef = "auditorProvider") @PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "com.baeldung.persistence" }) public class PersistenceConfig { @@ -58,6 +59,11 @@ public class PersistenceConfig { super(); } + @Bean("auditorProvider") + public AuditorAwareImpl auditorAwareImpl() { + return new AuditorAwareImpl(); + } + @Bean public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index 27a2fe8368..599a667a13 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -10,7 +10,7 @@ - [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database) - [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source) - [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys) -- [Transactions with Spring 4 and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) +- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many) - [Spring Persistence (Hibernate and JPA) with a JNDI datasource](https://www.baeldung.com/spring-persistence-hibernate-and-jpa-with-a-jndi-datasource/) diff --git a/persistence-modules/spring-persistence-simple-2/README.md b/persistence-modules/spring-persistence-simple-2/README.md new file mode 100644 index 0000000000..a6408df8f2 --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Spring JdbcTemplate Unit Testing](https://www.baeldung.com/spring-jdbctemplate-testing) diff --git a/persistence-modules/spring-persistence-simple-2/pom.xml b/persistence-modules/spring-persistence-simple-2/pom.xml new file mode 100644 index 0000000000..8380d635de --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + spring-persistence-simple-2 + 0.1-SNAPSHOT + spring-persistence-simple-2 + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework + spring-orm + ${org.springframework.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + + + com.h2database + h2 + ${h2.version} + test + + + + + org.springframework + spring-test + ${org.springframework.version} + test + + + org.mockito + mockito-core + ${mockito.version} + test + + + + + + 5.2.4.RELEASE + + 1.4.200 + + 3.3.3 + + + \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java new file mode 100644 index 0000000000..bd6fe0fb15 --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java @@ -0,0 +1,42 @@ +package com.baeldung.jdbc; + +public class Employee { + private int id; + + private String firstName; + + private String lastName; + + + public Employee(int id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + +} diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java new file mode 100644 index 0000000000..2ea42381eb --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java @@ -0,0 +1,67 @@ +package com.baeldung.jdbc; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import org.springframework.jdbc.core.namedparam.SqlParameterSource; +import org.springframework.stereotype.Repository; + +@Repository +public class EmployeeDAO { + private JdbcTemplate jdbcTemplate; + private NamedParameterJdbcTemplate namedJdbcTemplate; + + public void setDataSource(DataSource dataSource) { + jdbcTemplate = new JdbcTemplate(dataSource); + namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); + } + + public int getCountOfEmployees() { + return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class); + } + + public List getEmployeesFromIdListNamed(List ids) { + SqlParameterSource parameters = new MapSqlParameterSource("ids", ids); + List employees = namedJdbcTemplate.query( + "SELECT * FROM EMPLOYEE WHERE id IN (:ids)", + parameters, + (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); + + return employees; + } + + public List getEmployeesFromIdList(List ids) { + String inSql = String.join(",", Collections.nCopies(ids.size(), "?")); + List employees = jdbcTemplate.query( + String.format("SELECT * FROM EMPLOYEE WHERE id IN (%s)", inSql), + ids.toArray(), + (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); + + return employees; + } + + public List getEmployeesFromLargeIdList(List ids) { + jdbcTemplate.execute("CREATE TEMPORARY TABLE IF NOT EXISTS employee_tmp (id INT NOT NULL)"); + + List employeeIds = new ArrayList<>(); + for (Integer id : ids) { + employeeIds.add(new Object[] { id }); + } + jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds); + + List employees = jdbcTemplate.query( + "SELECT * FROM EMPLOYEE WHERE id IN (SELECT id FROM employee_tmp)", + (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); + + jdbcTemplate.update("DELETE FROM employee_tmp"); + + return employees; + } + +} diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql new file mode 100644 index 0000000000..be102431ca --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql @@ -0,0 +1,6 @@ +CREATE TABLE EMPLOYEE +( + ID int NOT NULL PRIMARY KEY, + FIRST_NAME varchar(255), + LAST_NAME varchar(255) +); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql new file mode 100644 index 0000000000..5421c09849 --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql @@ -0,0 +1,4 @@ +INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling'); +INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth'); +INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds'); +INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie'); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java b/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java new file mode 100644 index 0000000000..369725bafd --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java @@ -0,0 +1,107 @@ +package com.baeldung.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) + +public class EmployeeDAOUnitTest { + @Mock + JdbcTemplate jdbcTemplate; + + DataSource dataSource; + + @Before + public void setup() { + dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) + .generateUniqueName(true) + .addScript("classpath:jdbc/schema.sql") + .addScript("classpath:jdbc/test-data.sql") + .build(); + + } + + @Test + public void whenMockJdbcTemplate_thenReturnCorrectEmployeeCount() { + EmployeeDAO employeeDAO = new EmployeeDAO(); + ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate); + Mockito.when(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class)) + .thenReturn(4); + + assertEquals(4, employeeDAO.getCountOfEmployees()); + + Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(Integer.class))) + .thenReturn(3); + + assertEquals(3, employeeDAO.getCountOfEmployees()); + } + + @Test + public void whenInjectInMemoryDataSource_thenReturnCorrectEmployeeCount() { + EmployeeDAO employeeDAO = new EmployeeDAO(); + employeeDAO.setDataSource(dataSource); + + assertEquals(4, employeeDAO.getCountOfEmployees()); + } + + @Test + public void givenSmallIdList_whenGetEmployeesFromIdList_thenReturnCorrectEmployees() { + List ids = new ArrayList<>(); + ids.add(1); + ids.add(3); + ids.add(4); + EmployeeDAO employeeDAO = new EmployeeDAO(); + employeeDAO.setDataSource(dataSource); + + List employees = employeeDAO.getEmployeesFromIdList(ids); + + assertEquals(3, employees.size()); + assertEquals(1, employees.get(0).getId()); + assertEquals(3, employees.get(1).getId()); + assertEquals(4, employees.get(2).getId()); + + employees = employeeDAO.getEmployeesFromIdListNamed(ids); + + assertEquals(3, employees.size()); + assertEquals(1, employees.get(0).getId()); + assertEquals(3, employees.get(1).getId()); + assertEquals(4, employees.get(2).getId()); + } + + @Test + public void givenLargeIdList_whenGetEmployeesFromIdList_thenReturnCorrectEmployees() { + List ids = new ArrayList<>(); + ids.add(1); + ids.add(3); + ids.add(4); + EmployeeDAO employeeDAO = new EmployeeDAO(); + employeeDAO.setDataSource(dataSource); + + List employees = employeeDAO.getEmployeesFromLargeIdList(ids); + + assertEquals(3, employees.size()); + assertEquals(1, employees.get(0).getId()); + assertEquals(3, employees.get(1).getId()); + assertEquals(4, employees.get(2).getId()); + + ids.clear(); + ids.add(2); + employees = employeeDAO.getEmployeesFromLargeIdList(ids); + assertEquals(1, employees.size()); + } +} diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index 8a03310048..878c4592f9 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -24,7 +24,11 @@ spring-context ${org.springframework.version} - + + org.springframework + spring-aspects + ${org.springframework.version} + org.hibernate @@ -128,12 +132,13 @@ - 5.1.6.RELEASE + 5.2.5.RELEASE - 5.4.2.Final - 6.0.6 - 2.1.6.RELEASE + 5.4.13.Final + 8.0.19 + 1.4.200 + 2.2.6.RELEASE 9.0.0.M26 1.1 4.2.1 diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java index 569971e311..80f3ff14c5 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java @@ -1,9 +1,7 @@ package com.baeldung.config; -import java.util.Properties; - -import javax.sql.DataSource; - +import com.baeldung.persistence.service.FooService; +import com.google.common.base.Preconditions; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -23,16 +21,15 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import com.baeldung.hibernate.dao.FooDao; -import com.baeldung.jpa.dao.IFooDao; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.Properties; @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = { "com.baeldung.hibernate.dao" }, transactionManagerRef = "jpaTransactionManager") @EnableJpaAuditing @PropertySource({ "classpath:persistence-mysql.properties" }) -@ComponentScan({ "com.baeldung.persistence", "com.baeldung.hibernate.dao" }) +@ComponentScan(basePackages = { "com.baeldung.persistence.dao", "com.baeldung.jpa.dao" }) public class PersistenceConfig { @Autowired @@ -46,7 +43,7 @@ public class PersistenceConfig { public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + sessionFactory.setPackagesToScan("com.baeldung.persistence.model"); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; @@ -56,7 +53,7 @@ public class PersistenceConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); emf.setDataSource(restDataSource()); - emf.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + emf.setPackagesToScan("com.baeldung.persistence.model"); final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); emf.setJpaVendorAdapter(vendorAdapter); @@ -96,18 +93,15 @@ public class PersistenceConfig { } @Bean - public IFooDao fooHibernateDao() { - return new FooDao(); + public FooService fooService() { + return new FooService(); } private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", "true"); - // hibernateProperties.setProperty("hibernate.format_sql", "true"); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); // Envers properties hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); 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 7d3a881827..06cae493c9 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 @@ -1,10 +1,6 @@ package com.baeldung.config; -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - +import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -21,7 +17,8 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.Properties; @Configuration @EnableTransactionManagement @@ -43,7 +40,7 @@ public class PersistenceJPAConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + em.setPackagesToScan("com.baeldung.persistence.model"); final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); @@ -64,9 +61,9 @@ public class PersistenceJPAConfig { } @Bean - public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + public PlatformTransactionManager transactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(emf); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java index 4fbc8464bb..a6542c5cb1 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java @@ -1,16 +1,15 @@ package com.baeldung.jpa.dao; -import java.io.Serializable; -import java.util.List; - import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; +import java.io.Serializable; +import java.util.List; public abstract class AbstractJpaDAO { private Class clazz; - @PersistenceContext + @PersistenceContext(unitName = "entityManagerFactory") private EntityManager entityManager; public final void setClazz(final Class clazzToSet) { diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml index bbb61cb3e0..55546a862a 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml +++ b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml @@ -21,7 +21,7 @@ - + diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql index c86d35cdae..ef4460e267 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql +++ b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql @@ -3,5 +3,5 @@ CREATE TABLE EMPLOYEE ID int NOT NULL PRIMARY KEY, FIRST_NAME varchar(255), LAST_NAME varchar(255), - ADDRESS varchar(255), + ADDRESS varchar(255) ); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties index b3cfd31f46..9ba4f7602a 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties +++ b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties @@ -1,7 +1,7 @@ # jdbc.X jdbc.driverClassName=com.mysql.cj.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true -jdbc.eventGeneratedId=tutorialuser +jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true&serverTimezone=UTC +jdbc.user=tutorialuser jdbc.pass=tutorialmy5ql # hibernate.X diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java index 69ddbb9b9f..5874b3c643 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java @@ -1,25 +1,6 @@ package com.baeldung.spring.data.persistence.jpaquery; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Stream; - -import javax.persistence.EntityManager; -import javax.persistence.Query; - import com.baeldung.spring.data.persistence.config.PersistenceConfig; -import com.baeldung.spring.data.persistence.jpaquery.UserRepository; import com.baeldung.spring.data.persistence.model.User; import org.junit.After; import org.junit.Test; @@ -36,6 +17,16 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.transaction.annotation.Transactional; +import javax.persistence.EntityManager; +import javax.persistence.Query; +import java.time.LocalDate; +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.*; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) @@ -283,7 +274,7 @@ public class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); assertThat(usersSortByName.get(0) .getName()).isEqualTo(USER_NAME_ADAM); @@ -295,7 +286,7 @@ public class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); @@ -459,6 +450,8 @@ public class UserRepositoryCommon { userRepository.save(usr01); userRepository.save(usr02); + System.out.println(TimeZone.getDefault()); + List users = userRepository.findUsersWithGmailAddress(); assertEquals(1, users.size()); assertEquals(usr02, users.get(0)); diff --git a/pom.xml b/pom.xml index a295439951..83ed9efbed 100644 --- a/pom.xml +++ b/pom.xml @@ -69,6 +69,12 @@ ${hamcrest-all.version} test + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + test + org.mockito mockito-core @@ -336,6 +342,7 @@ algorithms-miscellaneous-3 algorithms-miscellaneous-4 algorithms-miscellaneous-5 + algorithms-miscellaneous-6 algorithms-searching algorithms-sorting algorithms-sorting-2 @@ -380,8 +387,7 @@ bazel blade bootique - - cas + cdi checker-plugin @@ -394,7 +400,6 @@ core-java-modules core-kotlin-modules - core-scala couchbase custom-pmd @@ -448,15 +453,12 @@ java-collections-conversions java-collections-conversions-2 - java-collections-maps - java-collections-maps-2 + java-collections-maps-3 javafx java-jdi java-lite - java-math - java-math-2 java-numbers java-numbers-2 java-numbers-3 @@ -503,6 +505,7 @@ libraries-data-db libraries-data-io libraries-http + libraries-http-2 libraries-io libraries-primitive libraries-security @@ -532,6 +535,7 @@ mybatis netflix-modules + ninja open-liberty @@ -562,6 +566,8 @@ rxjava-libraries rxjava-observables rxjava-operators + + atomikos @@ -646,6 +652,7 @@ spring-core spring-core-2 spring-core-3 + spring-core-4 spring-cucumber spring-data-rest @@ -726,6 +733,7 @@ spring-threads spring-thymeleaf spring-thymeleaf-2 + spring-thymeleaf-3 spring-vault spring-vertx @@ -805,7 +813,8 @@ libraries vaadin - vavr + vavr + vavr-2 @@ -848,6 +857,7 @@ algorithms-miscellaneous-3 algorithms-miscellaneous-4 algorithms-miscellaneous-5 + algorithms-miscellaneous-6 algorithms-searching algorithms-sorting algorithms-sorting-2 @@ -893,8 +903,7 @@ bazel blade bootique - - cas + cdi checker-plugin @@ -907,7 +916,6 @@ core-java-modules core-kotlin-modules - core-scala couchbase custom-pmd @@ -961,15 +969,12 @@ java-collections-conversions java-collections-conversions-2 - java-collections-maps - java-collections-maps-2 + java-collections-maps-3 javafx java-jdi java-lite - java-math - java-math-2 java-numbers java-numbers-2 java-numbers-3 @@ -1015,6 +1020,7 @@ libraries-data-db libraries-data-io libraries-http + libraries-http-2 libraries-io libraries-primitive libraries-security @@ -1044,6 +1050,7 @@ mybatis netflix-modules + ninja open-liberty @@ -1074,6 +1081,8 @@ rxjava-libraries rxjava-observables rxjava-operators + + atomikos @@ -1150,6 +1159,7 @@ spring-core spring-core-2 spring-core-3 + spring-core-4 spring-cucumber spring-data-rest @@ -1197,6 +1207,7 @@ spring-mvc-views spring-mvc-webflow spring-mvc-xml + spring-mvc-crash spring-protobuf spring-quartz @@ -1229,6 +1240,7 @@ spring-thymeleaf spring-thymeleaf-2 + spring-thymeleaf-3 spring-vault spring-vertx @@ -1259,6 +1271,7 @@ wildfly xml xstream + libraries-concurrency @@ -1300,7 +1313,8 @@ libraries vaadin - vavr + vavr + vavr-2 @@ -1330,7 +1344,8 @@ 4.12 2.2 1.3 - 2.21.0 + 3.3.0 + 1.10.5 1.7.30 diff --git a/quarkus-extension/quarkus-liquibase/deployment/pom.xml b/quarkus-extension/quarkus-liquibase/deployment/pom.xml index c85d986390..5c6b56e152 100644 --- a/quarkus-extension/quarkus-liquibase/deployment/pom.xml +++ b/quarkus-extension/quarkus-liquibase/deployment/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - quarkus-liquibase-deployment - quarkus-liquibase-deployment + deployment + deployment com.baeldung.quarkus.liquibase @@ -58,4 +58,4 @@ 3.8.1 - \ No newline at end of file + diff --git a/quarkus-extension/quarkus-liquibase/pom.xml b/quarkus-extension/quarkus-liquibase/pom.xml index 9536561701..8ed6555ed7 100644 --- a/quarkus-extension/quarkus-liquibase/pom.xml +++ b/quarkus-extension/quarkus-liquibase/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.baeldung.quarkus.liquibase quarkus-liquibase-parent - quarkus-liquibase-parent + quarkus-liquibase pom @@ -23,4 +23,4 @@ 1.0.0.Final - \ No newline at end of file + diff --git a/quarkus-extension/quarkus-liquibase/runtime/pom.xml b/quarkus-extension/quarkus-liquibase/runtime/pom.xml index 83f7c8d4cc..760e6ab719 100644 --- a/quarkus-extension/quarkus-liquibase/runtime/pom.xml +++ b/quarkus-extension/quarkus-liquibase/runtime/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - quarkus-liquibase-runtime - quarkus-liquibase-runtime + runtime + runtime com.baeldung.quarkus.liquibase @@ -70,4 +70,4 @@ 3.8.1 - \ No newline at end of file + diff --git a/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java new file mode 100644 index 0000000000..f9e67b0a2f --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.mono; + +import org.junit.Test; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; + +public class MonoUnitTest { + @Test + public void whenMonoProducesString_thenBlockAndConsume() { + + String result1 = blockingHelloWorld().block(); + assertEquals("Hello world!", result1); + + String result2 = blockingHelloWorld() + .block(Duration.of(1000, ChronoUnit.MILLIS)); + assertEquals("Hello world!", result2); + + Optional result3 = Mono.empty().blockOptional(); + assertEquals(Optional.empty(), result3); + } + + @Test + public void whenMonoProducesString_thenConsumeNonBlocking() { + + blockingHelloWorld() + .doOnNext(result -> assertEquals("Hello world!", result)) + .subscribe(); + + blockingHelloWorld() + .subscribe(result -> assertEquals("Hello world!", result)); + + } + + private Mono blockingHelloWorld() { + // blocking + return Mono.just("Hello world!"); + } +} diff --git a/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java rename to spring-5-data-reactive/src/test/java/com/baeldung/SpringContextTest.java index c3ea1d8435..bedb30fcaa 100644 --- a/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-5-data-reactive/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index e98012c047..aff8bb227c 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -6,3 +6,4 @@ This module contains articles about Spring 5 model-view-controller (MVC) pattern - [Spring Boot and Kotlin](https://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) - [Interface Driven Controllers in Spring](https://www.baeldung.com/spring-interface-driven-controllers) +- [Returning Plain HTML From a Spring MVC Controller](https://www.baeldung.com/spring-mvc-return-html) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 2f8ef05bff..4b42528d0f 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -42,6 +42,11 @@ org.slf4j jcl-over-slf4j + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + org.jetbrains.kotlin @@ -175,8 +180,8 @@ 2.9.0 2.9.9 1.2.71 - com.baeldung.Spring5Application 4.5.8 + com.baeldung.Spring5Application diff --git a/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java new file mode 100644 index 0000000000..ad660559c7 --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.html; + +import org.springframework.boot.*; +import org.springframework.boot.autoconfigure.*; + +@SpringBootApplication +public class HtmlApplication +{ + public static void main(String[] args) { + SpringApplication.run(HtmlApplication.class, args); + } +} diff --git a/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java new file mode 100644 index 0000000000..23674d165e --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java @@ -0,0 +1,17 @@ +package com.baeldung.html; + +import org.springframework.http.*; +import org.springframework.stereotype.*; +import org.springframework.web.bind.annotation.*; + +@Controller +public class HtmlController +{ + @GetMapping(value = "/welcome", produces = MediaType.TEXT_HTML_VALUE) + @ResponseBody + public String welcomeAsHTML() + { + return "\n" + "
Welcome
\n" + + "\n" + "Hello world\n" + "\n" + ""; + } +} diff --git a/spring-5-mvc/src/main/resources/application.properties b/spring-5-mvc/src/main/resources/application.properties index 886ea1978b..ccec014c2b 100644 --- a/spring-5-mvc/src/main/resources/application.properties +++ b/spring-5-mvc/src/main/resources/application.properties @@ -1,6 +1,3 @@ server.port=8081 -security.user.name=user -security.user.password=pass - logging.level.root=INFO \ No newline at end of file diff --git a/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java b/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java new file mode 100644 index 0000000000..8eba4e8cf9 --- /dev/null +++ b/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java @@ -0,0 +1,30 @@ +package com.baeldung.html; + +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.*; +import org.springframework.boot.test.autoconfigure.web.servlet.*; +import org.springframework.test.web.servlet.*; +import org.springframework.test.web.servlet.request.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@WebMvcTest(HtmlController.class) +class HtmlControllerUnitTest { + + @Autowired + private MockMvc mockMvc; + + private final String expectedHtmlResponse = + "\n" + "
Welcome
\n" + + "\n" + "Hello world\n" + "\n" + ""; + + @Test + void whenGETRequestToCorrectURL_thenReturnCorrectWelcomeMessage() throws Exception { + MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/welcome")) + .andExpect(status().isOk()) + .andReturn(); + + String resultDOW = result.getResponse().getContentAsString(); + assertEquals(expectedHtmlResponse, resultDOW); + } +} diff --git a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java index b7ed031ec7..9d04541f8d 100644 --- a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java +++ b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java @@ -52,14 +52,13 @@ public class ConsumerFooServiceIntegrationTest { .map(Arrays::stream) .orElse(Stream.empty()); }) - .map(IThrowableProxy::getMessage) + .map(IThrowableProxy::getClassName) .collect(Collectors.toList()); assertThat(allLoggedEntries).anyMatch(entry -> entry.contains("The following error happened on processFoo method!")) .anyMatch(entry -> entry.contains("| onSubscribe")) .anyMatch(entry -> entry.contains("| cancel()")); - assertThat(allSuppressedEntries).anyMatch(entry -> entry.contains("Assembly trace from producer")) - .anyMatch(entry -> entry.contains("Error has been observed by the following operator(s)")); + assertThat(allSuppressedEntries) + .anyMatch(entry -> entry.contains("reactor.core.publisher.FluxOnAssembly$OnAssemblyException")); } - } diff --git a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java index af9bdfbc9b..e61ea9e155 100644 --- a/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java +++ b/spring-5-reactive-2/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java @@ -7,6 +7,11 @@ import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; import com.baeldung.debugging.consumer.service.FooService; +/** + * In order to run this live test, start the following classes: + * - com.baeldung.debugging.server.ServerDebuggingApplication + * - com.baeldung.debugging.consumer.ConsumerDebuggingApplication + */ public class ConsumerFooServiceLiveTest { FooService service = new FooService(); diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index e3c41f8b84..cc728398f3 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -92,8 +92,8 @@
com.github.tomakehurst - wiremock - 2.24.1 + wiremock-standalone + 2.26.0 test diff --git a/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java rename to spring-5-reactive-client/src/test/java/com/baeldung/SpringContextTest.java index 678d04897b..c0ca9b7e64 100644 --- a/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-5-reactive-client/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/ReactiveIntegrationTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/ReactiveIntegrationTest.java index 394ff42e5f..1d2197a381 100644 --- a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/ReactiveIntegrationTest.java +++ b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/ReactiveIntegrationTest.java @@ -1,37 +1,67 @@ package com.baeldung.reactive; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; import com.baeldung.reactive.model.Foo; +import com.github.tomakehurst.wiremock.WireMockServer; import reactor.core.publisher.Mono; +@RunWith(SpringRunner.class) @SpringBootTest public class ReactiveIntegrationTest { private WebClient client; - - @BeforeEach - public void before() { - client = WebClient.create("http://localhost:8080"); + private int singleRequestTime = 1000; + private WireMockServer wireMockServer; + + @Before + public void setup() { + wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); + wireMockServer.start(); + configureFor("localhost", wireMockServer.port()); + client = WebClient.create("http://localhost:" + wireMockServer.port()); } - // + @After + public void tearDown() { + wireMockServer.stop(); + } @Test public void whenMonoReactiveEndpointIsConsumed_thenCorrectOutput() { - final Mono fooMono = client.get().uri("/foos/123").exchange().log(); + stubFor(get(urlEqualTo("/foo/123")).willReturn(aResponse().withFixedDelay(singleRequestTime) + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{\"id\":123, \"name\":\"foo\"}"))); + + final Mono fooMono = client.get().uri("/foo/123").exchange().log(); System.out.println(fooMono.subscribe()); } @Test public void whenFluxReactiveEndpointIsConsumed_thenCorrectOutput() throws InterruptedException { - client.get().uri("/foos") + stubFor(get(urlEqualTo("/foo")).willReturn(aResponse().withFixedDelay(singleRequestTime) + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{\"id\":1, \"name\":\"foo\"}"))); + + client.get().uri("/foo") .retrieve() .bodyToFlux(Foo.class).log() .subscribe(System.out::println); diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/webclient/simultaneous/ClientIntegrationTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/webclient/simultaneous/ClientIntegrationTest.java index d74a64d9c9..43454daf17 100644 --- a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/webclient/simultaneous/ClientIntegrationTest.java +++ b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/webclient/simultaneous/ClientIntegrationTest.java @@ -5,6 +5,7 @@ import org.junit.Before; import org.junit.After; 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.github.tomakehurst.wiremock.WireMockServer; @@ -19,15 +20,19 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest +@DirtiesContext public class ClientIntegrationTest { private WireMockServer wireMockServer; + private Client client; + @Before public void setup() { - wireMockServer = new WireMockServer(wireMockConfig().port(8089)); + wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); wireMockServer.start(); configureFor("localhost", wireMockServer.port()); + client = new Client("http://localhost:" + wireMockServer.port()); } @After @@ -52,8 +57,6 @@ public class ClientIntegrationTest { .boxed() .collect(Collectors.toList()); - Client client = new Client("http://localhost:8089"); - // Act long start = System.currentTimeMillis(); List users = client.fetchUsers(userIds) diff --git a/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java rename to spring-5-reactive-security/src/test/java/com/baeldung/SpringContextTest.java index 479c35d986..b4f4118527 100644 --- a/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java rename to spring-5-reactive/src/test/java/com/baeldung/SpringContextTest.java index c3ea1d8435..bedb30fcaa 100644 --- a/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-5-security/src/main/java/com/baeldung/manuallogout/BasicAuthController.java b/spring-5-security/src/main/java/com/baeldung/manuallogout/BasicAuthController.java new file mode 100644 index 0000000000..8f01940dce --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/manuallogout/BasicAuthController.java @@ -0,0 +1,32 @@ +package com.baeldung.manuallogout; + +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.RequestMethod; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +@Controller +public class BasicAuthController { + + @RequestMapping(value = {"/basiclogout"}, method = RequestMethod.POST) + public String logout(HttpServletRequest request, HttpServletResponse response) { + HttpSession session; + SecurityContextHolder.clearContext(); + session = request.getSession(false); + if (session != null) { + session.invalidate(); + } + for (Cookie cookie : request.getCookies()) { + String cookieName = cookie.getName(); + Cookie cookieToDelete = new Cookie(cookieName, null); + cookieToDelete.setMaxAge(0); + response.addCookie(cookieToDelete); + } + return "redirect:/login?logout"; + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/manuallogout/ClearSiteDataController.java b/spring-5-security/src/main/java/com/baeldung/manuallogout/ClearSiteDataController.java new file mode 100644 index 0000000000..7eef397da3 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/manuallogout/ClearSiteDataController.java @@ -0,0 +1,29 @@ +package com.baeldung.manuallogout; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@Controller +public class ClearSiteDataController { + + Directive[] SOURCE = {Directive.COOKIES, Directive.STORAGE, Directive.EXECUTION_CONTEXTS, Directive.CACHE}; + + @RequestMapping(value = {"/csdlogout"}, method = RequestMethod.POST) + public String logout(HttpServletRequest request, HttpServletResponse response) { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null) { + ClearSiteDataHeaderWriter csdHeaderWriter = new ClearSiteDataHeaderWriter(SOURCE); + new HeaderWriterLogoutHandler(csdHeaderWriter).logout(request, response, auth); + } + return "redirect:/login?logout"; + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java b/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java new file mode 100644 index 0000000000..50ea356f03 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.manuallogout; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ManualLogoutApplication { + public static void main(String[] args) { + SpringApplication.run(ManualLogoutApplication.class, args); + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java b/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java new file mode 100644 index 0000000000..6f14f6fca2 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java @@ -0,0 +1,39 @@ +package com.baeldung.manuallogout; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SimpleSecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.formLogin() + .loginProcessingUrl("/login") + .loginPage("/login") + .usernameParameter("username") + .passwordParameter("password") + .defaultSuccessUrl("/") + .failureUrl("/login?error"); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("user") + .password("password") + .roles("USER") + .and() + .withUser("manager") + .password("password") + .credentialsExpired(true) + .accountExpired(true) + .accountLocked(true) + .authorities("WRITE_PRIVILEGES", "READ_PRIVILEGES") + .roles("MANAGER"); + } +} diff --git a/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-security/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-5-security/src/test/java/org/baeldung/SpringContextTest.java rename to spring-5-security/src/test/java/com/baeldung/SpringContextTest.java index 729790bd14..7812a5c063 100644 --- a/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-5-security/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java b/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java new file mode 100644 index 0000000000..a64cb82910 --- /dev/null +++ b/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java @@ -0,0 +1,70 @@ +package com.baeldung.manuallogout; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpSession; + +import static org.junit.Assert.assertNull; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringRunner.class) +@WebMvcTest() +public class ManualLogoutIntegrationTest { + + private static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data"; + public static final int EXPIRY = 60 * 10; + public static final String COOKIE_NAME = "customerName"; + public static final String COOKIE_VALUE = "myName"; + public static final String ATTRIBUTE_NAME = "att"; + public static final String ATTRIBUTE_VALUE = "attvalue"; + + @Autowired + private MockMvc mockMvc; + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutThenSessionCleared() throws Exception { + + MockHttpSession session = new MockHttpSession(); + session.setAttribute(ATTRIBUTE_NAME, ATTRIBUTE_VALUE); + + Cookie randomCookie = new Cookie(COOKIE_NAME, COOKIE_VALUE); + randomCookie.setMaxAge(EXPIRY); // 10 minutes + + MockHttpServletRequest requestStateAfterLogout = this.mockMvc.perform(post("/basiclogout").secure(true).with(csrf()).session(session).cookie(randomCookie)) + .andExpect(status().is3xxRedirection()) + .andExpect(unauthenticated()) + .andExpect(cookie().maxAge(COOKIE_NAME, 0)) + .andReturn() + .getRequest(); + + HttpSession sessionStateAfterLogout = requestStateAfterLogout.getSession(); + assertNull(sessionStateAfterLogout.getAttribute(ATTRIBUTE_NAME)); + + + } + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutThenClearDataSiteHeaderPresent() throws Exception { + + this.mockMvc.perform(post("/csdlogout").secure(true).with(csrf())) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(header().exists(CLEAR_SITE_DATA_HEADER)) + .andReturn(); + } +} \ No newline at end of file diff --git a/spring-5/src/test/java/org/baeldung/SpringContextTest.java b/spring-5/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-5/src/test/java/org/baeldung/SpringContextTest.java rename to spring-5/src/test/java/com/baeldung/SpringContextTest.java index 56e8697f5c..e3f67def90 100644 --- a/spring-5/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-5/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-all/README.md b/spring-all/README.md index d71b8569cf..9ad78aa1ee 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -1,7 +1,3 @@ ## Spring All This module contains articles about Spring - -### Relevant Articles: - -- [The @Scheduled Annotation in Spring](https://www.baeldung.com/spring-scheduled-tasks) diff --git a/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java similarity index 89% rename from spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java rename to spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java index 1c098a56ab..14e7de2095 100644 --- a/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; diff --git a/spring-batch/README.md b/spring-batch/README.md index d637de269c..3a89459629 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -3,6 +3,7 @@ This module contains articles about Spring Batch ### Relevant Articles: + - [Introduction to Spring Batch](https://www.baeldung.com/introduction-to-spring-batch) - [Spring Batch using Partitioner](https://www.baeldung.com/spring-batch-partitioner) - [Spring Batch – Tasklets vs Chunks](https://www.baeldung.com/spring-batch-tasklet-chunk) @@ -10,3 +11,4 @@ This module contains articles about Spring Batch - [Configuring Skip Logic in Spring Batch](https://www.baeldung.com/spring-batch-skip-logic) - [Testing a Spring Batch Job](https://www.baeldung.com/spring-batch-testing-job) - [Configuring Retry Logic in Spring Batch](https://www.baeldung.com/spring-batch-retry-logic) +- [Conditional Flow in Spring Batch](https://www.baeldung.com/spring-batch-conditional-flow) diff --git a/spring-batch/repository.sqlite b/spring-batch/repository.sqlite index 4456ef63cc..2b549352ec 100644 Binary files a/spring-batch/repository.sqlite and b/spring-batch/repository.sqlite differ diff --git a/spring-batch/src/main/java/org/baeldung/batch/App.java b/spring-batch/src/main/java/com/baeldung/batch/App.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/batch/App.java rename to spring-batch/src/main/java/com/baeldung/batch/App.java index 764ef72a35..0f888a77b3 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/App.java +++ b/spring-batch/src/main/java/com/baeldung/batch/App.java @@ -1,4 +1,4 @@ -package org.baeldung.batch; +package com.baeldung.batch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java b/spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java similarity index 92% rename from spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java rename to spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java index 07dd65bcfd..e1c52e1582 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java +++ b/spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java @@ -1,12 +1,12 @@ -package org.baeldung.batch; +package com.baeldung.batch; -import org.baeldung.batch.model.Transaction; -import org.baeldung.batch.service.CustomItemProcessor; -import org.baeldung.batch.service.CustomSkipPolicy; -import org.baeldung.batch.service.MissingUsernameException; -import org.baeldung.batch.service.NegativeAmountException; -import org.baeldung.batch.service.RecordFieldSetMapper; -import org.baeldung.batch.service.SkippingItemProcessor; +import com.baeldung.batch.model.Transaction; +import com.baeldung.batch.service.CustomItemProcessor; +import com.baeldung.batch.service.CustomSkipPolicy; +import com.baeldung.batch.service.MissingUsernameException; +import com.baeldung.batch.service.NegativeAmountException; +import com.baeldung.batch.service.RecordFieldSetMapper; +import com.baeldung.batch.service.SkippingItemProcessor; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; diff --git a/spring-batch/src/main/java/org/baeldung/batch/SpringBatchRetryConfig.java b/spring-batch/src/main/java/com/baeldung/batch/SpringBatchRetryConfig.java similarity index 95% rename from spring-batch/src/main/java/org/baeldung/batch/SpringBatchRetryConfig.java rename to spring-batch/src/main/java/com/baeldung/batch/SpringBatchRetryConfig.java index 56088f194b..a329df3016 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/SpringBatchRetryConfig.java +++ b/spring-batch/src/main/java/com/baeldung/batch/SpringBatchRetryConfig.java @@ -1,12 +1,12 @@ -package org.baeldung.batch; +package com.baeldung.batch; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.baeldung.batch.model.Transaction; -import org.baeldung.batch.service.RecordFieldSetMapper; -import org.baeldung.batch.service.RetryItemProcessor; +import com.baeldung.batch.model.Transaction; +import com.baeldung.batch.service.RecordFieldSetMapper; +import com.baeldung.batch.service.RetryItemProcessor; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; diff --git a/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java b/spring-batch/src/main/java/com/baeldung/batch/SpringConfig.java similarity index 99% rename from spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java rename to spring-batch/src/main/java/com/baeldung/batch/SpringConfig.java index 35abcb2d16..73a07482ce 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java +++ b/spring-batch/src/main/java/com/baeldung/batch/SpringConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.batch; +package com.baeldung.batch; import java.net.MalformedURLException; diff --git a/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java b/spring-batch/src/main/java/com/baeldung/batch/model/Transaction.java similarity index 94% rename from spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java rename to spring-batch/src/main/java/com/baeldung/batch/model/Transaction.java index 8ed1d29e3b..ffb6d59a79 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java +++ b/spring-batch/src/main/java/com/baeldung/batch/model/Transaction.java @@ -1,6 +1,6 @@ -package org.baeldung.batch.model; +package com.baeldung.batch.model; -import org.baeldung.batch.service.adapter.LocalDateTimeAdapter; +import com.baeldung.batch.service.adapter.LocalDateTimeAdapter; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; diff --git a/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/com/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java rename to spring-batch/src/main/java/com/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java index 667e013c35..4fade76ffc 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java +++ b/spring-batch/src/main/java/com/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.baeldung.batch.partitioner; +package com.baeldung.batch.partitioner; import java.util.HashMap; import java.util.Map; diff --git a/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionConfig.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java rename to spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionConfig.java index ad3aee4a2e..b08c95af53 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java +++ b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionConfig.java @@ -1,7 +1,7 @@ -package org.baeldung.batch.partitioner; +package com.baeldung.batch.partitioner; -import org.baeldung.batch.model.Transaction; -import org.baeldung.batch.service.RecordFieldSetMapper; +import com.baeldung.batch.model.Transaction; +import com.baeldung.batch.service.RecordFieldSetMapper; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; diff --git a/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionerApp.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java rename to spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionerApp.java index f456135058..e755e21ca9 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java +++ b/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringbatchPartitionerApp.java @@ -1,4 +1,4 @@ -package org.baeldung.batch.partitioner; +package com.baeldung.batch.partitioner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batch/service/CustomItemProcessor.java similarity index 77% rename from spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java rename to spring-batch/src/main/java/com/baeldung/batch/service/CustomItemProcessor.java index 8ca7892fec..5c5f78f861 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/CustomItemProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; -import org.baeldung.batch.model.Transaction; +import com.baeldung.batch.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class CustomItemProcessor implements ItemProcessor { diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/CustomSkipPolicy.java b/spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/batch/service/CustomSkipPolicy.java rename to spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java index a156a65b6e..25401de022 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/CustomSkipPolicy.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java @@ -1,4 +1,4 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; import org.springframework.batch.core.step.skip.SkipLimitExceededException; import org.springframework.batch.core.step.skip.SkipPolicy; diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/MissingUsernameException.java b/spring-batch/src/main/java/com/baeldung/batch/service/MissingUsernameException.java similarity index 65% rename from spring-batch/src/main/java/org/baeldung/batch/service/MissingUsernameException.java rename to spring-batch/src/main/java/com/baeldung/batch/service/MissingUsernameException.java index 2cf8f4d334..b12daa17cc 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/MissingUsernameException.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/MissingUsernameException.java @@ -1,4 +1,4 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; public class MissingUsernameException extends RuntimeException { } diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/NegativeAmountException.java b/spring-batch/src/main/java/com/baeldung/batch/service/NegativeAmountException.java similarity index 87% rename from spring-batch/src/main/java/org/baeldung/batch/service/NegativeAmountException.java rename to spring-batch/src/main/java/com/baeldung/batch/service/NegativeAmountException.java index c9c05be671..ee46574f87 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/NegativeAmountException.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/NegativeAmountException.java @@ -1,4 +1,4 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; public class NegativeAmountException extends RuntimeException { diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java similarity index 93% rename from spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java rename to spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java index e61c54193a..09478e9a30 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java @@ -1,6 +1,6 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; -import org.baeldung.batch.model.Transaction; +import com.baeldung.batch.model.Transaction; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.validation.BindException; diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/RetryItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java similarity index 95% rename from spring-batch/src/main/java/org/baeldung/batch/service/RetryItemProcessor.java rename to spring-batch/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java index d4e82452a7..c380e2c0ab 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/RetryItemProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java @@ -1,10 +1,10 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; -import org.baeldung.batch.model.Transaction; +import com.baeldung.batch.model.Transaction; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/SkippingItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batch/service/SkippingItemProcessor.java similarity index 88% rename from spring-batch/src/main/java/org/baeldung/batch/service/SkippingItemProcessor.java rename to spring-batch/src/main/java/com/baeldung/batch/service/SkippingItemProcessor.java index 307a8213e2..ee37eb6c1b 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/SkippingItemProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/SkippingItemProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.batch.service; +package com.baeldung.batch.service; -import org.baeldung.batch.model.Transaction; +import com.baeldung.batch.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class SkippingItemProcessor implements ItemProcessor { diff --git a/spring-batch/src/main/java/org/baeldung/batch/service/adapter/LocalDateTimeAdapter.java b/spring-batch/src/main/java/com/baeldung/batch/service/adapter/LocalDateTimeAdapter.java similarity index 93% rename from spring-batch/src/main/java/org/baeldung/batch/service/adapter/LocalDateTimeAdapter.java rename to spring-batch/src/main/java/com/baeldung/batch/service/adapter/LocalDateTimeAdapter.java index 45c35b87f1..561a7335b3 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/service/adapter/LocalDateTimeAdapter.java +++ b/spring-batch/src/main/java/com/baeldung/batch/service/adapter/LocalDateTimeAdapter.java @@ -1,4 +1,4 @@ -package org.baeldung.batch.service.adapter; +package com.baeldung.batch.service.adapter; import javax.xml.bind.annotation.adapters.XmlAdapter; import java.time.LocalDateTime; diff --git a/spring-batch/src/main/java/org/baeldung/batchscheduler/SpringBatchScheduler.java b/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/batchscheduler/SpringBatchScheduler.java rename to spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java index 1beeb6b2bf..4de3e0a4b6 100644 --- a/spring-batch/src/main/java/org/baeldung/batchscheduler/SpringBatchScheduler.java +++ b/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java @@ -1,4 +1,4 @@ -package org.baeldung.batchscheduler; +package com.baeldung.batchscheduler; import java.util.Date; import java.util.IdentityHashMap; @@ -7,7 +7,7 @@ import java.util.Map; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import org.baeldung.batchscheduler.model.Book; +import com.baeldung.batchscheduler.model.Book; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; diff --git a/spring-batch/src/main/java/org/baeldung/batchscheduler/model/Book.java b/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java similarity index 92% rename from spring-batch/src/main/java/org/baeldung/batchscheduler/model/Book.java rename to spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java index f992bde20e..8ee986c729 100644 --- a/spring-batch/src/main/java/org/baeldung/batchscheduler/model/Book.java +++ b/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java @@ -1,4 +1,4 @@ -package org.baeldung.batchscheduler.model; +package com.baeldung.batchscheduler.model; public class Book { private int id; diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchApplication.java b/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchApplication.java similarity index 97% rename from spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchApplication.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchApplication.java index 39bfdfbee7..04185fb1ca 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchApplication.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.batchtesting; +package com.baeldung.batchtesting; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParametersBuilder; diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchConfiguration.java b/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java similarity index 92% rename from spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchConfiguration.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java index 2d891ad7da..664db3fbba 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/SpringBatchConfiguration.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java @@ -1,13 +1,13 @@ -package org.baeldung.batchtesting; +package com.baeldung.batchtesting; import java.io.IOException; -import org.baeldung.batchtesting.model.Book; -import org.baeldung.batchtesting.model.BookDetails; -import org.baeldung.batchtesting.model.BookRecord; -import org.baeldung.batchtesting.service.BookDetailsItemProcessor; -import org.baeldung.batchtesting.service.BookItemProcessor; -import org.baeldung.batchtesting.service.BookRecordFieldSetMapper; +import com.baeldung.batchtesting.model.Book; +import com.baeldung.batchtesting.model.BookDetails; +import com.baeldung.batchtesting.model.BookRecord; +import com.baeldung.batchtesting.service.BookDetailsItemProcessor; +import com.baeldung.batchtesting.service.BookItemProcessor; +import com.baeldung.batchtesting.service.BookRecordFieldSetMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/model/Book.java b/spring-batch/src/main/java/com/baeldung/batchtesting/model/Book.java similarity index 92% rename from spring-batch/src/main/java/org/baeldung/batchtesting/model/Book.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/model/Book.java index 3ea4a29e7f..f34e6cb5f6 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/model/Book.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/model/Book.java @@ -1,4 +1,4 @@ -package org.baeldung.batchtesting.model; +package com.baeldung.batchtesting.model; public class Book { diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/model/BookDetails.java b/spring-batch/src/main/java/com/baeldung/batchtesting/model/BookDetails.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/batchtesting/model/BookDetails.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/model/BookDetails.java index d9284fbc66..3e994d2c92 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/model/BookDetails.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/model/BookDetails.java @@ -1,4 +1,4 @@ -package org.baeldung.batchtesting.model; +package com.baeldung.batchtesting.model; public class BookDetails { diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/model/BookRecord.java b/spring-batch/src/main/java/com/baeldung/batchtesting/model/BookRecord.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/batchtesting/model/BookRecord.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/model/BookRecord.java index 35fb40e878..d6a1692577 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/model/BookRecord.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/model/BookRecord.java @@ -1,4 +1,4 @@ -package org.baeldung.batchtesting.model; +package com.baeldung.batchtesting.model; public class BookRecord { diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookDetailsItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java similarity index 83% rename from spring-batch/src/main/java/org/baeldung/batchtesting/service/BookDetailsItemProcessor.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java index f3800fee51..514a383108 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookDetailsItemProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java @@ -1,7 +1,7 @@ -package org.baeldung.batchtesting.service; +package com.baeldung.batchtesting.service; -import org.baeldung.batchtesting.model.BookDetails; -import org.baeldung.batchtesting.model.BookRecord; +import com.baeldung.batchtesting.model.BookDetails; +import com.baeldung.batchtesting.model.BookRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookItemProcessor.java b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookItemProcessor.java similarity index 79% rename from spring-batch/src/main/java/org/baeldung/batchtesting/service/BookItemProcessor.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/service/BookItemProcessor.java index 69e72ba1d3..84e850fe71 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookItemProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookItemProcessor.java @@ -1,7 +1,7 @@ -package org.baeldung.batchtesting.service; +package com.baeldung.batchtesting.service; -import org.baeldung.batchtesting.model.Book; -import org.baeldung.batchtesting.model.BookRecord; +import com.baeldung.batchtesting.model.Book; +import com.baeldung.batchtesting.model.BookRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; diff --git a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookRecordFieldSetMapper.java b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java similarity index 89% rename from spring-batch/src/main/java/org/baeldung/batchtesting/service/BookRecordFieldSetMapper.java rename to spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java index cfc36fed7a..d9e8ee1158 100644 --- a/spring-batch/src/main/java/org/baeldung/batchtesting/service/BookRecordFieldSetMapper.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java @@ -1,6 +1,6 @@ -package org.baeldung.batchtesting.service; +package com.baeldung.batchtesting.service; -import org.baeldung.batchtesting.model.BookRecord; +import com.baeldung.batchtesting.model.BookRecord; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.validation.BindException; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineProcessor.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineProcessor.java similarity index 92% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineProcessor.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineProcessor.java index 5b6cd9add3..87d0bdc3fb 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.taskletsvschunks.chunks; +package com.baeldung.taskletsvschunks.chunks; -import org.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.model.Line; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineReader.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java similarity index 87% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineReader.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java index 5f6b6de218..6ffa730c19 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LineReader.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java @@ -1,7 +1,7 @@ -package org.baeldung.taskletsvschunks.chunks; +package com.baeldung.taskletsvschunks.chunks; -import org.baeldung.taskletsvschunks.model.Line; -import org.baeldung.taskletsvschunks.utils.FileUtils; +import com.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LinesWriter.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java similarity index 87% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LinesWriter.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java index 66f9103a56..9f292b24b9 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/chunks/LinesWriter.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java @@ -1,7 +1,7 @@ -package org.baeldung.taskletsvschunks.chunks; +package com.baeldung.taskletsvschunks.chunks; -import org.baeldung.taskletsvschunks.model.Line; -import org.baeldung.taskletsvschunks.utils.FileUtils; +import com.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/ChunksConfig.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java similarity index 91% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/ChunksConfig.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java index 601ffb7f27..57288fb312 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/ChunksConfig.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java @@ -1,9 +1,9 @@ -package org.baeldung.taskletsvschunks.config; +package com.baeldung.taskletsvschunks.config; -import org.baeldung.taskletsvschunks.chunks.LineProcessor; -import org.baeldung.taskletsvschunks.chunks.LineReader; -import org.baeldung.taskletsvschunks.chunks.LinesWriter; -import org.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.chunks.LineProcessor; +import com.baeldung.taskletsvschunks.chunks.LineReader; +import com.baeldung.taskletsvschunks.chunks.LinesWriter; +import com.baeldung.taskletsvschunks.model.Line; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/TaskletsConfig.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java similarity index 92% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/TaskletsConfig.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java index b9d06d2639..e7157ac520 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/config/TaskletsConfig.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java @@ -1,8 +1,8 @@ -package org.baeldung.taskletsvschunks.config; +package com.baeldung.taskletsvschunks.config; -import org.baeldung.taskletsvschunks.tasklets.LinesProcessor; -import org.baeldung.taskletsvschunks.tasklets.LinesReader; -import org.baeldung.taskletsvschunks.tasklets.LinesWriter; +import com.baeldung.taskletsvschunks.tasklets.LinesProcessor; +import com.baeldung.taskletsvschunks.tasklets.LinesReader; +import com.baeldung.taskletsvschunks.tasklets.LinesWriter; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/model/Line.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/model/Line.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/model/Line.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/model/Line.java index fee6fd31a6..2d7d3ff63f 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/model/Line.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/model/Line.java @@ -1,4 +1,4 @@ -package org.baeldung.taskletsvschunks.model; +package com.baeldung.taskletsvschunks.model; import java.io.Serializable; import java.time.LocalDate; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesProcessor.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesProcessor.java similarity index 94% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesProcessor.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesProcessor.java index ba7a3088d5..8b84c39174 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesProcessor.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.taskletsvschunks.tasklets; +package com.baeldung.taskletsvschunks.tasklets; -import org.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.model.Line; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesReader.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java similarity index 91% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesReader.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java index 9905ee8f8a..b1f58be4a4 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesReader.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java @@ -1,7 +1,7 @@ -package org.baeldung.taskletsvschunks.tasklets; +package com.baeldung.taskletsvschunks.tasklets; -import org.baeldung.taskletsvschunks.model.Line; -import org.baeldung.taskletsvschunks.utils.FileUtils; +import com.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesWriter.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesWriter.java similarity index 91% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesWriter.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesWriter.java index 937288a890..76128b7841 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/tasklets/LinesWriter.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesWriter.java @@ -1,7 +1,7 @@ -package org.baeldung.taskletsvschunks.tasklets; +package com.baeldung.taskletsvschunks.tasklets; -import org.baeldung.taskletsvschunks.model.Line; -import org.baeldung.taskletsvschunks.utils.FileUtils; +import com.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; diff --git a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/utils/FileUtils.java b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/utils/FileUtils.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/taskletsvschunks/utils/FileUtils.java rename to spring-batch/src/main/java/com/baeldung/taskletsvschunks/utils/FileUtils.java index df36d5c756..fde3b1fa9d 100644 --- a/spring-batch/src/main/java/org/baeldung/taskletsvschunks/utils/FileUtils.java +++ b/spring-batch/src/main/java/com/baeldung/taskletsvschunks/utils/FileUtils.java @@ -1,8 +1,8 @@ -package org.baeldung.taskletsvschunks.utils; +package com.baeldung.taskletsvschunks.utils; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; -import org.baeldung.taskletsvschunks.model.Line; +import com.baeldung.taskletsvschunks.model.Line; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java new file mode 100644 index 0000000000..c977d6ecab --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java @@ -0,0 +1,21 @@ +package org.baeldung.conditionalflow; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ConditionalFlowApplication implements CommandLineRunner { + private static Logger logger = LoggerFactory.getLogger(ConditionalFlowApplication.class); + + public static void main(String[] args) { + SpringApplication.run(ConditionalFlowApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + logger.info("Running conditional flow application..."); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java new file mode 100644 index 0000000000..701011b4d3 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java @@ -0,0 +1,29 @@ +package org.baeldung.conditionalflow; + +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.core.job.flow.FlowExecutionStatus; +import org.springframework.batch.core.job.flow.JobExecutionDecider; + +public class NumberInfoDecider implements JobExecutionDecider { + + public static final String NOTIFY = "NOTIFY"; + public static final String QUIET = "QUIET"; + + /** + * Method that determines notification status of job + * @return true if notifications should be sent. + */ + private boolean shouldNotify() { + return true; + } + + @Override + public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { + if (shouldNotify()) { + return new FlowExecutionStatus(NOTIFY); + } else { + return new FlowExecutionStatus(QUIET); + } + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java new file mode 100644 index 0000000000..906a6e1d28 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java @@ -0,0 +1,91 @@ +package org.baeldung.conditionalflow.config; + +import org.baeldung.conditionalflow.NumberInfoDecider; +import org.baeldung.conditionalflow.model.NumberInfo; +import org.baeldung.conditionalflow.step.*; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +import static org.baeldung.conditionalflow.NumberInfoDecider.NOTIFY; + +@Configuration +@EnableBatchProcessing +public class NumberInfoConfig { + + @Bean + @Qualifier("NotificationStep") + public Step notificationStep(StepBuilderFactory sbf) { + return sbf.get("Notify step") + .tasklet(new NotifierTasklet()) + .build(); + } + + public Step numberGeneratorStep(StepBuilderFactory sbf, int[] values, String prepend) { + return sbf.get("Number generator") + . chunk(1) + .reader(new NumberInfoGenerator(values)) + .processor(new NumberInfoClassifier()) + .writer(new PrependingStdoutWriter<>(prepend)) + .build(); + } + + public Step numberGeneratorStepDecider(StepBuilderFactory sbf, int[] values, String prepend) { + return sbf.get("Number generator decider") + . chunk(1) + .reader(new NumberInfoGenerator(values)) + .processor(new NumberInfoClassifierWithDecider()) + .writer(new PrependingStdoutWriter<>(prepend)) + .build(); + } + + @Bean + @Qualifier("first_job") + public Job numberGeneratorNonNotifierJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) { + int[] nonNotifierData = { -1, -2, -3 }; + Step step = numberGeneratorStep(stepBuilderFactory, nonNotifierData, "First Dataset Processor"); + return jobBuilderFactory.get("Number generator - first dataset") + .start(step) + .on(NOTIFY) + .to(notificationStep) + .from(step) + .on("*") + .stop() + .end() + .build(); + } + + @Bean + @Qualifier("second_job") + public Job numberGeneratorNotifierJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) { + int[] billableData = { 11, -2, -3 }; + Step dataProviderStep = numberGeneratorStep(stepBuilderFactory, billableData, "Second Dataset Processor"); + return jobBuilderFactory.get("Number generator - second dataset") + .start(dataProviderStep) + .on(NOTIFY) + .to(notificationStep) + .end() + .build(); + } + + @Bean + @Qualifier("third_job") + @Primary + public Job numberGeneratorNotifierJobWithDecider(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) { + int[] billableData = { 11, -2, -3 }; + Step dataProviderStep = numberGeneratorStepDecider(stepBuilderFactory, billableData, "Third Dataset Processor"); + return jobBuilderFactory.get("Number generator - third dataset") + .start(dataProviderStep) + .next(new NumberInfoDecider()) + .on(NOTIFY) + .to(notificationStep) + .end() + .build(); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java new file mode 100644 index 0000000000..4134974386 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java @@ -0,0 +1,47 @@ +package org.baeldung.conditionalflow.model; + +import java.util.Objects; + +public class NumberInfo { + private int number; + + public NumberInfo(int number) { + this.number = number; + } + + public static NumberInfo from(int number) { + return new NumberInfo(number); + } + + public boolean isPositive() { + return number > 0; + } + + public boolean isEven() { + return number % 2 == 0; + } + + public int getNumber() { + return number; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + NumberInfo that = (NumberInfo) o; + return number == that.number; + } + + @Override + public int hashCode() { + return Objects.hash(number); + } + + @Override + public String toString() { + return "NumberInfo{" + "number=" + number + '}'; + } +} \ No newline at end of file diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java new file mode 100644 index 0000000000..0d1db66fe9 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java @@ -0,0 +1,15 @@ +package org.baeldung.conditionalflow.step; + +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; + +public class NotifierTasklet implements Tasklet { + @Override + public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { + System.err.println("[" + chunkContext.getStepContext() + .getJobName() + "] contains interesting data!!"); + return RepeatStatus.FINISHED; + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java new file mode 100644 index 0000000000..fdb28263e7 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java @@ -0,0 +1,35 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.core.annotation.BeforeStep; +import org.springframework.batch.core.listener.ItemListenerSupport; +import org.springframework.batch.item.ItemProcessor; + +import static org.baeldung.conditionalflow.NumberInfoDecider.NOTIFY; +import static org.baeldung.conditionalflow.NumberInfoDecider.QUIET; + +public class NumberInfoClassifier extends ItemListenerSupport + implements ItemProcessor { + private StepExecution stepExecution; + + @BeforeStep + public void beforeStep(StepExecution stepExecution) { + this.stepExecution = stepExecution; + this.stepExecution.setExitStatus(new ExitStatus(QUIET)); + } + + @Override + public void afterProcess(NumberInfo item, Integer result) { + super.afterProcess(item, result); + if (item.isPositive()) { + stepExecution.setExitStatus(new ExitStatus(NOTIFY)); + } + } + + @Override + public Integer process(NumberInfo numberInfo) throws Exception { + return Integer.valueOf(numberInfo.getNumber()); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java new file mode 100644 index 0000000000..4a8b7f1963 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java @@ -0,0 +1,13 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.core.listener.ItemListenerSupport; +import org.springframework.batch.item.ItemProcessor; + +public class NumberInfoClassifierWithDecider extends ItemListenerSupport implements ItemProcessor { + + @Override + public Integer process(NumberInfo numberInfo) throws Exception { + return Integer.valueOf(numberInfo.getNumber()); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java new file mode 100644 index 0000000000..606ebf6204 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java @@ -0,0 +1,23 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.item.ItemReader; + +public class NumberInfoGenerator implements ItemReader { + private int[] values; + private int counter; + + public NumberInfoGenerator(int[] values) { + this.values = values; + counter = 0; + } + + @Override + public NumberInfo read() { + if (counter == values.length) { + return null; + } else { + return new NumberInfo(values[counter++]); + } + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java new file mode 100644 index 0000000000..9ffea1e798 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java @@ -0,0 +1,20 @@ +package org.baeldung.conditionalflow.step; + +import java.util.List; + +import org.springframework.batch.item.ItemWriter; + +public class PrependingStdoutWriter implements ItemWriter { + private String prependText; + + public PrependingStdoutWriter(String prependText) { + this.prependText = prependText; + } + + @Override + public void write(List list) { + for (T listItem : list) { + System.out.println(prependText + " " + listItem.toString()); + } + } +} diff --git a/spring-batch/src/main/resources/logback.xml b/spring-batch/src/main/resources/logback.xml index 9a622ceb65..55bbeba870 100644 --- a/spring-batch/src/main/resources/logback.xml +++ b/spring-batch/src/main/resources/logback.xml @@ -8,15 +8,15 @@ - + - + - + diff --git a/spring-batch/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml index 908b8aa2e1..2a7c1e7c4a 100644 --- a/spring-batch/src/main/resources/spring-batch-intro.xml +++ b/spring-batch/src/main/resources/spring-batch-intro.xml @@ -22,14 +22,14 @@ + class="com.baeldung.batch.service.RecordFieldSetMapper" /> - + @@ -40,7 +40,7 @@ - org.baeldung.batch.model.Transaction + com.baeldung.batch.model.Transaction diff --git a/spring-batch/src/test/java/org/baeldung/SpringContextTest.java b/spring-batch/src/test/java/com/baeldung/SpringContextTest.java similarity index 73% rename from spring-batch/src/test/java/org/baeldung/SpringContextTest.java rename to spring-batch/src/test/java/com/baeldung/SpringContextTest.java index 1a4f923a1e..b82bb35daf 100644 --- a/spring-batch/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-batch/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.batch.App; +import com.baeldung.batch.App; import org.junit.Test; public class SpringContextTest { diff --git a/spring-batch/src/test/java/org/baeldung/batch/SpringBatchRetryIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batch/SpringBatchRetryIntegrationTest.java similarity index 98% rename from spring-batch/src/test/java/org/baeldung/batch/SpringBatchRetryIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/batch/SpringBatchRetryIntegrationTest.java index 293c97ac5d..df9154a765 100644 --- a/spring-batch/src/test/java/org/baeldung/batch/SpringBatchRetryIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/batch/SpringBatchRetryIntegrationTest.java @@ -1,5 +1,6 @@ -package org.baeldung.batch; +package com.baeldung.batch; +import com.baeldung.batch.SpringBatchRetryConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.entity.StringEntity; diff --git a/spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java similarity index 96% rename from spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java index 8927421ac5..81877fbc39 100644 --- a/spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java @@ -1,5 +1,6 @@ -package org.baeldung.batchscheduler; +package com.baeldung.batchscheduler; +import com.baeldung.batchscheduler.SpringBatchScheduler; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchIntegrationTest.java similarity index 98% rename from spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchIntegrationTest.java index d66da89ba4..333c69684e 100644 --- a/spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchIntegrationTest.java @@ -1,10 +1,11 @@ -package org.baeldung.batchtesting; +package com.baeldung.batchtesting; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.Collection; +import com.baeldung.batchtesting.SpringBatchConfiguration; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java similarity index 95% rename from spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java index f7b888f0f9..4655117b85 100644 --- a/spring-batch/src/test/java/org/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java @@ -1,12 +1,13 @@ -package org.baeldung.batchtesting; +package com.baeldung.batchtesting; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.Arrays; -import org.baeldung.batchtesting.model.Book; -import org.baeldung.batchtesting.model.BookRecord; +import com.baeldung.batchtesting.SpringBatchConfiguration; +import com.baeldung.batchtesting.model.Book; +import com.baeldung.batchtesting.model.BookRecord; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java similarity index 89% rename from spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java index eaf73e4a4a..1132e4d5e2 100644 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.taskletsvschunks.chunks; +package com.baeldung.taskletsvschunks.chunks; -import org.baeldung.taskletsvschunks.config.ChunksConfig; +import com.baeldung.taskletsvschunks.config.ChunksConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java similarity index 89% rename from spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java rename to spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java index 322b17bd55..2e1ad031aa 100644 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.taskletsvschunks.tasklets; +package com.baeldung.taskletsvschunks.tasklets; -import org.baeldung.taskletsvschunks.config.TaskletsConfig; +import com.baeldung.taskletsvschunks.config.TaskletsConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java new file mode 100644 index 0000000000..e73cb17494 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java @@ -0,0 +1,56 @@ +package org.baeldung.conditionalflow; + +import org.baeldung.conditionalflow.config.NumberInfoConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.test.JobLauncherTestUtils; +import org.springframework.batch.test.context.SpringBatchTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +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 java.util.Collection; +import java.util.Iterator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@SpringBatchTest +@EnableAutoConfiguration +@ContextConfiguration(classes = { NumberInfoConfig.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +public class DeciderJobIntegrationTest { + @Autowired + private JobLauncherTestUtils jobLauncherTestUtils; + + @Test + public void givenNumberGeneratorDecider_whenDeciderRuns_thenStatusIsNotify() throws Exception { + JobExecution jobExecution = jobLauncherTestUtils.launchJob(); + Collection actualStepExecutions = jobExecution.getStepExecutions(); + ExitStatus actualJobExitStatus = jobExecution.getExitStatus(); + + assertEquals("COMPLETED", actualJobExitStatus.getExitCode() + .toString()); + assertEquals(2, actualStepExecutions.size()); + boolean notifyStepDidRun = false; + Iterator iterator = actualStepExecutions.iterator(); + while (iterator.hasNext() && !notifyStepDidRun) { + if (iterator.next() + .getStepName() + .equals("Notify step")) { + notifyStepDidRun = true; + } + } + assertTrue(notifyStepDidRun); + } +} diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java new file mode 100644 index 0000000000..dc396b38da --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java @@ -0,0 +1,71 @@ +package org.baeldung.conditionalflow.model; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +class NumberInfoUnitTest { + + @Test + void givenPositive_whenFrom_isPositive() { + assertTrue(NumberInfo.from(1) + .isPositive()); + assertTrue(NumberInfo.from(11) + .isPositive()); + assertFalse(NumberInfo.from(0) + .isPositive()); + } + + @Test + void givenNegative_whenFrom_isNegative() { + assertFalse(NumberInfo.from(-1) + .isPositive()); + assertFalse(NumberInfo.from(-10) + .isPositive()); + } + + @Test + void givenEven_whenFrom_isEven() { + assertTrue(NumberInfo.from(0) + .isEven()); + assertTrue(NumberInfo.from(-2) + .isEven()); + assertTrue(NumberInfo.from(2) + .isEven()); + assertTrue(NumberInfo.from(-22) + .isEven()); + assertTrue(NumberInfo.from(22) + .isEven()); + } + + @Test + void givenOdd_whenFrom_isOdd() { + + assertFalse(NumberInfo.from(1) + .isEven()); + assertFalse(NumberInfo.from(-1) + .isEven()); + + assertFalse(NumberInfo.from(13) + .isEven()); + assertFalse(NumberInfo.from(-13) + .isEven()); + assertFalse(NumberInfo.from(31) + .isEven()); + assertFalse(NumberInfo.from(-51) + .isEven()); + } + + @Test + void giveGeneratedInt_whenFrom_isNumberFromGenerator() { + for (int i = -100; i < 100; i++) { + assertEquals(i, NumberInfo.from(i) + .getNumber()); + } + } +} \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java new file mode 100644 index 0000000000..cea0626168 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java @@ -0,0 +1,16 @@ +package org.baeldung.conditionalflow.step; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.junit.jupiter.api.Test; + +class NumberInfoClassifierUnitTest { + + @Test + void givenNumberInfo_whenProcess_thenConvertsToInteger() throws Exception { + NumberInfoClassifier nic = new NumberInfoClassifier(); + assertEquals(Integer.valueOf(4), nic.process(NumberInfo.from(4))); + assertEquals(Integer.valueOf(-4), nic.process(NumberInfo.from(-4))); + } +} \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java new file mode 100644 index 0000000000..90fd884674 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java @@ -0,0 +1,21 @@ +package org.baeldung.conditionalflow.step; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.junit.jupiter.api.Test; + +public class NumberInfoGeneratorUnitTest { + + @Test + public void givenArray_whenGenerator_correctOrderAndValue() { + int[] numbers = new int[] { 1, -2, 4, -10 }; + NumberInfoGenerator numberGenerator = new NumberInfoGenerator(numbers); + assertEquals(new NumberInfo(numbers[0]), numberGenerator.read()); + assertEquals(new NumberInfo(numbers[1]), numberGenerator.read()); + assertEquals(new NumberInfo(numbers[2]), numberGenerator.read()); + assertEquals(new NumberInfo(numbers[3]), numberGenerator.read()); + assertNull(numberGenerator.read()); + } +} \ No newline at end of file diff --git a/spring-batch/xml/retryOutput.xml b/spring-batch/xml/retryOutput.xml index d30f2c4a32..c5dec44f16 100644 --- a/spring-batch/xml/retryOutput.xml +++ b/spring-batch/xml/retryOutput.xml @@ -1 +1 @@ -1010000.04302222015-10-31 00:00:001234sammy1012321.04302222015-12-03 00:00:009999john \ No newline at end of file + \ No newline at end of file diff --git a/spring-bom/src/test/java/org/baeldung/SpringContextTest.java b/spring-bom/src/test/java/com/baeldung/SpringContextTest.java similarity index 90% rename from spring-bom/src/test/java/org/baeldung/SpringContextTest.java rename to spring-bom/src/test/java/com/baeldung/SpringContextTest.java index 783567cdfa..0c7da10dd6 100644 --- a/spring-bom/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-bom/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; diff --git a/spring-boot-groovy/pom.xml b/spring-boot-groovy/pom.xml new file mode 100644 index 0000000000..f61398c5d6 --- /dev/null +++ b/spring-boot-groovy/pom.xml @@ -0,0 +1,83 @@ + + + + 4.0.0 + com.baeldung.app + spring-boot-groovy + spring-boot-groovy + war + Spring Boot Todo Application with Groovy + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.codehaus.groovy + groovy + + + + org.springframework.boot + spring-boot-starter-test + test + + + com.h2database + h2 + runtime + + + net.bytebuddy + byte-buddy-dep + 1.10.9 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.codehaus.gmavenplus + gmavenplus-plugin + 1.9.0 + + + + addSources + addTestSources + generateStubs + compile + generateTestStubs + compileTests + removeStubs + removeTestStubs + + + + + + + + + com.baeldung.app.SpringBootGroovyApplication + + + diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/app/SpringBootGroovyApplication.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/app/SpringBootGroovyApplication.groovy new file mode 100644 index 0000000000..226a2ff53d --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/app/SpringBootGroovyApplication.groovy @@ -0,0 +1,13 @@ +package com.baeldung.app + +import org.springframework.boot.SpringApplication +import org.springframework.boot.autoconfigure.SpringBootApplication + +import com.baeldung.app.SpringBootGroovyApplication + +@SpringBootApplication +class SpringBootGroovyApplication { + static void main(String[] args) { + SpringApplication.run SpringBootGroovyApplication, args + } +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/app/controller/TodoController.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/app/controller/TodoController.groovy new file mode 100644 index 0000000000..02f6d0223b --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/app/controller/TodoController.groovy @@ -0,0 +1,48 @@ +package com.baeldung.app.controller + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.web.bind.annotation.DeleteMapping +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.PutMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RestController + +import com.baeldung.app.entity.Todo +import com.baeldung.app.service.TodoService + +@RestController +@RequestMapping('todo') +public class TodoController { + + @Autowired + TodoService todoService + + @GetMapping + List getAllTodoList(){ + todoService.findAll() + } + + @PostMapping + Todo saveTodo(@RequestBody Todo todo){ + todoService.saveTodo todo + } + + @PutMapping + Todo updateTodo(@RequestBody Todo todo){ + todoService.updateTodo todo + } + + @DeleteMapping('/{todoId}') + deleteTodo(@PathVariable Integer todoId){ + todoService.deleteTodo todoId + } + + @GetMapping('/{todoId}') + Todo getTodoById(@PathVariable Integer todoId){ + todoService.findById todoId + } +} \ No newline at end of file diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/app/entity/Todo.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/app/entity/Todo.groovy new file mode 100644 index 0000000000..9f1253c5b3 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/app/entity/Todo.groovy @@ -0,0 +1,23 @@ +package com.baeldung.app.entity + +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 = 'todo') +class Todo { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Integer id + + @Column + String task + + @Column + Boolean isCompleted + +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/app/repository/TodoRepository.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/app/repository/TodoRepository.groovy new file mode 100644 index 0000000000..c0b35cc37d --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/app/repository/TodoRepository.groovy @@ -0,0 +1,9 @@ +package com.baeldung.app.repository + +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +import com.baeldung.app.entity.Todo + +@Repository +interface TodoRepository extends JpaRepository {} \ No newline at end of file diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/app/service/TodoService.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/app/service/TodoService.groovy new file mode 100644 index 0000000000..0a59d93330 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/app/service/TodoService.groovy @@ -0,0 +1,16 @@ +package com.baeldung.app.service + +import com.baeldung.app.entity.Todo + +interface TodoService { + + List findAll() + + Todo findById(Integer todoId) + + Todo saveTodo(Todo todo) + + Todo updateTodo(Todo todo) + + Todo deleteTodo(Integer todoId) +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/app/service/impl/TodoServiceImpl.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/app/service/impl/TodoServiceImpl.groovy new file mode 100644 index 0000000000..6d0ee03a9f --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/app/service/impl/TodoServiceImpl.groovy @@ -0,0 +1,40 @@ +package com.baeldung.app.service.impl + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service + +import com.baeldung.app.entity.Todo +import com.baeldung.app.repository.TodoRepository +import com.baeldung.app.service.TodoService + +@Service +class TodoServiceImpl implements TodoService { + + @Autowired + TodoRepository todoRepository + + @Override + List findAll() { + todoRepository.findAll() + } + + @Override + Todo findById(Integer todoId) { + todoRepository.findById todoId get() + } + + @Override + Todo saveTodo(Todo todo){ + todoRepository.save todo + } + + @Override + Todo updateTodo(Todo todo){ + todoRepository.save todo + } + + @Override + Todo deleteTodo(Integer todoId){ + todoRepository.deleteById todoId + } +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy new file mode 100644 index 0000000000..4912b75a66 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy @@ -0,0 +1,13 @@ +package com.baeldung.springwithgroovy + +import org.springframework.boot.SpringApplication +import org.springframework.boot.autoconfigure.SpringBootApplication + +import com.baeldung.springwithgroovy.SpringBootGroovyApplication + +@SpringBootApplication +class SpringBootGroovyApplication { + static void main(String[] args) { + SpringApplication.run SpringBootGroovyApplication, args + } +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy new file mode 100644 index 0000000000..9c6aee20d3 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy @@ -0,0 +1,48 @@ +package com.baeldung.springwithgroovy.controller + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.web.bind.annotation.DeleteMapping +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.PutMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RestController + +import com.baeldung.springwithgroovy.entity.Todo +import com.baeldung.springwithgroovy.service.TodoService + +@RestController +@RequestMapping('todo') +public class TodoController { + + @Autowired + TodoService todoService + + @GetMapping + List getAllTodoList(){ + todoService.findAll() + } + + @PostMapping + Todo saveTodo(@RequestBody Todo todo){ + todoService.saveTodo todo + } + + @PutMapping + Todo updateTodo(@RequestBody Todo todo){ + todoService.updateTodo todo + } + + @DeleteMapping('/{todoId}') + deleteTodo(@PathVariable Integer todoId){ + todoService.deleteTodo todoId + } + + @GetMapping('/{todoId}') + Todo getTodoById(@PathVariable Integer todoId){ + todoService.findById todoId + } +} \ No newline at end of file diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy new file mode 100644 index 0000000000..000d981701 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy @@ -0,0 +1,23 @@ +package com.baeldung.springwithgroovy.entity + +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 = 'todo') +class Todo { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Integer id + + @Column + String task + + @Column + Boolean isCompleted + +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy new file mode 100644 index 0000000000..eb58cc0791 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy @@ -0,0 +1,9 @@ +package com.baeldung.springwithgroovy.repository + +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +import com.baeldung.springwithgroovy.entity.Todo + +@Repository +interface TodoRepository extends JpaRepository {} \ No newline at end of file diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy new file mode 100644 index 0000000000..c57af34cde --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy @@ -0,0 +1,16 @@ +package com.baeldung.springwithgroovy.service + +import com.baeldung.springwithgroovy.entity.Todo + +interface TodoService { + + List findAll() + + Todo findById(Integer todoId) + + Todo saveTodo(Todo todo) + + Todo updateTodo(Todo todo) + + Todo deleteTodo(Integer todoId) +} diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy new file mode 100644 index 0000000000..943c1c6944 --- /dev/null +++ b/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy @@ -0,0 +1,40 @@ +package com.baeldung.springwithgroovy.service.impl + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service + +import com.baeldung.springwithgroovy.entity.Todo +import com.baeldung.springwithgroovy.repository.TodoRepository +import com.baeldung.springwithgroovy.service.TodoService + +@Service +class TodoServiceImpl implements TodoService { + + @Autowired + TodoRepository todoRepository + + @Override + List findAll() { + todoRepository.findAll() + } + + @Override + Todo findById(Integer todoId) { + todoRepository.findById todoId get() + } + + @Override + Todo saveTodo(Todo todo){ + todoRepository.save todo + } + + @Override + Todo updateTodo(Todo todo){ + todoRepository.save todo + } + + @Override + Todo deleteTodo(Integer todoId){ + todoRepository.deleteById todoId + } +} diff --git a/spring-boot-groovy/src/main/resources/application.properties b/spring-boot-groovy/src/main/resources/application.properties new file mode 100644 index 0000000000..8d53a190bb --- /dev/null +++ b/spring-boot-groovy/src/main/resources/application.properties @@ -0,0 +1,5 @@ +spring.datasource.url=jdbc:h2:mem:todo +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password=sa +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/spring-boot-groovy/src/test/groovy/com/baeldung/app/TodoAppUnitTest.groovy b/spring-boot-groovy/src/test/groovy/com/baeldung/app/TodoAppUnitTest.groovy new file mode 100644 index 0000000000..faf2d64ba7 --- /dev/null +++ b/spring-boot-groovy/src/test/groovy/com/baeldung/app/TodoAppUnitTest.groovy @@ -0,0 +1,97 @@ +package com.baeldung.app + +import static org.junit.jupiter.api.Assertions.assertEquals +import static org.junit.jupiter.api.Assertions.assertTrue + +import org.junit.BeforeClass +import org.junit.Test +import org.junit.runner.RunWith +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.test.context.event.annotation.BeforeTestClass +import org.springframework.test.context.junit4.SpringRunner + +import com.baeldung.app.entity.Todo + +import io.restassured.RestAssured +import io.restassured.response.Response + +class TodoAppUnitTest { + static API_ROOT = 'http://localhost:8081/todo' + static readingTodoId + static writingTodoId + + @BeforeClass + static void populateDummyData() { + Todo readingTodo = new Todo(task: 'Reading', isCompleted: false) + Todo writingTodo = new Todo(task: 'Writing', isCompleted: false) + + final Response readingResponse = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(readingTodo).post(API_ROOT) + + Todo cookingTodoResponse = readingResponse.as Todo.class + readingTodoId = cookingTodoResponse.getId() + + final Response writingResponse = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(writingTodo).post(API_ROOT) + + Todo writingTodoResponse = writingResponse.as Todo.class + writingTodoId = writingTodoResponse.getId() + } + + @Test + void whenGetAllTodoList_thenOk(){ + final Response response = RestAssured.get(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + assertTrue response.as(List.class).size() > 0 + } + + @Test + void whenGetTodoById_thenOk(){ + final Response response = + RestAssured.get("$API_ROOT/$readingTodoId") + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + Todo todoResponse = response.as Todo.class + assertEquals readingTodoId,todoResponse.getId() + } + + @Test + void whenUpdateTodoById_thenOk(){ + Todo todo = new Todo(id:readingTodoId, isCompleted: true) + final Response response = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(todo).put(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + Todo todoResponse = response.as Todo.class + assertTrue todoResponse.getIsCompleted() + } + + @Test + void whenDeleteTodoById_thenOk(){ + final Response response = + RestAssured.given() + .delete("$API_ROOT/$writingTodoId") + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + } + + @Test + void whenSaveTodo_thenOk(){ + Todo todo = new Todo(task: 'Blogging', isCompleted: false) + final Response response = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(todo).post(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + } +} \ No newline at end of file diff --git a/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy b/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy new file mode 100644 index 0000000000..bf8b0ff27f --- /dev/null +++ b/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy @@ -0,0 +1,97 @@ +package com.baeldung.springwithgroovy + +import static org.junit.jupiter.api.Assertions.assertEquals +import static org.junit.jupiter.api.Assertions.assertTrue + +import org.junit.BeforeClass +import org.junit.Test +import org.junit.runner.RunWith +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.test.context.event.annotation.BeforeTestClass +import org.springframework.test.context.junit4.SpringRunner + +import com.baeldung.springwithgroovy.entity.Todo + +import io.restassured.RestAssured +import io.restassured.response.Response + +class TodoAppUnitTest { + static API_ROOT = 'http://localhost:8081/todo' + static readingTodoId + static writingTodoId + + @BeforeClass + static void populateDummyData() { + Todo readingTodo = new Todo(task: 'Reading', isCompleted: false) + Todo writingTodo = new Todo(task: 'Writing', isCompleted: false) + + final Response readingResponse = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(readingTodo).post(API_ROOT) + + Todo cookingTodoResponse = readingResponse.as Todo.class + readingTodoId = cookingTodoResponse.getId() + + final Response writingResponse = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(writingTodo).post(API_ROOT) + + Todo writingTodoResponse = writingResponse.as Todo.class + writingTodoId = writingTodoResponse.getId() + } + + @Test + void whenGetAllTodoList_thenOk(){ + final Response response = RestAssured.get(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + assertTrue response.as(List.class).size() > 0 + } + + @Test + void whenGetTodoById_thenOk(){ + final Response response = + RestAssured.get("$API_ROOT/$readingTodoId") + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + Todo todoResponse = response.as Todo.class + assertEquals readingTodoId,todoResponse.getId() + } + + @Test + void whenUpdateTodoById_thenOk(){ + Todo todo = new Todo(id:readingTodoId, isCompleted: true) + final Response response = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(todo).put(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + Todo todoResponse = response.as Todo.class + assertTrue todoResponse.getIsCompleted() + } + + @Test + void whenDeleteTodoById_thenOk(){ + final Response response = + RestAssured.given() + .delete("$API_ROOT/$writingTodoId") + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + } + + @Test + void whenSaveTodo_thenOk(){ + Todo todo = new Todo(task: 'Blogging', isCompleted: false) + final Response response = + RestAssured.given() + .contentType(MediaType.APPLICATION_JSON_VALUE) + .body(todo).post(API_ROOT) + + assertEquals HttpStatus.OK.value(),response.getStatusCode() + } +} \ No newline at end of file diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index c8d153d4bb..228e7ce481 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -20,6 +20,7 @@ spring-boot-annotations spring-boot-artifacts spring-boot-autoconfiguration + spring-boot-basic-customization spring-boot-bootstrap spring-boot-client spring-boot-config-jpa-error diff --git a/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java index 834f26dacf..78a1ab7a54 100644 --- a/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java index c185456019..3322193134 100644 --- a/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java index 961d756a68..0f4fa757d6 100644 --- a/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-annotations/pom.xml b/spring-boot-modules/spring-boot-annotations/pom.xml index 9ad63214ef..59de83b4e5 100644 --- a/spring-boot-modules/spring-boot-annotations/pom.xml +++ b/spring-boot-modules/spring-boot-annotations/pom.xml @@ -24,6 +24,22 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.zaxxer + HikariCP + + + + + + org.hibernate + hibernate-core + @@ -32,4 +48,5 @@ test + diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/ConditionalBeanConfiguration.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/ConditionalBeanConfiguration.java new file mode 100644 index 0000000000..4719425663 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/ConditionalBeanConfiguration.java @@ -0,0 +1,16 @@ +package com.baeldung.annotations; + +import java.util.Properties; + +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ConditionalBeanConfiguration { + + @Conditional(HibernateCondition.class) + Properties additionalProperties() { + // application specific properties + return new Properties(); + } +} diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HealthCheckController.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HealthCheckController.java new file mode 100644 index 0000000000..e87ed6cb47 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HealthCheckController.java @@ -0,0 +1,16 @@ +package com.baeldung.annotations; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HealthCheckController { + + private static final String STATUS = "UP"; + + @GetMapping("/health") + public ResponseEntity healthCheck() { + return ResponseEntity.ok(STATUS); + } +} diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HibernateCondition.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HibernateCondition.java new file mode 100644 index 0000000000..e2d77cc5d0 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HibernateCondition.java @@ -0,0 +1,15 @@ +package com.baeldung.annotations; + +import org.springframework.context.annotation.Condition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.core.type.AnnotatedTypeMetadata; + +public class HibernateCondition implements Condition { + + @Override + public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { + // application specific condition check + return true; + } + +} diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/MySQLAutoconfiguration.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/MySQLAutoconfiguration.java new file mode 100644 index 0000000000..ba23267525 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/MySQLAutoconfiguration.java @@ -0,0 +1,59 @@ +package com.baeldung.annotations; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import javax.sql.DataSource; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +@Configuration +@ConditionalOnClass(DataSource.class) +public class MySQLAutoconfiguration { + + @Bean + @ConditionalOnBean(name = "dataSource") + LocalContainerEntityManagerFactoryBean entityManagerFactory() throws IOException { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + return em; + } + + @Bean + @ConditionalOnProperty(name = "usemysql", havingValue = "local") + DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); + dataSource.setUrl("jdbc:hsqldb:mem:testdb"); + dataSource.setUsername( "sa" ); + dataSource.setPassword( "" ); + return dataSource; + } + + @ConditionalOnResource(resources = "classpath:mysql.properties") + Properties additionalProperties() throws IOException { + final Properties additionalProperties = new Properties(); + + try (InputStream inputStream = new ClassPathResource("classpath:mysql.properties").getInputStream()) { + additionalProperties.load(inputStream); + } + + return additionalProperties; + } +} diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/WebApplicationSpecificConfiguration.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/WebApplicationSpecificConfiguration.java new file mode 100644 index 0000000000..62f68bee29 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/WebApplicationSpecificConfiguration.java @@ -0,0 +1,13 @@ +package com.baeldung.annotations; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class WebApplicationSpecificConfiguration { + + @ConditionalOnWebApplication + HealthCheckController healthCheckController() { + return new HealthCheckController(); + } +} diff --git a/spring-boot-modules/spring-boot-artifacts/pom.xml b/spring-boot-modules/spring-boot-artifacts/pom.xml index f7c8636593..de9f6ab635 100644 --- a/spring-boot-modules/spring-boot-artifacts/pom.xml +++ b/spring-boot-modules/spring-boot-artifacts/pom.xml @@ -208,7 +208,7 @@ - org.baeldung.boot.Application + com.baeldung.boot.Application 3.1.1 3.3.7-1 2.2 diff --git a/spring-boot-modules/spring-boot-basic-customization/README.md b/spring-boot-modules/spring-boot-basic-customization/README.md new file mode 100644 index 0000000000..6c067fc5a1 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/README.md @@ -0,0 +1,14 @@ +## Spring Boot Basic Customization + +This module contains articles about Spring Boot customization + +### Relevant Articles: + + - [How to Change the Default Port in Spring Boot](https://www.baeldung.com/spring-boot-change-port) + - [Using Custom Banners in Spring Boot](https://www.baeldung.com/spring-boot-custom-banners) + - [Create a Custom FailureAnalyzer with Spring Boot](https://www.baeldung.com/spring-boot-failure-analyzer) + - [Spring Boot: Customize Whitelabel Error Page](https://www.baeldung.com/spring-boot-custom-error-page) + - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) + - [How to Define a Spring Boot Filter?](https://www.baeldung.com/spring-boot-add-filter) + - [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) + - [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) diff --git a/spring-boot-modules/spring-boot-basic-customization/pom.xml b/spring-boot-modules/spring-boot-basic-customization/pom.xml new file mode 100644 index 0000000000..7c2c89def4 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + spring-boot-basic-customization + spring-boot-basic-customization + jar + Module For Spring Boot Basic Customization + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + com.baeldung.changeport.CustomApplication + + diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java similarity index 93% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java index aa794182de..42da61fe14 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java @@ -1,10 +1,8 @@ package com.baeldung.bootcustomfilters; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - import com.baeldung.bootcustomfilters.filters.RequestResponseLoggingFilter; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Configuration; @Configuration public class FilterConfig { diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/SpringBootFiltersApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java similarity index 99% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java index 97165f2cf3..50d5f4ea71 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java @@ -1,16 +1,15 @@ package com.baeldung.bootcustomfilters.controller; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - +import com.baeldung.bootcustomfilters.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.baeldung.bootcustomfilters.model.User; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; /** * Rest controller for User diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java similarity index 86% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java index e42ea7d2dd..3924354932 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/RequestResponseLoggingFilter.java @@ -1,21 +1,15 @@ package com.baeldung.bootcustomfilters.filters; -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + /** * A servlet filter to log request and response * The logging implementation is pretty native and for demonstration only diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java similarity index 85% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java index d92b723e73..604829c3d3 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/filters/TransactionFilter.java @@ -1,20 +1,14 @@ package com.baeldung.bootcustomfilters.filters; -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + /** * A filter to create transaction before and commit it once request completes * The current implemenatation is just for demo diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/model/User.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/model/User.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/bootcustomfilters/model/User.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/bootcustomfilters/model/User.java diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/changeport/CustomApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/CustomApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/changeport/CustomApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/CustomApplication.java diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java similarity index 73% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java index 5dd55ef077..9f6c209deb 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java @@ -2,10 +2,8 @@ package com.baeldung.errorhandling; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; -@SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.errorhandling") +@SpringBootApplication(scanBasePackages = "com.baeldung.errorhandling") public class ErrorHandlingApplication { public static void main(String [] args) { diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/IndexController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java new file mode 100644 index 0000000000..c28f908fb8 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/event/ExitCodeEventDemoApplication.java @@ -0,0 +1,31 @@ +package com.baeldung.exitcode.event; + +import org.springframework.boot.ExitCodeEvent; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.event.EventListener; + +@SpringBootApplication +public class ExitCodeEventDemoApplication { + + public static void main(String[] args) { + System.exit( + SpringApplication.exit( + SpringApplication.run(ExitCodeEventDemoApplication.class, args) + ) + ); + } + + @Bean + DemoListener demoListenerBean() { + return new DemoListener(); + } + + private static class DemoListener { + @EventListener + public void exitEvent(ExitCodeEvent event) { + System.out.println("Exit code: " + event.getExitCode()); + } + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java new file mode 100644 index 0000000000..44b4ff36f5 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/exception/ExitCodeExceptionMapperDemoApplication.java @@ -0,0 +1,31 @@ +package com.baeldung.exitcode.exception; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeExceptionMapper; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class ExitCodeExceptionMapperDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(ExitCodeExceptionMapperDemoApplication.class, args); + } + + @Bean + CommandLineRunner createException() { + return args -> Integer.parseInt("test"); + } + + @Bean + ExitCodeExceptionMapper exitCodeToExceptionMapper() { + return exception -> { + // set exit code based on the exception type + if (exception.getCause() instanceof NumberFormatException) { + return 80; + } + return 1; + }; + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java new file mode 100644 index 0000000000..7f7acbe86e --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/exitcode/generator/ExitCodeGeneratorDemoApplication.java @@ -0,0 +1,22 @@ +package com.baeldung.exitcode.generator; + +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ExitCodeGeneratorDemoApplication implements ExitCodeGenerator { + + public static void main(String[] args) { + System.exit( + SpringApplication.exit( + SpringApplication.run(ExitCodeGeneratorDemoApplication.class, args) + ) + ); + } + + @Override + public int getExitCode() { + return 42; + } +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java index 7bd5c36786..d08fa05c6e 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java @@ -1,10 +1,10 @@ package com.baeldung.failureanalyzer; -import javax.annotation.security.RolesAllowed; - import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import javax.annotation.security.RolesAllowed; + @SpringBootApplication public class FailureAnalyzerApplication { @RolesAllowed("*") diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyDAO.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyDAO.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyDAO.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyDAO.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MySecondDAO.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyService.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyService.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyService.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyService.java index 72334ca8fa..f31b67615f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyService.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/failureanalyzer/MyService.java @@ -1,9 +1,9 @@ package com.baeldung.failureanalyzer; -import javax.annotation.Resource; - import org.springframework.stereotype.Service; +import javax.annotation.Resource; + @Service public class MyService { diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/FaviconApplication.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/FaviconApplication.java new file mode 100644 index 0000000000..f94549b988 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/FaviconApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.favicon; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FaviconApplication { + + public static void main(String[] args) { + SpringApplication.run(FaviconApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/config/FaviconConfiguration.java similarity index 96% rename from spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java rename to spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/config/FaviconConfiguration.java index 9a1f47b5cb..d1809199d6 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/favicon/config/FaviconConfiguration.java @@ -1,8 +1,4 @@ -package com.baeldung.springbootmvc.config; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +package com.baeldung.favicon.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -14,8 +10,13 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + @Configuration public class FaviconConfiguration { + @Bean public SimpleUrlHandlerMapping myFaviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); @@ -33,7 +34,7 @@ public class FaviconConfiguration { return requestHandler; } - // @Controller + // @Controller static class FaviconController { @RequestMapping(value = "favicon.ico", method = RequestMethod.GET) diff --git a/spring-boot-modules/spring-boot/src/main/resources/META-INF/spring.factories b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/META-INF/spring.factories rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/META-INF/spring.factories diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application-errorhandling.properties b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application-errorhandling.properties new file mode 100644 index 0000000000..0a6d68763c --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application-errorhandling.properties @@ -0,0 +1,10 @@ +#server +server.port=9000 +spring.mvc.servlet.path=/ +server.servlet.context-path=/ +server.error.whitelabel.enabled=false + +#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration + +#for Spring Boot 2.0+ +#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties new file mode 100644 index 0000000000..4d4a6ec7bd --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties @@ -0,0 +1,7 @@ +#spring.banner.charset=UTF-8 +#spring.banner.location=classpath:banner.txt +#spring.banner.image.location=classpath:banner.gif +#spring.banner.image.width= //TODO +#spring.banner.image.height= //TODO +#spring.banner.image.margin= //TODO +#spring.banner.image.invert= //TODO diff --git a/spring-boot-modules/spring-boot/src/main/resources/banner.txt b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/banner.txt similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/banner.txt rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/banner.txt diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/com/baeldung/images/favicon.ico similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/com/baeldung/images/favicon.ico diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/favicon.ico b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/favicon.ico similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/resources/favicon.ico rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/favicon.ico diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/static/favicon.ico b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/static/favicon.ico similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/main/resources/static/favicon.ico rename to spring-boot-modules/spring-boot-basic-customization/src/main/resources/static/favicon.ico diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-404.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-404.html new file mode 100644 index 0000000000..555cf52de4 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-404.html @@ -0,0 +1,7 @@ + + + +

Sorry, we couldn't find the page you were looking for.

+

Go Home

+ + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-500.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-500.html new file mode 100644 index 0000000000..fc64c7e180 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error-500.html @@ -0,0 +1,9 @@ + + + +

Sorry, something went wrong!

+ +

We're fixing it.

+

Go Home

+ + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error.html new file mode 100644 index 0000000000..4e953059e2 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error.html @@ -0,0 +1,8 @@ + + + +

Something went wrong!

+

Our Engineers are on it.

+

Go Home

+ + diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error/404.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error/404.html new file mode 100644 index 0000000000..df83ce219b --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/error/404.html @@ -0,0 +1,8 @@ + + + RESOURCE NOT FOUND + + +

404 RESOURCE NOT FOUND

+ + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/index.html b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/index.html new file mode 100644 index 0000000000..95c68c8600 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/templates/index.html @@ -0,0 +1,6 @@ + + +

Welcome Home

+

Success! It is working as we expected.

+ + diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java rename to spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java index b3555f55da..2d9fb56217 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/FailureAnalyzerAppIntegrationTest.java @@ -1,18 +1,16 @@ package com.baeldung.failureanalyzer; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Collection; -import java.util.stream.Collectors; - +import ch.qos.logback.classic.spi.ILoggingEvent; +import com.baeldung.failureanalyzer.utils.ListAppender; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.SpringApplication; -import com.baeldung.failureanalyzer.utils.ListAppender; +import java.util.Collection; +import java.util.stream.Collectors; -import ch.qos.logback.classic.spi.ILoggingEvent; +import static org.assertj.core.api.Assertions.assertThat; public class FailureAnalyzerAppIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java rename to spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java index a298f49ff5..091cd687f1 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/test/java/com/baeldung/failureanalyzer/utils/ListAppender.java @@ -1,11 +1,11 @@ package com.baeldung.failureanalyzer.utils; -import java.util.ArrayList; -import java.util.List; - import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import java.util.ArrayList; +import java.util.List; + public class ListAppender extends AppenderBase { static private List events = new ArrayList<>(); diff --git a/spring-boot-modules/spring-boot/src/test/resources/logback-test.xml b/spring-boot-modules/spring-boot-basic-customization/src/test/resources/logback-test.xml similarity index 51% rename from spring-boot-modules/spring-boot/src/test/resources/logback-test.xml rename to spring-boot-modules/spring-boot-basic-customization/src/test/resources/logback-test.xml index 9e0f4e221f..6919a457cb 100644 --- a/spring-boot-modules/spring-boot/src/test/resources/logback-test.xml +++ b/spring-boot-modules/spring-boot-basic-customization/src/test/resources/logback-test.xml @@ -1,15 +1,15 @@ + resource="org/springframework/boot/logging/logback/base.xml" /> + class="com.baeldung.failureanalyzer.utils.ListAppender"> + name="org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter"> - \ No newline at end of file + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java index 8324fabfca..ce743e0f77 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/Application.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/Application.java similarity index 100% rename from spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/Application.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/Application.java diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/Details.java similarity index 93% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/Details.java index 1e3ddf7b21..c806476634 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/Details.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.client; +package com.baeldung.boot.client; public class Details { diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/DetailsServiceClient.java similarity index 93% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/DetailsServiceClient.java index f2b9d6d030..a9f1b08c97 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/DetailsServiceClient.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.client; +package com.baeldung.boot.client; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Service; diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/Message.java similarity index 89% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/Message.java index 2744c49f62..19140f76a2 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/Message.java @@ -1,4 +1,4 @@ -package org.baeldung.websocket.client; +package com.baeldung.websocket.client; public class Message { diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/MyStompSessionHandler.java similarity index 98% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/MyStompSessionHandler.java index 92beab9430..8ccc42c58a 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/MyStompSessionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.websocket.client; +package com.baeldung.websocket.client; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/StompClient.java similarity index 96% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/StompClient.java index 2bff07186d..04d87dd2ed 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/StompClient.java @@ -1,4 +1,4 @@ -package org.baeldung.websocket.client; +package com.baeldung.websocket.client; import java.util.Scanner; diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/Application.java b/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/Application.java deleted file mode 100644 index c1b6558b26..0000000000 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.boot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ApplicationContext; - -@SpringBootApplication -public class Application { - private static ApplicationContext applicationContext; - - public static void main(String[] args) { - applicationContext = SpringApplication.run(Application.class, args); - } -} diff --git a/spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/SpringContextTest.java similarity index 86% rename from spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/SpringContextTest.java index 9c3b83ea79..1341f17eac 100644 --- a/spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.boot.Application; +import com.baeldung.boot.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/boot/client/DetailsServiceClientIntegrationTest.java similarity index 90% rename from spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java rename to spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/boot/client/DetailsServiceClientIntegrationTest.java index d423300b85..4af5370950 100644 --- a/spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/boot/client/DetailsServiceClientIntegrationTest.java @@ -1,10 +1,12 @@ -package org.baeldung.boot.client; +package com.baeldung.boot.client; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; -import org.baeldung.boot.Application; +import com.baeldung.boot.Application; +import com.baeldung.boot.client.Details; +import com.baeldung.boot.client.DetailsServiceClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java index bb1b5e254e..57eec935f6 100644 --- a/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.websocket.client; -import org.baeldung.websocket.client.MyStompSessionHandler; import org.junit.Test; import org.mockito.Mockito; import org.springframework.messaging.simp.stomp.StompHeaders; diff --git a/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/README.md b/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/README.md deleted file mode 100644 index 443ec07183..0000000000 --- a/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-application/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Unable to Find @SpringBootConfiguration with @DataJpaTest](https://www.baeldung.com/spring-boot-unable-to-find-springbootconfiguration-with-datajpatest) diff --git a/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/README.md b/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/README.md deleted file mode 100644 index 4e852f8a90..0000000000 --- a/spring-boot-modules/spring-boot-config-jpa-error/data-jpa-library/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Unable to Find @SpringBootConfiguration with @DataJpaTest](https://www.baeldung.com/spring-boot-unable-to-find-springbootconfiguration-with-datajpatest) diff --git a/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java index ff3e795778..ca8989724b 100644 --- a/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; diff --git a/spring-boot-modules/spring-boot-custom-starter/README.md b/spring-boot-modules/spring-boot-custom-starter/README.md index d74dc222d5..667be7ca40 100644 --- a/spring-boot-modules/spring-boot-custom-starter/README.md +++ b/spring-boot-modules/spring-boot-custom-starter/README.md @@ -1,6 +1,6 @@ ## Spring Boot Custom Starter -This module contains articles about writing [Spring Boot Starters](https://www.baeldung.com/spring-boot-starters). +This module contains articles about writing Spring Boot Starters. ### Relevant Articles: - [Creating a Custom Starter with Spring Boot](https://www.baeldung.com/spring-boot-custom-starter) diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/com/baeldung/SpringContextTest.java index e6ce83fab5..b4668e7d2b 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml index 818ce5c107..8d328b88be 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../../parent-boot-1 + ../../../parent-boot-2 diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java index b82b67df68..7103da97f3 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml index 89119e2e99..47296990aa 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/greeter/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../../parent-boot-1 + ../../../parent-boot-2 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-deployment/pom.xml b/spring-boot-modules/spring-boot-deployment/pom.xml index 64c0e698f6..b3fc3eabd1 100644 --- a/spring-boot-modules/spring-boot-deployment/pom.xml +++ b/spring-boot-modules/spring-boot-deployment/pom.xml @@ -190,7 +190,7 @@ - org.baeldung.boot.Application + com.baeldung.boot.Application 3.1.1 3.3.7-1 2.2 diff --git a/spring-boot-modules/spring-boot-gradle/build.gradle b/spring-boot-modules/spring-boot-gradle/build.gradle index 96055536c3..faae01a1a5 100644 --- a/spring-boot-modules/spring-boot-gradle/build.gradle +++ b/spring-boot-modules/spring-boot-gradle/build.gradle @@ -21,7 +21,7 @@ apply plugin: 'io.spring.dependency-management' //add tasks thinJar and thinResolve for thin JAR deployments apply plugin: 'org.springframework.boot.experimental.thin-launcher' -group = 'org.baeldung' +group = 'com.baeldung' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 @@ -35,16 +35,16 @@ dependencies { } springBoot { - mainClassName = 'org.baeldung.DemoApplication' + mainClassName = 'com.baeldung.DemoApplication' } bootJar { // This is overridden by the mainClassName in springBoot{} and added here for reference purposes. - mainClassName = 'org.baeldung.DemoApplication' + mainClassName = 'com.baeldung.DemoApplication' // This block serves the same purpose as the above thus commented out. Added here for reference purposes // manifest { -// attributes 'Start-Class': 'org.baeldung.DemoApplication' +// attributes 'Start-Class': 'com.baeldung.DemoApplication' // } } diff --git a/spring-boot-modules/spring-boot-gradle/src/main/java/org/baeldung/DemoApplication.java b/spring-boot-modules/spring-boot-gradle/src/main/java/com/baeldung/DemoApplication.java similarity index 92% rename from spring-boot-modules/spring-boot-gradle/src/main/java/org/baeldung/DemoApplication.java rename to spring-boot-modules/spring-boot-gradle/src/main/java/com/baeldung/DemoApplication.java index f8df823f25..64bac6936b 100644 --- a/spring-boot-modules/spring-boot-gradle/src/main/java/org/baeldung/DemoApplication.java +++ b/spring-boot-modules/spring-boot-gradle/src/main/java/com/baeldung/DemoApplication.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-gradle/src/test/java/org/baeldung/DemoApplicationTests.java b/spring-boot-modules/spring-boot-gradle/src/test/java/com/baeldung/DemoApplicationTests.java similarity index 93% rename from spring-boot-modules/spring-boot-gradle/src/test/java/org/baeldung/DemoApplicationTests.java rename to spring-boot-modules/spring-boot-gradle/src/test/java/com/baeldung/DemoApplicationTests.java index b24bfb2cb6..65395582cb 100644 --- a/spring-boot-modules/spring-boot-gradle/src/test/java/org/baeldung/DemoApplicationTests.java +++ b/spring-boot-modules/spring-boot-gradle/src/test/java/com/baeldung/DemoApplicationTests.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java index ab6e4557d5..97810cf590 100644 --- a/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java index 4effccc083..3f3ecd87d0 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-libraries/README.md b/spring-boot-modules/spring-boot-libraries/README.md index f0bc3c9e89..c02fb69e5d 100644 --- a/spring-boot-modules/spring-boot-libraries/README.md +++ b/spring-boot-modules/spring-boot-libraries/README.md @@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide to ShedLock with Spring](https://www.baeldung.com/shedlock-spring) - [A Guide to the Problem Spring Web Library](https://www.baeldung.com/problem-spring-web) +- [Generating Barcodes and QR Codes in Java](https://www.baeldung.com/java-generating-barcodes-qr-codes) diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index ba1164dd59..090967d8a8 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -28,6 +28,10 @@ org.springframework.boot spring-boot-starter-tomcat + + org.springframework.boot + spring-boot-starter-data-jpa + org.springframework.boot spring-boot-starter-test @@ -52,9 +56,47 @@ shedlock-provider-jdbc-template ${shedlock.version} + + com.h2database + h2 + ${h2.version} + + + + net.sourceforge.barbecue + barbecue + ${barbecue.version} + + + net.sf.barcode4j + barcode4j + ${barcode4j.version} + + + com.github.kenglxn.qrgen + javase + ${qrgen.version} + + + com.google.zxing + core + ${zxing.version} + + + com.google.zxing + javase + ${zxing.version} + + + + jitpack.io + https://jitpack.io + + + spring-boot-libraries @@ -152,7 +194,12 @@ 2.2.4 2.3.2 0.23.0 + 1.4.200 2.1.0 + 1.5-beta1 + 2.1 + 2.6.0 + 3.3.0
diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/BarcodesController.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/BarcodesController.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/BarcodesController.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/BarcodesController.java diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/SpringBootApp.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/SpringBootApp.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/SpringBootApp.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/SpringBootApp.java diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/BarbecueBarcodeGenerator.java diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/Barcode4jBarcodeGenerator.java diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/QRGenBarcodeGenerator.java diff --git a/libraries-3/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/barcodes/generators/ZxingBarcodeGenerator.java diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java similarity index 85% rename from spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java index 060afe660e..cd5f63e962 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java @@ -5,9 +5,8 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component -class TaskScheduler { - - @Scheduled(cron = "*/15 * * * *") +class BaeldungTaskScheduler { + @Scheduled(cron = "0 0/15 * * * ?") @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") public void scheduledTask() { System.out.println("Running ShedLock task"); diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java index 74ea39683d..440e1ffc6a 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java @@ -1,12 +1,16 @@ package com.baeldung.scheduling.shedlock; +import net.javacrumbs.shedlock.core.LockProvider; +import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; -import org.springframework.scheduling.annotation.EnableScheduling; + +import javax.sql.DataSource; @Configuration -@EnableScheduling -@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") public class SchedulerConfiguration { - + @Bean + public LockProvider lockProvider(DataSource dataSource) { + return new JdbcTemplateLockProvider(dataSource); + } } \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java new file mode 100644 index 0000000000..cebb234036 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.scheduling.shedlock; + +import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@EnableScheduling +@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") +public class SpringBootShedlockApplication { + public static void main(String[] args) { + SpringApplication.run(SpringBootShedlockApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml new file mode 100644 index 0000000000..3477520208 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + datasource: + driverClassName: org.h2.Driver + url: jdbc:h2:mem:shedlock_DB;INIT=CREATE SCHEMA IF NOT EXISTS shedlock;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + username: sa + password: diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java new file mode 100644 index 0000000000..47f42c133f --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.scheduling.shedlock; + +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.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class BaeldungTaskSchedulerIntegrationTest { + @Autowired + private BaeldungTaskScheduler taskScheduler; + + @Test + public void whenShedLockConfigCorrect_thenSpringCtxtStartsWithoutError() { + // save the old out + PrintStream old = System.out; + + // Create a stream to hold the output for test + ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(consoleOutput); + System.setOut(ps); + //test + taskScheduler.scheduledTask(); + System.out.flush(); + String expected = "Running ShedLock task\n"; + assertThat(consoleOutput.toString()).isEqualTo(expected); + + //restore the old out + System.setOut(old); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/group/LogGroupApplication.java b/spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/group/LogGroupApplication.java new file mode 100644 index 0000000000..021f27bd98 --- /dev/null +++ b/spring-boot-modules/spring-boot-logging-log4j2/src/main/java/com/baeldung/group/LogGroupApplication.java @@ -0,0 +1,26 @@ +package com.baeldung.group; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@SpringBootApplication +@ActiveProfiles("log-group") +public class LogGroupApplication { + + private static final Logger LOGGER = LoggerFactory.getLogger(LogGroupApplication.class); + + @RequestMapping("/log-group") + public void justLog() { + LOGGER.debug("Received a request"); + } + + public static void main(String[] args) { + SpringApplication.run(LogGroupApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/application-log-group.properties b/spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/application-log-group.properties new file mode 100644 index 0000000000..6dfe11724e --- /dev/null +++ b/spring-boot-modules/spring-boot-logging-log4j2/src/main/resources/application-log-group.properties @@ -0,0 +1 @@ +logging.level.web=debug \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java index 9817522e68..d2660ad84e 100644 --- a/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-mvc-2/README.md b/spring-boot-modules/spring-boot-mvc-2/README.md index 4200f58024..c42730f9cc 100644 --- a/spring-boot-modules/spring-boot-mvc-2/README.md +++ b/spring-boot-modules/spring-boot-mvc-2/README.md @@ -7,4 +7,8 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Functional Controllers in Spring MVC](https://www.baeldung.com/spring-mvc-functional-controllers) - [Specify an Array of Strings as Body Parameters in Swagger](https://www.baeldung.com/swagger-body-array-of-strings) - [Swagger @ApiParam vs @ApiModelProperty](https://www.baeldung.com/swagger-apiparam-vs-apimodelproperty) +- [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) +- [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) +- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) +- [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) - More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc) diff --git a/spring-boot-modules/spring-boot-mvc-2/pom.xml b/spring-boot-modules/spring-boot-mvc-2/pom.xml index edebd41986..3c503eb23d 100644 --- a/spring-boot-modules/spring-boot-mvc-2/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-2/pom.xml @@ -49,6 +49,27 @@ org.apache.commons commons-lang3 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.h2database + h2 + + + + com.thoughtworks.xstream + xstream + ${xstream.version} @@ -79,7 +100,11 @@ Spring Milestones https://repo.spring.io/milestone - + + jcenter-snapshots + jcenter + http://oss.jfrog.org/artifactory/oss-snapshot-local/ + @@ -103,6 +128,7 @@ com.baeldung.swagger2boot.SpringBootSwaggerApplication 2.2.0.BUILD-SNAPSHOT + 1.4.11.1 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java new file mode 100644 index 0000000000..e553ca1b72 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java @@ -0,0 +1,95 @@ +package com.baeldung.etag; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Version; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + @Version + private long version; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getVersion() { + return version; + } + + public void setVersion(long version) { + this.version = version; + } + + // + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java new file mode 100644 index 0000000000..58f366501d --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java @@ -0,0 +1,58 @@ +package com.baeldung.etag; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +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.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController +@RequestMapping(value = "/foos") +public class FooController { + + @Autowired + private FooDao fooDao; + + @GetMapping(value = "/{id}") + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + return fooDao.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + } + + // Note: the global filter overrides the ETag value we set here. We can still + // analyze its behaviour in the Integration Test. + @GetMapping(value = "/{id}/custom-etag") + public ResponseEntity findByIdWithCustomEtag(@PathVariable("id") final Long id, + final HttpServletResponse response) { + final Foo foo = fooDao.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + return ResponseEntity.ok().eTag(Long.toString(foo.getVersion())).body(foo); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { + return fooDao.save(resource); + } + + @PutMapping(value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { + fooDao.save(resource); + } + + @DeleteMapping(value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void delete(@PathVariable("id") final Long id) { + fooDao.deleteById(id); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java new file mode 100644 index 0000000000..aff011af4a --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java @@ -0,0 +1,8 @@ +package com.baeldung.etag; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface FooDao extends CrudRepository{ +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java new file mode 100644 index 0000000000..9e58a1550c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.etag; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootEtagApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootEtagApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java new file mode 100644 index 0000000000..bef468452a --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java @@ -0,0 +1,28 @@ +package com.baeldung.etag; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.ShallowEtagHeaderFilter; + +@Configuration +public class WebConfig { + + // Etags + + // If we're not using Spring Boot we can make use of + // AbstractAnnotationConfigDispatcherServletInitializer#getServletFilters + @Bean + public FilterRegistrationBean shallowEtagHeaderFilter() { + FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>( new ShallowEtagHeaderFilter()); + filterRegistrationBean.addUrlPatterns("/foos/*"); + filterRegistrationBean.setName("etagFilter"); + return filterRegistrationBean; + } + + // We can also just declare the filter directly + // @Bean + // public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { + // return new ShallowEtagHeaderFilter(); + // } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/SpringBootStudentsApplication.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/SpringBootStudentsApplication.java new file mode 100644 index 0000000000..9c499e6103 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/SpringBootStudentsApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.students; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootStudentsApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootStudentsApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/Student.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/Student.java new file mode 100644 index 0000000000..16d02fe14a --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/Student.java @@ -0,0 +1,53 @@ +package com.baeldung.students; + +public class Student { + + private long id; + private String firstName; + private String lastName; + + public Student() {} + + public Student(String firstName, String lastName) { + super(); + this.firstName = firstName; + this.lastName = lastName; + } + + public Student(long id, String firstName, String lastName) { + super(); + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public String toString() { + return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentController.java new file mode 100644 index 0000000000..c71bb6c6e6 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentController.java @@ -0,0 +1,74 @@ +package com.baeldung.students; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +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.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.baeldung.students.StudentService; + +@RestController +@RequestMapping("/students") +public class StudentController { + + @Autowired + private StudentService service; + + @GetMapping("/") + public List read() { + return service.readAll(); + } + + @GetMapping("/{id}") + public ResponseEntity read(@PathVariable("id") Long id) { + Student foundStudent = service.read(id); + if (foundStudent == null) { + return ResponseEntity.notFound().build(); + } else { + return ResponseEntity.ok(foundStudent); + } + } + + @PostMapping("/") + public ResponseEntity create(@RequestBody Student student) throws URISyntaxException { + Student createdStudent = service.create(student); + + URI uri = ServletUriComponentsBuilder.fromCurrentRequest() + .path("/{id}") + .buildAndExpand(createdStudent.getId()) + .toUri(); + + return ResponseEntity.created(uri) + .body(createdStudent); + + } + + @PutMapping("/{id}") + public ResponseEntity update(@RequestBody Student student, @PathVariable Long id) { + Student updatedStudent = service.update(id, student); + if (updatedStudent == null) { + return ResponseEntity.notFound().build(); + } else { + return ResponseEntity.ok(updatedStudent); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteStudent(@PathVariable Long id) { + service.delete(id); + + return ResponseEntity.noContent().build(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentService.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentService.java new file mode 100644 index 0000000000..80f6dfd514 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentService.java @@ -0,0 +1,51 @@ +package com.baeldung.students; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Service; + +@Service +public class StudentService { + + // DB repository mock + private Map repository = Arrays.asList( + new Student[]{ + new Student(1, "Alan","Turing"), + new Student(2, "Sebastian","Bach"), + new Student(3, "Pablo","Picasso"), + }).stream() + .collect(Collectors.toConcurrentMap(s -> s.getId(), Function.identity())); + + // DB id sequence mock + private AtomicLong sequence = new AtomicLong(3); + + public List readAll() { + return repository.values().stream().collect(Collectors.toList()); + } + + public Student read(Long id) { + return repository.get(id); + } + + public Student create(Student student) { + long key = sequence.incrementAndGet(); + student.setId(key); + repository.put(key, student); + return student; + } + + public Student update(Long id, Student student) { + student.setId(id); + Student oldStudent = repository.replace(id, student); + return oldStudent == null ? null : student; + } + + public void delete(Long id) { + repository.remove(id); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml new file mode 100644 index 0000000000..7f36b33b38 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties index 709574239b..7070d4c2f0 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties @@ -1 +1,4 @@ -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true +spring.mvc.static-path-pattern=/content/** +spring.webflux.static-path-pattern=/content/** +spring.resources.static-locations=classpath:/files/,classpath:/static-files \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html new file mode 100644 index 0000000000..15df316612 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html @@ -0,0 +1,10 @@ + + + + + Hello World! + + +Hello World! + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/foo_API_test.postman_collection.json b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/foo_API_test.postman_collection.json new file mode 100644 index 0000000000..dc4acafab3 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/foo_API_test.postman_collection.json @@ -0,0 +1,180 @@ +{ + "info": { + "_postman_id": "9989b5be-13ba-4d22-8e43-d05dbf628e58", + "name": "foo API test", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "add a foo", + "event": [ + { + "listen": "test", + "script": { + "id": "a01534dc-6fc7-4c54-ba1d-6bcf311e5836", + "exec": [ + "pm.test(\"success status\", () => pm.response.to.be.success );", + "", + "pm.test(\"name is correct\", () => ", + " pm.expect(pm.response.json().name).to.equal(\"Transformers\"));", + "", + "pm.test(\"id was assigned\", () => ", + " pm.expect(pm.response.json().id).to.be.not.null );", + "", + "pm.variables.set(\"id\", pm.response.json().id);" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "name": "Content-Type", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Transformers\"\n}" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos" + ] + } + }, + "response": [] + }, + { + "name": "get a foo", + "event": [ + { + "listen": "test", + "script": { + "id": "03de440c-b483-4ab8-a11a-d0c99b349963", + "exec": [ + "pm.test(\"success status\", () => pm.response.to.be.success );", + "", + "pm.test(\"name is correct\", () => ", + " pm.expect(pm.response.json().name).to.equal(\"Transformers\"));", + "", + "pm.test(\"id is correct\", () => ", + " pm.expect(pm.response.json().id).to.equal(pm.variables.get(\"id\")) );" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos", + "{{id}}" + ] + } + }, + "response": [] + }, + { + "name": "delete a foo", + "event": [ + { + "listen": "test", + "script": { + "id": "74c1bb0f-c06c-48b1-a545-459233541b14", + "exec": [ + "pm.test(\"success status\", () => pm.response.to.be.success );" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "DELETE", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos", + "{{id}}" + ] + } + }, + "response": [] + }, + { + "name": "verify delete", + "event": [ + { + "listen": "test", + "script": { + "id": "03de440c-b483-4ab8-a11a-d0c99b349963", + "exec": [ + "pm.test(\"status is 500\", () => pm.response.to.have.status(500) );", + "", + "pm.test(\"no value present\", () => ", + " pm.expect(pm.response.json().cause).to.equal(\"No value present\"));" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos", + "{{id}}" + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java new file mode 100644 index 0000000000..88c5ae1686 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java @@ -0,0 +1,123 @@ +package com.baeldung.etag; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.assertj.core.util.Preconditions; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ComponentScan(basePackageClasses = WebConfig.class) +@EnableAutoConfiguration +public class EtagIntegrationTest { + + @LocalServerPort + private int port; + + @Test + public void givenResourceExists_whenRetrievingResource_thenEtagIsAlsoReturned() { + // Given + final String uriOfResource = createAsUri(); + + // When + final Response findOneResponse = RestAssured.given().header("Accept", "application/json").get(uriOfResource); + + // Then + assertNotNull(findOneResponse.getHeader(HttpHeaders.ETAG)); + } + + @Test + public void givenResourceWasRetrieved_whenRetrievingAgainWithEtag_thenNotModifiedReturned() { + // Given + final String uriOfResource = createAsUri(); + final Response findOneResponse = RestAssured.given().header("Accept", "application/json").get(uriOfResource); + final String etagValue = findOneResponse.getHeader(HttpHeaders.ETAG); + + // When + final Response secondFindOneResponse = RestAssured.given().header("Accept", "application/json") + .headers("If-None-Match", etagValue).get(uriOfResource); + + // Then + assertTrue(secondFindOneResponse.getStatusCode() == 304); + } + + @Test + public void givenResourceWasRetrievedThenModified_whenRetrievingAgainWithEtag_thenResourceIsReturned() { + // Given + final String uriOfResource = createAsUri(); + final Response firstFindOneResponse = RestAssured.given().header("Accept", "application/json") + .get(uriOfResource); + final String etagValue = firstFindOneResponse.getHeader(HttpHeaders.ETAG); + final long createdId = firstFindOneResponse.jsonPath().getLong("id"); + + Foo updatedFoo = new Foo("updated value"); + updatedFoo.setId(createdId); + Response updatedResponse = RestAssured.given().contentType(ContentType.JSON).body(updatedFoo) + .put(uriOfResource); + assertThat(updatedResponse.getStatusCode() == 200); + + // When + final Response secondFindOneResponse = RestAssured.given().header("Accept", "application/json") + .headers("If-None-Match", etagValue).get(uriOfResource); + + // Then + assertTrue(secondFindOneResponse.getStatusCode() == 200); + } + + @Test + @Ignore("Not Yet Implemented By Spring - https://jira.springsource.org/browse/SPR-10164") + public void givenResourceExists_whenRetrievedWithIfMatchIncorrectEtag_then412IsReceived() { + // Given + final String uriOfResource = createAsUri(); + + // When + final Response findOneResponse = RestAssured.given().header("Accept", "application/json") + .headers("If-Match", randomAlphabetic(8)).get(uriOfResource); + + // Then + assertTrue(findOneResponse.getStatusCode() == 412); + } + + private final String createAsUri() { + final Response response = createAsResponse(new Foo(randomAlphabetic(6))); + Preconditions.checkState(response.getStatusCode() == 201, "create operation: " + response.getStatusCode()); + + return getURL() + "/" + response.getBody().as(Foo.class).getId(); + } + + private Response createAsResponse(final Foo resource) { + String resourceAsString; + try { + resourceAsString = new ObjectMapper().writeValueAsString(resource); + } catch (JsonProcessingException e) { + throw new AssertionError("Error during serialization"); + } + return RestAssured.given().contentType(MediaType.APPLICATION_JSON.toString()).body(resourceAsString) + .post(getURL()); + } + + private String getURL() { + return "http://localhost:" + port + "/foos"; + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java new file mode 100644 index 0000000000..e65b106ead --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java @@ -0,0 +1,82 @@ +package com.baeldung.mime; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.etag.Foo; +import com.baeldung.etag.WebConfig; + +import io.restassured.RestAssured; +import io.restassured.response.Response; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes= WebConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ComponentScan({"com.baeldung.mime", "com.baeldung.etag"}) +@EnableAutoConfiguration +@ActiveProfiles("test") +public class FooLiveTest { + + @LocalServerPort + private int port; + + @Autowired + protected IMarshaller marshaller; + + // API + + public final void create() { + create(new Foo(randomAlphabetic(6))); + } + + public final String createAsUri() { + return createAsUri(new Foo(randomAlphabetic(6))); + } + + protected final void create(final Foo resource) { + createAsUri(resource); + } + + private final String createAsUri(final Foo resource) { + final Response response = createAsResponse(resource); + return getURL() + "/" + response.getBody().as(Foo.class).getId(); + } + + private final Response createAsResponse(final Foo resource) { + + final String resourceAsString = marshaller.encode(resource); + return RestAssured.given() + .contentType(marshaller.getMime()) + .body(resourceAsString) + .post(getURL()); + } + + // + + protected String getURL() { + return "http://localhost:" + port + "/foos"; + } + + @Test + public void givenResourceExists_whenRetrievingResource_thenEtagIsAlsoReturned() { + // Given + final String uriOfResource = createAsUri(); + + // When + final Response findOneResponse = RestAssured.given().header("Accept", "application/json").get(uriOfResource); + + // Then + assertEquals(findOneResponse.getStatusCode(), 200); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/IMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/IMarshaller.java new file mode 100644 index 0000000000..79c0616043 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/IMarshaller.java @@ -0,0 +1,15 @@ +package com.baeldung.mime; + +import java.util.List; + +public interface IMarshaller { + + String encode(final T entity); + + T decode(final String entityAsString, final Class clazz); + + List decodeList(final String entitiesAsString, final Class clazz); + + String getMime(); + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java new file mode 100644 index 0000000000..9dee0ef2cd --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java @@ -0,0 +1,75 @@ +package com.baeldung.mime; + +import java.io.IOException; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; + +import com.baeldung.etag.Foo; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +public final class JacksonMarshaller implements IMarshaller { + private final Logger logger = LoggerFactory.getLogger(JacksonMarshaller.class); + + private final ObjectMapper objectMapper; + + public JacksonMarshaller() { + super(); + + objectMapper = new ObjectMapper(); + } + + // API + + @Override + public final String encode(final T resource) { + String entityAsJSON = null; + try { + entityAsJSON = objectMapper.writeValueAsString(resource); + } catch (final IOException ioEx) { + logger.error("", ioEx); + } + + return entityAsJSON; + } + + @Override + public final T decode(final String resourceAsString, final Class clazz) { + T entity = null; + try { + entity = objectMapper.readValue(resourceAsString, clazz); + } catch (final IOException ioEx) { + logger.error("", ioEx); + } + + return entity; + } + + @SuppressWarnings("unchecked") + @Override + public final List decodeList(final String resourcesAsString, final Class clazz) { + List entities = null; + try { + if (clazz.equals(Foo.class)) { + entities = objectMapper.readValue(resourcesAsString, new TypeReference>() { + // ... + }); + } else { + entities = objectMapper.readValue(resourcesAsString, List.class); + } + } catch (final IOException ioEx) { + logger.error("", ioEx); + } + + return entities; + } + + @Override + public final String getMime() { + return MediaType.APPLICATION_JSON.toString(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/TestMarshallerFactory.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/TestMarshallerFactory.java new file mode 100644 index 0000000000..d7cd875ae4 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/TestMarshallerFactory.java @@ -0,0 +1,48 @@ +package com.baeldung.mime; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Profile("test") +public class TestMarshallerFactory implements FactoryBean { + + @Autowired + private Environment env; + + public TestMarshallerFactory() { + super(); + } + + // API + + @Override + public IMarshaller getObject() { + final String testMime = env.getProperty("test.mime"); + if (testMime != null) { + switch (testMime) { + case "json": + return new JacksonMarshaller(); + case "xml": + return new XStreamMarshaller(); + default: + throw new IllegalStateException(); + } + } + + return new JacksonMarshaller(); + } + + @Override + public Class getObjectType() { + return IMarshaller.class; + } + + @Override + public boolean isSingleton() { + return true; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java new file mode 100644 index 0000000000..2c67694e83 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java @@ -0,0 +1,46 @@ +package com.baeldung.mime; + +import java.util.List; + +import org.springframework.http.MediaType; + +import com.baeldung.etag.Foo; +import com.thoughtworks.xstream.XStream; + +public final class XStreamMarshaller implements IMarshaller { + + private XStream xstream; + + public XStreamMarshaller() { + super(); + + xstream = new XStream(); + xstream.autodetectAnnotations(true); + xstream.processAnnotations(Foo.class); + } + + // API + + @Override + public final String encode(final T resource) { + return xstream.toXML(resource); + } + + @SuppressWarnings("unchecked") + @Override + public final T decode(final String resourceAsString, final Class clazz) { + return (T) xstream.fromXML(resourceAsString); + } + + @SuppressWarnings("unchecked") + @Override + public List decodeList(final String resourcesAsString, final Class clazz) { + return this.decode(resourcesAsString, List.class); + } + + @Override + public final String getMime() { + return MediaType.APPLICATION_XML.toString(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/students/StudentControllerIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/students/StudentControllerIntegrationTest.java new file mode 100644 index 0000000000..577dbb6eb1 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/students/StudentControllerIntegrationTest.java @@ -0,0 +1,73 @@ +package com.baeldung.students; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +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.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.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.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class StudentControllerIntegrationTest { + + private static final String STUDENTS_PATH = "/students/"; + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenReadAll_thenStatusIsOk() throws Exception { + this.mockMvc.perform(get(STUDENTS_PATH)) + .andExpect(status().isOk()); + } + + @Test + public void whenReadOne_thenStatusIsOk() throws Exception { + this.mockMvc.perform(get(STUDENTS_PATH + 1)) + .andExpect(status().isOk()); + } + + @Test + public void whenCreate_thenStatusIsCreated() throws Exception { + Student student = new Student(10, "Albert", "Einstein"); + this.mockMvc.perform(post(STUDENTS_PATH).content(asJsonString(student)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isCreated()); + } + + @Test + public void whenUpdate_thenStatusIsOk() throws Exception { + Student student = new Student(1, "Nikola", "Tesla"); + this.mockMvc.perform(put(STUDENTS_PATH + 1) + .content(asJsonString(student)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()); + } + + @Test + public void whenDelete_thenStatusIsNoContent() throws Exception { + this.mockMvc.perform(delete(STUDENTS_PATH + 3)) + .andExpect(status().isNoContent()); + } + + private String asJsonString(final Object obj) { + try { + return new ObjectMapper().writeValueAsString(obj); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md index 2e67c42ede..41b98063a6 100644 --- a/spring-boot-modules/spring-boot-mvc/README.md +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -4,7 +4,6 @@ This module contains articles about Spring Web MVC in Spring Boot projects. ### Relevant Articles: -- [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) - [Custom Validation MessageSource in Spring Boot](https://www.baeldung.com/spring-custom-validation-message-source) - [Display RSS Feed with Spring MVC](https://www.baeldung.com/spring-mvc-rss-feed) - [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java index 069dd41b8d..209a93d94c 100644 --- a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java index 16e0708fc9..e73f4e79f7 100644 --- a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java index 41f26d51f7..e54f28837d 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.configurationproperties.ConfigProperties; @SpringBootApplication -@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class }) +@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class, Database.class }) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java new file mode 100644 index 0000000000..6e798672e7 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java @@ -0,0 +1,33 @@ +package com.baeldung.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "database") +public class Database { + + private String url; + private String username; + private String password; + + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java index d43f18f6a7..5b954f8941 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration -@ComponentScan("org.baeldung.properties.core") +@ComponentScan("com.baeldung.properties.core") @PropertySource("classpath:foo.properties") public class ExternalPropertiesWithJavaConfig { diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java index 6d105428d9..9080e3d0ba 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:configForProperties.xml") -@ComponentScan("org.baeldung.core") +@ComponentScan("com.baeldung.core") public class ExternalPropertiesWithXmlConfig { public ExternalPropertiesWithXmlConfig() { diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java index 6f1e4c8490..f45f5b6a03 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:configForPropertiesOne.xml") -@ComponentScan("org.baeldung.core") +@ComponentScan("com.baeldung.core") public class ExternalPropertiesWithXmlConfigOne { public ExternalPropertiesWithXmlConfigOne() { diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties index 2e06fad574..d4d1df7abc 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties @@ -1,4 +1,8 @@ management.endpoints.web.exposure.include=refresh spring.properties.refreshDelay=1000 spring.config.location=file:extra.properties -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true + +database.url=jdbc:postgresql:/localhost:5432/instance +database.username=foo +database.password=bar \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java new file mode 100644 index 0000000000..0b9bd797ae --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.configurationproperties; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.properties.ConfigPropertiesDemoApplication; +import com.baeldung.properties.Database; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigPropertiesDemoApplication.class) +@TestPropertySource("classpath:application.properties") +public class DatabasePropertiesIntegrationTest { + + @Autowired + private Database database; + + @Test + public void testDatabaseProperties() { + Assert.assertNotNull(database); + Assert.assertEquals("jdbc:postgresql:/localhost:5432/instance", database.getUrl()); + Assert.assertEquals("foo", database.getUsername()); + Assert.assertEquals("bar", database.getPassword()); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties b/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties index 2e06fad574..d4d1df7abc 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties +++ b/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties @@ -1,4 +1,8 @@ management.endpoints.web.exposure.include=refresh spring.properties.refreshDelay=1000 spring.config.location=file:extra.properties -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true + +database.url=jdbc:postgresql:/localhost:5432/instance +database.username=foo +database.password=bar \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java index 874c4f582f..2e1a17199d 100644 --- a/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java index 874c4f582f..2e1a17199d 100644 --- a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-runtime/README.md b/spring-boot-modules/spring-boot-runtime/README.md index a544faf830..62727ecc76 100644 --- a/spring-boot-modules/spring-boot-runtime/README.md +++ b/spring-boot-modules/spring-boot-runtime/README.md @@ -8,7 +8,6 @@ This module contains articles about administering a Spring Boot runtime - [Logging HTTP Requests with Spring Boot Actuator HTTP Tracing](https://www.baeldung.com/spring-boot-actuator-http) - [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) - [Spring Boot Embedded Tomcat Logs](https://www.baeldung.com/spring-boot-embedded-tomcat-logs) - - [How to Change the Default Port in Spring Boot](https://www.baeldung.com/spring-boot-change-port) - [Project Configuration with Spring](https://www.baeldung.com/project-configuration-with-spring) - [CORS with Spring](https://www.baeldung.com/spring-cors) - [Spring – Log Incoming Requests](https://www.baeldung.com/spring-http-logging) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/disabling-console-jul/README.md b/spring-boot-modules/spring-boot-runtime/disabling-console-jul/README.md deleted file mode 100644 index 554f051b41..0000000000 --- a/spring-boot-modules/spring-boot-runtime/disabling-console-jul/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) diff --git a/spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/README.md b/spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/README.md deleted file mode 100644 index 554f051b41..0000000000 --- a/spring-boot-modules/spring-boot-runtime/disabling-console-log4j2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java index f20fba737a..40f5341e29 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java @@ -1,43 +1,22 @@ package com.baeldung.web.log.app; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; import org.springframework.context.annotation.PropertySource; import com.baeldung.web.log.config.CustomeRequestLoggingFilter; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; - @EnableAutoConfiguration @ComponentScan("com.baeldung.web.log") @PropertySource("application-log.properties") @SpringBootApplication -public class Application extends SpringBootServletInitializer { +public class Application { public static void main(final String[] args) { SpringApplication.run(Application.class, args); } - - @Override - public void onStartup(ServletContext container) throws ServletException { - - AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.setConfigLocation("com.baeldung.web.log"); - container.addListener(new ContextLoaderListener(context)); - - ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context)); - dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/"); - - container.addFilter("customRequestLoggingFilter", CustomeRequestLoggingFilter.class).addMappingForServletNames(null, false, "dispatcher"); - } } \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomWebAppInitializer.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomWebAppInitializer.java new file mode 100644 index 0000000000..f51bb52990 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomWebAppInitializer.java @@ -0,0 +1,25 @@ +package com.baeldung.web.log.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; +import org.springframework.web.WebApplicationInitializer; + +public class CustomWebAppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) throws ServletException { + + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.setConfigLocation("com.baeldung.web.log"); + container.addListener(new ContextLoaderListener(context)); + + ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/"); + + container.addFilter("customRequestLoggingFilter", CustomeRequestLoggingFilter.class).addMappingForServletNames(null, false, "dispatcher"); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml index fd8a9e71ae..375cf06c2c 100644 --- a/spring-boot-modules/spring-boot-springdoc/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -1,7 +1,8 @@ - + 4.0.0 spring-boot-springdoc 0.0.1-SNAPSHOT @@ -16,11 +17,6 @@ ../../parent-boot-2 - - 1.8 - 1.2.32 - - org.springframework.boot @@ -41,6 +37,12 @@ test + + org.hibernate + hibernate-core + ${hibernate.version} + + org.springdoc @@ -63,6 +65,12 @@ + + 1.8 + 5.2.10.Final + 1.2.32 + + integration diff --git a/spring-boot-modules/spring-boot-testing/README.md b/spring-boot-modules/spring-boot-testing/README.md index 882e2be766..192f5cee99 100644 --- a/spring-boot-modules/spring-boot-testing/README.md +++ b/spring-boot-modules/spring-boot-testing/README.md @@ -13,3 +13,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level) - [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis) - [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties) +- [Prevent ApplicationRunner or CommandLineRunner Beans From Executing During Junit Testing](https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution) diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationCommandLineRunnerApp.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationCommandLineRunnerApp.java new file mode 100644 index 0000000000..76e18dfd2f --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationCommandLineRunnerApp.java @@ -0,0 +1,11 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationCommandLineRunnerApp { + public static void main(String[] args) { + SpringApplication.run(ApplicationCommandLineRunnerApp.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java new file mode 100644 index 0000000000..3bf08491bf --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java @@ -0,0 +1,27 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Profile("!test") +@ConditionalOnProperty( + prefix = "application.runner", + value = "enabled", + havingValue = "true", + matchIfMissing = true) +@Component +public class ApplicationRunnerTaskExecutor implements ApplicationRunner { + private TaskService taskService; + + public ApplicationRunnerTaskExecutor(TaskService taskService) { + this.taskService = taskService; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + taskService.execute("application runner task"); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java new file mode 100644 index 0000000000..38fd3b9c0a --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java @@ -0,0 +1,26 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Profile("!test") +@ConditionalOnProperty( + prefix = "command.line.runner", + value = "enabled", + havingValue = "true", + matchIfMissing = true) +@Component +public class CommandLineTaskExecutor implements CommandLineRunner { + private TaskService taskService; + + public CommandLineTaskExecutor(TaskService taskService) { + this.taskService = taskService; + } + + @Override + public void run(String... args) throws Exception { + taskService.execute("command line runner task"); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java new file mode 100644 index 0000000000..dac437e72d --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java @@ -0,0 +1,14 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +@Service +public class TaskService { + private static Logger logger = LoggerFactory.getLogger(TaskService.class); + + public void execute(String task) { + logger.info("do " + task); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/LoadSpringContextIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/LoadSpringContextIntegrationTest.java new file mode 100644 index 0000000000..6698094550 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/LoadSpringContextIntegrationTest.java @@ -0,0 +1,43 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.prevent.commandline.application.runner.execution.ApplicationCommandLineRunnerApp; +import com.baeldung.prevent.commandline.application.runner.execution.TaskService; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { ApplicationCommandLineRunnerApp.class }, + initializers = ConfigFileApplicationContextInitializer.class) +public class LoadSpringContextIntegrationTest { + @SpyBean + TaskService taskService; + + @SpyBean + CommandLineRunner commandLineRunner; + + @SpyBean + ApplicationRunner applicationRunner; + + @Test + void whenContextLoads_thenRunnersDoNotRun() throws Exception { + assertNotNull(taskService); + assertNotNull(commandLineRunner); + assertNotNull(applicationRunner); + + verify(taskService, times(0)).execute(any()); + verify(commandLineRunner, times(0)).run(any()); + verify(applicationRunner, times(0)).run(any()); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java new file mode 100644 index 0000000000..26a7339f1d --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.SpyBean; + +import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor; +import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@SpringBootTest +class RunApplicationIntegrationTest { + @SpyBean + ApplicationRunnerTaskExecutor applicationRunnerTaskExecutor; + @SpyBean + CommandLineTaskExecutor commandLineTaskExecutor; + + @Test + void whenContextLoads_thenRunnersRun() throws Exception { + verify(applicationRunnerTaskExecutor, times(1)).run(any()); + verify(commandLineTaskExecutor, times(1)).run(any()); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestProfileIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestProfileIntegrationTest.java new file mode 100644 index 0000000000..333cd2ab91 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestProfileIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import org.junit.jupiter.api.Test; +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.ActiveProfiles; + +import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor; +import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor; +import com.baeldung.prevent.commandline.application.runner.execution.TaskService; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@ActiveProfiles("test") +@SpringBootTest +class RunApplicationWithTestProfileIntegrationTest { + @Autowired + private ApplicationContext context; + + @Test + void whenContextLoads_thenRunnersAreNotLoaded() { + assertNotNull(context.getBean(TaskService.class)); + assertThrows(NoSuchBeanDefinitionException.class, + () -> context.getBean(CommandLineTaskExecutor.class), + "CommandLineRunner should not be loaded during this integration test"); + assertThrows(NoSuchBeanDefinitionException.class, + () -> context.getBean(ApplicationRunnerTaskExecutor.class), + "ApplicationRunner should not be loaded during this integration test"); + } +} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestPropertiesIntegrationTest.java new file mode 100644 index 0000000000..264a06a41e --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestPropertiesIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.prevent.commandline.application.runner.execution; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; +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 com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor; +import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor; +import com.baeldung.prevent.commandline.application.runner.execution.TaskService; + +@SpringBootTest(properties = { + "command.line.runner.enabled=false", + "application.runner.enabled=false" }) +class RunApplicationWithTestPropertiesIntegrationTest { + @Autowired + private ApplicationContext context; + + @Test + void whenContextLoads_thenRunnersAreNotLoaded() { + assertNotNull(context.getBean(TaskService.class)); + assertThrows(NoSuchBeanDefinitionException.class, + () -> context.getBean(CommandLineTaskExecutor.class), + "CommandLineRunner should not be loaded during this integration test"); + assertThrows(NoSuchBeanDefinitionException.class, + () -> context.getBean(ApplicationRunnerTaskExecutor.class), + "ApplicationRunner should not be loaded during this integration test"); + } +} diff --git a/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java index 16e0708fc9..e73f4e79f7 100644 --- a/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot/README.MD b/spring-boot-modules/spring-boot/README.MD index 217d9e90b2..fb1c20e988 100644 --- a/spring-boot-modules/spring-boot/README.MD +++ b/spring-boot-modules/spring-boot/README.MD @@ -11,9 +11,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) - [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) -- [Using Custom Banners in Spring Boot](https://www.baeldung.com/spring-boot-custom-banners) - [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) -- [Create a Custom FailureAnalyzer with Spring Boot](https://www.baeldung.com/spring-boot-failure-analyzer) - [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) - [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) - [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) @@ -22,12 +20,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql) - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) - [An Introduction to Kong](https://www.baeldung.com/kong) -- [Spring Boot: Customize Whitelabel Error Page](https://www.baeldung.com/spring-boot-custom-error-page) - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) - [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) -- [How to Define a Spring Boot Filter?](https://www.baeldung.com/spring-boot-add-filter) -- [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) -- [Guide to the Favicon in Spring Boot](https://www.baeldung.com/spring-boot-favicon) - [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) - [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) - [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) +- [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java similarity index 93% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/Application.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java index c1b6558b26..cb0d0c1532 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/Application.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.boot; +package com.baeldung.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java similarity index 89% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java index 92a6ed7ab0..928928c9a5 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.config; +package com.baeldung.boot.config; import java.util.Properties; @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.boot.boottest", "org.baeldung.repository" }) +@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.boot.boottest", "com.baeldung.repository" }) @PropertySource("classpath:persistence-generic-entity.properties") @EnableTransactionManagement public class H2JpaConfig { @@ -41,7 +41,7 @@ public class H2JpaConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.boot.domain", "org.baeldung.boot.model", "org.baeldung.boot.boottest", "org.baeldung.model" }); + em.setPackagesToScan(new String[] { "com.baeldung.boot.domain", "com.baeldung.boot.model", "com.baeldung.boot.boottest", "com.baeldung.model" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java similarity index 71% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java index 9554facb12..b23c910a04 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.config; +package com.baeldung.boot.config; -import org.baeldung.boot.converter.StringToEmployeeConverter; -import org.baeldung.boot.converter.StringToEnumConverterFactory; -import org.baeldung.boot.converter.GenericBigDecimalConverter; +import com.baeldung.boot.converter.StringToEmployeeConverter; +import com.baeldung.boot.converter.StringToEnumConverterFactory; +import com.baeldung.boot.converter.GenericBigDecimalConverter; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java index 34ad11254c..80c75aa8b5 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.controller.servlet; +package com.baeldung.boot.controller.servlet; import java.io.IOException; import java.io.PrintWriter; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java index 91547683c6..f276f94b7c 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.controller.servlet; +package com.baeldung.boot.controller.servlet; import java.io.IOException; import java.io.PrintWriter; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java index 8add28fc2d..fc73cfee5f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.converter; +package com.baeldung.boot.converter; import com.google.common.collect.ImmutableSet; import org.springframework.core.convert.TypeDescriptor; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java similarity index 90% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java index 1bf75b38f0..ac635532ea 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.converter; +package com.baeldung.boot.converter; import org.springframework.core.convert.converter.Converter; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java index ddb2cd2b08..a2dce11a6a 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.converter; +package com.baeldung.boot.converter; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java index 27bad4c387..260b1c734b 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.converter.controller; +package com.baeldung.boot.converter.controller; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java similarity index 54% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java index dcba064e8c..7717294996 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.domain; +package com.baeldung.boot.domain; public enum Modes { diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java similarity index 93% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java index df0e3ec0b2..373ae8f745 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java @@ -1,4 +1,4 @@ -package org.baeldung.common.error; +package com.baeldung.common.error; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java index 774cf1b970..3f51a4ab69 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java @@ -1,4 +1,4 @@ -package org.baeldung.common.error; +package com.baeldung.common.error; import org.springframework.boot.web.servlet.ServletRegistrationBean; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java similarity index 90% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java index ac5f92e9c9..1e5fbf3ac4 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java @@ -1,4 +1,4 @@ -package org.baeldung.common.error.controller; +package com.baeldung.common.error.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java index d553d44769..be503b1b6c 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java @@ -1,4 +1,4 @@ -package org.baeldung.common.properties; +package com.baeldung.common.properties; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.WebServerFactoryCustomizer; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java index 64853a9941..1db7054f85 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java @@ -1,4 +1,4 @@ -package org.baeldung.common.resources; +package com.baeldung.common.resources; import org.springframework.boot.ExitCodeGenerator; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java index 4a88fcea07..eb091b4695 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.demo; +package com.baeldung.demo; import com.baeldung.graphql.GraphqlConfiguration; import org.springframework.boot.SpringApplication; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java index 645ce2838a..fa3c1dc809 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java index 00fdbfaae4..b6850d587e 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java index 516bff0e8c..7d2e06d4a0 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java similarity index 89% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java index 07765a511c..ff1976cad1 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java index a1639b29cc..156fc571f3 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java similarity index 77% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java index 66943f6461..98a0db67ef 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java @@ -1,7 +1,7 @@ -package org.baeldung.demo.components; +package com.baeldung.demo.components; -import org.baeldung.demo.model.Foo; -import org.baeldung.demo.repository.FooRepository; +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.repository.FooRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java similarity index 85% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java index 51dd7bbd44..276802d0b9 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.exceptions; +package com.baeldung.demo.exceptions; public class CommonException extends RuntimeException { diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java similarity index 86% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java index 59796c58f0..8c425d078e 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.exceptions; +package com.baeldung.demo.exceptions; public class FooNotFoundException extends RuntimeException { diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java index e5638cfd3d..796bcca11b 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.model; +package com.baeldung.demo.model; import java.io.Serializable; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java similarity index 70% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java index c04e0c7438..ed27ac23bc 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.demo.repository; +package com.baeldung.demo.repository; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; import org.springframework.data.jpa.repository.JpaRepository; public interface FooRepository extends JpaRepository { diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java similarity index 85% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java index c28dcde1a7..c72c52fa3e 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java @@ -1,7 +1,7 @@ -package org.baeldung.demo.service; +package com.baeldung.demo.service; -import org.baeldung.demo.components.FooService; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.components.FooService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java similarity index 89% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java index 34b50a2c0a..c316cabda5 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java @@ -1,9 +1,9 @@ -package org.baeldung.endpoints.info; +package com.baeldung.endpoints.info; import java.util.HashMap; import java.util.Map; -import org.baeldung.repository.UserRepository; +import com.baeldung.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java similarity index 78% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java index a203659d63..383932524f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java @@ -1,9 +1,9 @@ -package org.baeldung.main; +package com.baeldung.main; -import org.baeldung.boot.controller.servlet.HelloWorldServlet; -import org.baeldung.boot.controller.servlet.SpringHelloWorldServlet; -import org.baeldung.common.error.SpringHelloServletRegistrationBean; -import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator; +import com.baeldung.boot.controller.servlet.HelloWorldServlet; +import com.baeldung.boot.controller.servlet.SpringHelloWorldServlet; +import com.baeldung.common.error.SpringHelloServletRegistrationBean; +import com.baeldung.common.resources.ExecutorServiceExitCodeGenerator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -18,7 +18,7 @@ import java.util.concurrent.Executors; @RestController @EnableAutoConfiguration -@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config" }) +@ComponentScan({ "com.baeldung.common.error", "com.baeldung.common.error.controller", "com.baeldung.common.properties", "com.baeldung.common.resources", "com.baeldung.endpoints", "com.baeldung.service", "com.baeldung.monitor.jmx", "com.baeldung.boot.config" }) public class SpringBootApplication { private static ApplicationContext applicationContext; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/model/User.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/model/User.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java index eb886338a0..cc5f27f38c 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/model/User.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.model; +package com.baeldung.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java similarity index 98% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java index 752664cd5d..4dd863fb17 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.repository; +package com.baeldung.repository; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java similarity index 87% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/Application.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java index 354c64c258..de4ca5998e 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/Application.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java @@ -1,6 +1,6 @@ -package org.baeldung.session.exception; +package com.baeldung.session.exception; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java similarity index 50% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java index ce7bbfe57b..5e748973ed 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.session.exception.repository; +package com.baeldung.session.exception.repository; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; public interface FooRepository { diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java similarity index 88% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java index 607bae83ba..a304373d6c 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java @@ -1,8 +1,8 @@ -package org.baeldung.session.exception.repository; +package com.baeldung.session.exception.repository; import javax.persistence.EntityManagerFactory; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/AppStartupRunner.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/AppStartupRunner.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java index d491bdb42c..0495473704 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/AppStartupRunner.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/CommandLineAppStartupRunner.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/CommandLineAppStartupRunner.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java index 6a7be59c21..48c5225cf1 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/CommandLineAppStartupRunner.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties b/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties index 6ffcfbaf52..270e86d443 100644 --- a/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties +++ b/spring-boot-modules/spring-boot/src/main/resources/application-errorhandling.properties @@ -1,10 +1,4 @@ #server server.port=9000 server.servlet-path=/ -server.context-path=/ -#server.error.whitelabel.enabled=false - -#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration - -#for Spring Boot 2.0+ -#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration \ No newline at end of file +server.context-path=/ \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/application.properties b/spring-boot-modules/spring-boot/src/main/resources/application.properties index 7de79da574..44649fc1c0 100644 --- a/spring-boot-modules/spring-boot/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot/src/main/resources/application.properties @@ -33,12 +33,4 @@ logging.level.org.springframework=INFO servlet.name=dispatcherExample servlet.mapping=/dispatcherExampleURL -#spring.banner.charset=UTF-8 -#spring.banner.location=classpath:banner.txt -#spring.banner.image.location=classpath:banner.gif -#spring.banner.image.width= //TODO -#spring.banner.image.height= //TODO -#spring.banner.image.margin= //TODO -#spring.banner.image.invert= //TODO - contactInfoType=email \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/error-404.html b/spring-boot-modules/spring-boot/src/main/resources/templates/error-404.html deleted file mode 100644 index cf68032596..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/error-404.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - -
-
-

Sorry, we couldn't find the page you were looking for.

-

Go Home

-
- - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/error-500.html b/spring-boot-modules/spring-boot/src/main/resources/templates/error-500.html deleted file mode 100644 index 5ddf458229..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/templates/error-500.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - -
-
-

Sorry, something went wrong!

- -

We're fixing it.

-

Go Home

-
- - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java similarity index 85% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java index 5e351157c8..462291e0ac 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.boot; +package com.baeldung.boot; -import org.baeldung.session.exception.Application; +import com.baeldung.session.exception.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java similarity index 87% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java index 0541da3199..aaf4f1f780 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.boot; +package com.baeldung.boot; -import org.baeldung.demo.DemoApplication; +import com.baeldung.demo.DemoApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java similarity index 82% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java index c32e36d7e3..1772739d20 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.DemoApplicationIntegrationTest; -import org.baeldung.demo.model.Foo; -import org.baeldung.demo.repository.FooRepository; +import com.baeldung.boot.DemoApplicationIntegrationTest; +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.repository.FooRepository; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java similarity index 81% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java index b22282e896..2fe072bb67 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.DemoApplicationIntegrationTest; -import org.baeldung.demo.model.Foo; -import org.baeldung.demo.repository.FooRepository; +import com.baeldung.boot.DemoApplicationIntegrationTest; +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.repository.FooRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java similarity index 78% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java index 5c8d10223b..2e3326e6b1 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.ApplicationIntegrationTest; -import org.baeldung.demo.model.Foo; -import org.baeldung.session.exception.repository.FooRepository; +import com.baeldung.boot.ApplicationIntegrationTest; +import com.baeldung.demo.model.Foo; +import com.baeldung.session.exception.repository.FooRepository; import org.hibernate.HibernateException; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java index bd1ae2c8fa..4619964783 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java @@ -1,9 +1,9 @@ -package org.baeldung.converter; +package com.baeldung.converter; import com.baeldung.toggle.Employee; -import org.baeldung.boot.Application; -import org.baeldung.boot.domain.Modes; +import com.baeldung.boot.Application; +import com.baeldung.boot.domain.Modes; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java index 2afda7565a..52dc542ebf 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.converter.controller; +package com.baeldung.converter.controller; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,7 +14,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.boot.Application; +import com.baeldung.boot.Application; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = Application.class) diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java similarity index 93% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java index 2d70583a54..962abf0fa3 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java @@ -1,8 +1,5 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; -import org.baeldung.demo.boottest.Employee; -import org.baeldung.demo.boottest.EmployeeRestController; -import org.baeldung.demo.boottest.EmployeeService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java index 3042f95a46..164887886b 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java @@ -1,7 +1,7 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; -import org.baeldung.demo.boottest.Employee; -import org.baeldung.demo.boottest.EmployeeRepository; +import com.baeldung.demo.boottest.Employee; +import com.baeldung.demo.boottest.EmployeeRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java similarity index 97% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java index a4b35889d6..327e9f9d56 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; @@ -14,7 +14,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.io.IOException; import java.util.List; -import org.baeldung.demo.DemoApplication; +import com.baeldung.demo.DemoApplication; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java index df28111a57..88f2830a2b 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import static org.assertj.core.api.Assertions.assertThat; @@ -6,6 +6,10 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; +import com.baeldung.demo.boottest.Employee; +import com.baeldung.demo.boottest.EmployeeRepository; +import com.baeldung.demo.boottest.EmployeeService; +import com.baeldung.demo.boottest.EmployeeServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java similarity index 91% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java index 7e04f47696..3fcd709f7c 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java similarity index 92% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java index ea7f118967..a1318949f3 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java @@ -1,7 +1,8 @@ -package org.baeldung.repository; +package com.baeldung.repository; -import org.baeldung.boot.config.H2JpaConfig; -import org.baeldung.model.User; +import com.baeldung.boot.config.H2JpaConfig; +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json b/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json new file mode 100644 index 0000000000..f19bc1febb --- /dev/null +++ b/spring-boot-modules/spring-boot/src/test/resources/GraphQL collection.postman_collection.json @@ -0,0 +1,169 @@ +{ + "info": { + "_postman_id": "910d9690-f629-4491-bbbd-adb30982a386", + "name": "GraphQL collection", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "mutations", + "item": [ + { + "name": "writePost", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "mutation writePost ($title: String!, $text: String!, $category: String) {\n writePost (title: $title, text: $text, category: $category) {\n id\n title\n text\n category\n }\n}", + "variables": "{\n \"title\": \"\",\n \"text\": \"\",\n \"category\": \"\"\n}" + }, + "options": { + "graphql": {} + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + } + ], + "protocolProfileBehavior": {} + }, + { + "name": "queries", + "item": [ + { + "name": "get recent posts", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "{\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n text\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}", + "variables": "" + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + }, + { + "name": "recentPosts - variables", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { + "query": "query recentPosts ($count: Int, $offset: Int) {\n recentPosts (count: $count, offset: $offset) {\n id\n title\n text\n category\n }\n}", + "variables": "{\n \"count\": 1,\n \"offset\": 0\n}" + }, + "options": { + "graphql": {} + } + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + }, + { + "name": "get recent posts - raw", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/graphql", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "query {\r\n recentPosts(count: 10, offset: 0) {\r\n id\r\n title\r\n category\r\n author {\r\n id\r\n name\r\n thumbnail\r\n }\r\n }\r\n}" + }, + "url": { + "raw": "http://localhost:9090/springbootapp/graphql", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "9090", + "path": [ + "springbootapp", + "graphql" + ] + } + }, + "response": [] + } + ], + "protocolProfileBehavior": {} + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "id": "b54f267b-c450-4f2d-8105-2f23bab4c922", + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "id": "00b575be-03d4-4b29-b137-733ead139638", + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "id": "20a274e5-6d51-40d6-81cb-af9eb115b21b", + "key": "url", + "value": "", + "type": "string" + } + ], + "protocolProfileBehavior": {} +} \ No newline at end of file diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index f78c88d30b..861181c53e 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -4,12 +4,7 @@ This module contains articles about Spring Boot RESTful APIs. ### Relevant Articles -- [HATEOAS for a Spring REST Service](https://www.baeldung.com/rest-api-discoverability-with-spring) - [Versioning a REST API](https://www.baeldung.com/rest-versioning) -- [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) -- [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) -- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) -- [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) ### E-book @@ -25,6 +20,7 @@ These articles are part of the Spring REST E-book: 8. [An Intro to Spring HATEOAS](https://www.baeldung.com/spring-hateoas-tutorial) 9. [REST Pagination in Spring](https://www.baeldung.com/rest-api-pagination-in-spring) 10. [Test a REST API with Java](https://www.baeldung.com/integration-testing-a-rest-api) +11. [HATEOAS for a Spring REST Service](https://www.baeldung.com/rest-api-discoverability-with-spring) NOTE: Since this is a module tied to an e-book, it should not be moved or used to store the code for any further article. diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index 10dacf99e8..a8500d50f2 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -79,6 +79,11 @@ modelmapper ${modelmapper.version}
+ + net.bytebuddy + byte-buddy + ${byte-buddy.version} +
diff --git a/spring-caching/pom.xml b/spring-caching/pom.xml index c3ededbd14..f56d3cf328 100644 --- a/spring-caching/pom.xml +++ b/spring-caching/pom.xml @@ -1,45 +1,67 @@ - - 4.0.0 - spring-caching - 0.1-SNAPSHOT - spring-caching - war + + 4.0.0 + spring-caching + 0.1-SNAPSHOT + spring-caching + war - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + - - - org.springframework - spring-context - - - org.springframework - spring-web - - - org.springframework - spring-webmvc - - - org.ehcache - ehcache - - - org.springframework - spring-test - test - - + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework + spring-context + + + org.springframework.boot + spring-boot-starter-cache + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.ehcache + ehcache + + + org.springframework + spring-test + test + + + com.github.ben-manes.caffeine + caffeine + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-jdbc + + + + + 3.5.2 + - - 3.5.2 - - \ No newline at end of file diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java b/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java new file mode 100644 index 0000000000..afa1d0ec99 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java @@ -0,0 +1,18 @@ +package com.baeldung.caching.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; +//import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@EnableCaching +//to run any module like ehcache,caching or multiplecachemanager in local machine +//add it's package for ComponentScan like below +//@ComponentScan("com.baeldung.multiplecachemanager") +public class CacheApplication { + + public static void main(String[] args) { + SpringApplication.run(CacheApplication.class, args); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java b/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java new file mode 100644 index 0000000000..a76a01caae --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java @@ -0,0 +1,24 @@ +package com.baeldung.caching.boot; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.stereotype.Component; + +import static java.util.Arrays.asList; + +@Component +public class SimpleCacheCustomizer implements CacheManagerCustomizer { + + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleCacheCustomizer.class); + + static final String USERS_CACHE = "users"; + static final String TRANSACTIONS_CACHE = "transactions"; + + @Override + public void customize(ConcurrentMapCacheManager cacheManager) { + LOGGER.info("Customizing Cache Manager"); + cacheManager.setCacheNames(asList(USERS_CACHE, TRANSACTIONS_CACHE)); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java new file mode 100644 index 0000000000..3da4c23e28 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java @@ -0,0 +1,28 @@ +package com.baeldung.multiplecachemanager.bo; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import com.baeldung.multiplecachemanager.entity.Customer; +import com.baeldung.multiplecachemanager.entity.Order; +import com.baeldung.multiplecachemanager.repository.CustomerDetailRepository; + +@Component +public class CustomerDetailBO { + + @Autowired + private CustomerDetailRepository customerDetailRepository; + + @Cacheable(cacheNames = "customers") + public Customer getCustomerDetail(Integer customerId) { + return customerDetailRepository.getCustomerDetail(customerId); + } + + @Cacheable(cacheNames = "customerOrders", cacheManager = "alternateCacheManager") + public List getCustomerOrders(Integer customerId) { + return customerDetailRepository.getCustomerOrders(customerId); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java new file mode 100644 index 0000000000..390881167f --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java @@ -0,0 +1,25 @@ +package com.baeldung.multiplecachemanager.bo; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import com.baeldung.multiplecachemanager.entity.Order; +import com.baeldung.multiplecachemanager.repository.OrderDetailRepository; + +@Component +public class OrderDetailBO { + + @Autowired + private OrderDetailRepository orderDetailRepository; + + @Cacheable(cacheNames = "orders", cacheResolver = "cacheResolver") + public Order getOrderDetail(Integer orderId) { + return orderDetailRepository.getOrderDetail(orderId); + } + + @Cacheable(cacheNames = "orderprice", cacheResolver = "cacheResolver") + public double getOrderPrice(Integer orderId) { + return orderDetailRepository.getOrderPrice(orderId); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java new file mode 100644 index 0000000000..247a9b596b --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java @@ -0,0 +1,40 @@ +package com.baeldung.multiplecachemanager.config; + +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.caffeine.CaffeineCacheManager; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.cache.interceptor.CacheResolver; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +//import org.springframework.context.annotation.Primary; + +import com.github.benmanes.caffeine.cache.Caffeine; + +@Configuration +@EnableCaching +public class MultipleCacheManagerConfig extends CachingConfigurerSupport { + + @Bean + //@Primary + public CacheManager cacheManager() { + CaffeineCacheManager cacheManager = new CaffeineCacheManager("customers", "orders"); + cacheManager.setCaffeine(Caffeine.newBuilder() + .initialCapacity(200) + .maximumSize(500) + .weakKeys() + .recordStats()); + return cacheManager; + } + + @Bean + public CacheManager alternateCacheManager() { + return new ConcurrentMapCacheManager("customerOrders", "orderprice"); + } + + @Bean + public CacheResolver cacheResolver() { + return new MultipleCacheResolver(alternateCacheManager(), cacheManager()); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java new file mode 100644 index 0000000000..1bd869d98e --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java @@ -0,0 +1,38 @@ +package com.baeldung.multiplecachemanager.config; + +import java.util.ArrayList; +import java.util.Collection; + +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.interceptor.CacheOperationInvocationContext; +import org.springframework.cache.interceptor.CacheResolver; + +public class MultipleCacheResolver implements CacheResolver { + + private final CacheManager simpleCacheManager; + + private final CacheManager caffeineCacheManager; + + private static final String ORDER_CACHE = "orders"; + + private static final String ORDER_PRICE_CACHE = "orderprice"; + + public MultipleCacheResolver(CacheManager simpleCacheManager, CacheManager caffeineCacheManager) { + this.simpleCacheManager = simpleCacheManager; + this.caffeineCacheManager = caffeineCacheManager; + + } + + @Override + public Collection resolveCaches(CacheOperationInvocationContext context) { + Collection caches = new ArrayList(); + if ("getOrderDetail".equals(context.getMethod() + .getName())) { + caches.add(caffeineCacheManager.getCache(ORDER_CACHE)); + } else { + caches.add(simpleCacheManager.getCache(ORDER_PRICE_CACHE)); + } + return caches; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java new file mode 100644 index 0000000000..17a73bb27a --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java @@ -0,0 +1,43 @@ +package com.baeldung.multiplecachemanager.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.multiplecachemanager.bo.CustomerDetailBO; +import com.baeldung.multiplecachemanager.bo.OrderDetailBO; +import com.baeldung.multiplecachemanager.entity.Customer; +import com.baeldung.multiplecachemanager.entity.Order; + +@RestController +public class MultipleCacheManagerController { + + @Autowired + private CustomerDetailBO customerDetailBO; + + @Autowired + private OrderDetailBO orderDetailBO; + + @GetMapping(value = "/getCustomer/{customerid}") + public Customer getCustomer(@PathVariable Integer customerid) { + return customerDetailBO.getCustomerDetail(customerid); + } + + @GetMapping(value = "/getCustomerOrders/{customerid}") + public List getCustomerOrders(@PathVariable Integer customerid) { + return customerDetailBO.getCustomerOrders(customerid); + } + + @GetMapping(value = "/getOrder/{orderid}") + public Order getOrder(@PathVariable Integer orderid) { + return orderDetailBO.getOrderDetail(orderid); + } + + @GetMapping(value = "/getOrderPrice/{orderid}") + public double getOrderPrice(@PathVariable Integer orderid) { + return orderDetailBO.getOrderPrice(orderid); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java new file mode 100644 index 0000000000..cfae15f4e9 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java @@ -0,0 +1,24 @@ +package com.baeldung.multiplecachemanager.entity; + +public class Customer { + + private int customerId; + + private String customerName; + + public int getCustomerId() { + return customerId; + } + + public void setCustomerId(int customerId) { + this.customerId = customerId; + } + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java new file mode 100644 index 0000000000..4131464981 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java @@ -0,0 +1,34 @@ +package com.baeldung.multiplecachemanager.entity; + +public class Item { + + private int itemId; + + private String itemDesc; + + private double itemPrice; + + public int getItemId() { + return itemId; + } + + public void setItemId(int itemId) { + this.itemId = itemId; + } + + public String getItemDesc() { + return itemDesc; + } + + public void setItemDesc(String itemDesc) { + this.itemDesc = itemDesc; + } + + public double getItemPrice() { + return itemPrice; + } + + public void setItemPrice(double itemPrice) { + this.itemPrice = itemPrice; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java new file mode 100644 index 0000000000..15da60d6ea --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java @@ -0,0 +1,44 @@ +package com.baeldung.multiplecachemanager.entity; + +public class Order { + + private int orderId; + + private int itemId; + + private int quantity; + + private int customerId; + + public int getOrderId() { + return orderId; + } + + public void setOrderId(int orderId) { + this.orderId = orderId; + } + + public int getItemId() { + return itemId; + } + + public void setItemId(int itemId) { + this.itemId = itemId; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public int getCustomerId() { + return customerId; + } + + public void setCustomerId(int customerId) { + this.customerId = customerId; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java new file mode 100644 index 0000000000..aab011427d --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java @@ -0,0 +1,49 @@ +package com.baeldung.multiplecachemanager.repository; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.stereotype.Repository; + +import com.baeldung.multiplecachemanager.entity.Customer; +import com.baeldung.multiplecachemanager.entity.Order; + +@Repository +public class CustomerDetailRepository { + + @Autowired + private JdbcTemplate jdbcTemplate; + + public Customer getCustomerDetail(Integer customerId) { + String customerQuery = "select * from customer where customerid = ? "; + Customer customer = new Customer(); + jdbcTemplate.query(customerQuery, new Object[] { customerId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + customer.setCustomerId(rs.getInt("customerid")); + customer.setCustomerName(rs.getString("customername")); + } + }); + return customer; + } + + public List getCustomerOrders(Integer customerId) { + String customerOrderQuery = "select * from orderdetail where customerid = ? "; + List orders = new ArrayList(); + jdbcTemplate.query(customerOrderQuery, new Object[] { customerId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + Order order = new Order(); + order.setCustomerId(rs.getInt("customerid")); + order.setItemId(rs.getInt("orderid")); + order.setOrderId(rs.getInt("orderid")); + order.setQuantity(rs.getInt("quantity")); + orders.add(order); + } + }); + return orders; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java new file mode 100644 index 0000000000..58c0968e48 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java @@ -0,0 +1,53 @@ +package com.baeldung.multiplecachemanager.repository; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.stereotype.Repository; + +import com.baeldung.multiplecachemanager.entity.Item; +import com.baeldung.multiplecachemanager.entity.Order; + +@Repository +public class OrderDetailRepository { + + @Autowired + private JdbcTemplate jdbcTemplate; + + public Order getOrderDetail(Integer orderId) { + String orderDetailQuery = "select * from orderdetail where orderid = ? "; + Order order = new Order(); + jdbcTemplate.query(orderDetailQuery, new Object[] { orderId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + order.setCustomerId(rs.getInt("customerid")); + order.setOrderId(rs.getInt("orderid")); + order.setItemId(rs.getInt("itemid")); + order.setQuantity(rs.getInt("quantity")); + } + }); + return order; + } + + public double getOrderPrice(Integer orderId) { + + String orderItemJoinQuery = "select * from ( select * from orderdetail where orderid = ? ) o left join item on o.itemid = ITEM.itemid"; + Order order = new Order(); + Item item = new Item(); + + jdbcTemplate.query(orderItemJoinQuery, new Object[] { orderId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + order.setCustomerId(rs.getInt("customerid")); + order.setOrderId(rs.getInt("orderid")); + order.setItemId(rs.getInt("itemid")); + order.setQuantity(rs.getInt("quantity")); + item.setItemDesc("itemdesc"); + item.setItemId(rs.getInt("itemid")); + item.setItemPrice(rs.getDouble("price")); + } + }); + return order.getQuantity() * item.getItemPrice(); + } +} diff --git a/spring-caching/src/main/resources/application.properties b/spring-caching/src/main/resources/application.properties new file mode 100644 index 0000000000..ee7b5e62c0 --- /dev/null +++ b/spring-caching/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= + +# Enabling H2 Console +spring.h2.console.enabled=true +spring.h2.console.path=/h2 diff --git a/spring-caching/src/main/resources/data.sql b/spring-caching/src/main/resources/data.sql new file mode 100644 index 0000000000..e4165ae71f --- /dev/null +++ b/spring-caching/src/main/resources/data.sql @@ -0,0 +1,7 @@ +INSERT INTO CUSTOMER VALUES(1001,'BAELDUNG'); + +INSERT INTO ITEM VALUES(10001,'ITEM1',50.0); +INSERT INTO ITEM VALUES(10002,'ITEM2',100.0); + +INSERT INTO ORDERDETAIL VALUES(300001,1001,10001,2); +INSERT INTO ORDERDETAIL VALUES(300002,1001,10002,5); \ No newline at end of file diff --git a/spring-caching/src/main/resources/schema.sql b/spring-caching/src/main/resources/schema.sql new file mode 100644 index 0000000000..5862499bc0 --- /dev/null +++ b/spring-caching/src/main/resources/schema.sql @@ -0,0 +1,19 @@ +CREATE TABLE CUSTOMER( + CUSTOMERID INT PRIMARY KEY, + CUSTOMERNAME VARCHAR(250) NOT NULL +); + +CREATE TABLE ITEM( +ITEMID INT PRIMARY KEY, +ITEMDESC VARCHAR(250), +PRICE DOUBLE +); + +CREATE TABLE ORDERDETAIL( +ORDERID INT PRIMARY KEY, +CUSTOMERID INT NOT NULL, +ITEMID INT NOT NULL, +QUANTITY INT, +FOREIGN KEY (customerid) references CUSTOMER(customerid), +FOREIGN KEY (itemid) references ITEM(itemid) +); \ No newline at end of file diff --git a/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java b/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java new file mode 100644 index 0000000000..56a4bd4745 --- /dev/null +++ b/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.caching.boot; + +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.cache.CacheManager; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SimpleCacheCustomizerIntegrationTest { + + @Autowired + private CacheManager cacheManager; + + @Test + public void givenCacheManagerCustomizerWhenBootstrappedThenCacheManagerCustomized() { + assertThat(cacheManager.getCacheNames()) + .containsOnly(SimpleCacheCustomizer.USERS_CACHE, SimpleCacheCustomizer.TRANSACTIONS_CACHE); + } +} \ No newline at end of file diff --git a/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationUnitTest.java b/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationUnitTest.java new file mode 100644 index 0000000000..e02e5da246 --- /dev/null +++ b/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.multiplecachemanager; + +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.caffeine.CaffeineCache; +import org.springframework.util.Assert; + +import com.baeldung.multiplecachemanager.bo.OrderDetailBO; +import com.baeldung.multiplecachemanager.entity.Order; +import com.baeldung.multiplecachemanager.repository.OrderDetailRepository; + +@SpringBootApplication +@SpringBootTest +public class MultipleCacheManagerIntegrationUnitTest { + + @MockBean + private OrderDetailRepository orderDetailRepository; + + @Autowired + private OrderDetailBO orderDetailBO; + + @Autowired + private CacheManager cacheManager; + + @Autowired + private CacheManager alternateCacheManager; + + @Test + public void givenCacheResolverIsConfigured_whenCallGetOrderDetail_thenDataShouldBeInCaffieneCacheManager() { + Integer key = 30001; + cacheManager.getCache("orders") + .evict(key); + Order order = new Order(); + order.setCustomerId(1001); + order.setItemId(10001); + order.setOrderId(30001); + order.setQuantity(2); + Mockito.when(orderDetailRepository.getOrderDetail(key)) + .thenReturn(order); + orderDetailBO.getOrderDetail(key); + org.springframework.cache.caffeine.CaffeineCache cache = (CaffeineCache) cacheManager.getCache("orders"); + Assert.notNull(cache.get(key) + .get(), "caffieneCache should have had the data"); + } + + @Test + public void givenCacheResolverIsConfigured_whenCallGetOrderPrice_thenDataShouldBeInAlternateCacheManager() { + Integer key = 30001; + alternateCacheManager.getCache("orderprice") + .evict(key); + Mockito.when(orderDetailRepository.getOrderPrice(key)) + .thenReturn(500.0); + orderDetailBO.getOrderPrice(key); + Cache cache = alternateCacheManager.getCache("orderprice"); + Assert.notNull(cache.get(key) + .get(), "alternateCache should have had the data"); + } +} diff --git a/spring-cloud/spring-cloud-circuit-breaker/README.md b/spring-cloud/spring-cloud-circuit-breaker/README.md new file mode 100644 index 0000000000..040eb0ccee --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/README.md @@ -0,0 +1,5 @@ +## Spring Cloud Circuit Breaker + +This module contains articles about Spring Cloud Circuit Breaker + +### Relevant Articles: diff --git a/spring-cloud/spring-cloud-circuit-breaker/pom.xml b/spring-cloud/spring-cloud-circuit-breaker/pom.xml new file mode 100644 index 0000000000..188fc4bf8e --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + spring-cloud-circuit-breaker + spring-cloud-gateway + jar + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/libs-snapshot + + true + + + false + + + + + + + + org.springframework.boot + spring-boot-dependencies + 2.2.4.RELEASE + pom + import + + + + + + + org.springframework.cloud + spring-cloud-starter-circuitbreaker-resilience4j + 1.0.2.RELEASE + + + org.springframework.boot + spring-boot-starter-web + + + + diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java new file mode 100644 index 0000000000..67163c8c9a --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java @@ -0,0 +1,40 @@ +package com.baeldung.circuitbreaker; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.circuitbreaker.CircuitBreaker; +import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.nio.file.Files; +import java.nio.file.Paths; + +@Service +public class AlbumService { + + private static final Logger LOGGER = LoggerFactory.getLogger(AlbumService.class); + + @Autowired + private CircuitBreakerFactory circuitBreakerFactory; + + private RestTemplate restTemplate = new RestTemplate(); + + public String getAlbumList() { + CircuitBreaker circuitBreaker = circuitBreakerFactory.create("circuitbreaker"); + String url = "https://jsonplaceholder.typicode.com/albums"; + + return circuitBreaker.run(() -> restTemplate.getForObject(url, String.class), throwable -> getDefaultAlbumList()); + } + + private String getDefaultAlbumList() { + try { + return new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("fallback-album-list.json").toURI()))); + } catch (Exception e) { + LOGGER.error("error occurred while reading the file", e); + } + return null; + } + +} diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/Controller.java b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/Controller.java new file mode 100644 index 0000000000..10f7c57a7a --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/Controller.java @@ -0,0 +1,18 @@ +package com.baeldung.circuitbreaker; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class Controller { + + @Autowired + private AlbumService service; + + @GetMapping("/albums") + public String albums() { + return service.getAlbumList(); + } + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/SpringApp.java b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/SpringApp.java new file mode 100644 index 0000000000..f891e7693f --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/SpringApp.java @@ -0,0 +1,71 @@ +package com.baeldung.circuitbreaker; + +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; +import io.github.resilience4j.timelimiter.TimeLimiterConfig; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory; +import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder; +import org.springframework.cloud.client.circuitbreaker.Customizer; +import org.springframework.context.annotation.Bean; + +import java.time.Duration; + +@SpringBootApplication +public class SpringApp { + + public static void main(String[] args) { + SpringApplication.run(SpringApp.class, args); + } + + @Bean + public Customizer globalCustomConfiguration() { + TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() + .timeoutDuration(Duration.ofSeconds(4)) + .build(); + CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofMillis(1000)) + .slidingWindowSize(2) + .build(); + + return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id) + .timeLimiterConfig(timeLimiterConfig) + .circuitBreakerConfig(circuitBreakerConfig) + .build()); + } + + @Bean + public Customizer specificCustomConfiguration1() { + + TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() + .timeoutDuration(Duration.ofSeconds(4)) + .build(); + CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofMillis(1000)) + .slidingWindowSize(2) + .build(); + + return factory -> factory.configure(builder -> builder.circuitBreakerConfig(circuitBreakerConfig) + .timeLimiterConfig(timeLimiterConfig).build(), "circuitBreaker"); + } + + @Bean + public Customizer specificCustomConfiguration2() { + + TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() + .timeoutDuration(Duration.ofSeconds(4)) + .build(); + CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofMillis(1000)) + .slidingWindowSize(2) + .build(); + + return factory -> factory.configure(builder -> builder.circuitBreakerConfig(circuitBreakerConfig) + .timeLimiterConfig(timeLimiterConfig).build(), + "circuitBreaker1", "circuitBreaker2", "circuitBreaker3"); + } + +} diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/resources/fallback-album-list.json b/spring-cloud/spring-cloud-circuit-breaker/src/main/resources/fallback-album-list.json new file mode 100644 index 0000000000..001df7610a --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/resources/fallback-album-list.json @@ -0,0 +1,12 @@ +[ + { + "userId": 1, + "id": 1, + "title": "quidem molestiae enim" + }, + { + "userId": 1, + "id": 2, + "title": "sunt qui excepturi placeat culpa" + } +] \ No newline at end of file diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml index e20fe338c1..df529d7fb1 100644 --- a/spring-cloud/spring-cloud-openfeign/pom.xml +++ b/spring-cloud/spring-cloud-openfeign/pom.xml @@ -3,9 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.cloud - openfeign + spring-cloud-openfeign 0.0.1-SNAPSHOT - openfeign + spring-cloud-openfeign OpenFeign project for Spring Boot diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml index 441924f1d3..93255959e4 100644 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - SpringCloudTaskSink - SpringCloudTaskSink + springcloudtasksink + springcloudtasksink jar Demo project for Spring Boot diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml index c13aeb890e..8643309645 100644 --- a/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-post-filter/pom.xml @@ -1,7 +1,8 @@ - + spring-cloud-zuul com.baeldung.spring.cloud @@ -10,10 +11,6 @@ 4.0.0 spring-zuul-post-filter - - Hoxton.SR1 - - org.springframework.cloud @@ -21,5 +18,8 @@ + + Hoxton.SR1 + \ No newline at end of file diff --git a/spring-core-2/README.md b/spring-core-2/README.md index 1fb591f693..947b816db8 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -7,7 +7,6 @@ This module contains articles about core Spring functionality - [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire) - [Spring Profiles](http://www.baeldung.com/spring-profiles) - [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) -- [Running Setup Data on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) - [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope) - [@Order in Spring](http://www.baeldung.com/spring-order) @@ -15,6 +14,4 @@ This module contains articles about core Spring functionality - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) -- [Guide to the Spring BeanFactory](https://www.baeldung.com/spring-beanfactory) -- [Reading HttpServletRequest Multiple Times in Spring](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times) - More articles: [[<-- prev]](/spring-core)[[next -->]](/spring-core-3) diff --git a/spring-core-2/src/main/java/com/baeldung/spring/config/MainWebAppInitializer.java b/spring-core-2/src/main/java/com/baeldung/spring/config/MyWebApplicationInitializer.java similarity index 81% rename from spring-core-2/src/main/java/com/baeldung/spring/config/MainWebAppInitializer.java rename to spring-core-2/src/main/java/com/baeldung/spring/config/MyWebApplicationInitializer.java index dd396a653f..034386ade9 100644 --- a/spring-core-2/src/main/java/com/baeldung/spring/config/MainWebAppInitializer.java +++ b/spring-core-2/src/main/java/com/baeldung/spring/config/MyWebApplicationInitializer.java @@ -6,15 +6,12 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; -import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class MainWebAppInitializer implements WebApplicationInitializer +public class MyWebApplicationInitializer implements WebApplicationInitializer { /** @@ -22,7 +19,7 @@ public class MainWebAppInitializer implements WebApplicationInitializer */ @Override public void onStartup(final ServletContext sc) throws ServletException { - System.out.println("MainWebAppInitializer.onStartup()"); + System.out.println("MyWebApplicationInitializer.onStartup()"); // Create the 'root' Spring application context final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); diff --git a/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java index 60e9499d4b..1380e34ebd 100644 --- a/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java @@ -16,7 +16,7 @@ public class SpringProfilesWithMavenPropertiesIntegrationTest { DatasourceConfig datasourceConfig; @Test - public void testSpringProfiles() { + public void setupDatasource() { Assert.assertTrue(datasourceConfig instanceof DevDatasourceConfig); } } \ No newline at end of file diff --git a/spring-core-3/README.md b/spring-core-3/README.md index b2c4f694a8..6c210b23ef 100644 --- a/spring-core-3/README.md +++ b/spring-core-3/README.md @@ -10,4 +10,5 @@ This module contains articles about core Spring functionality - [Spring – Injecting Collections](https://www.baeldung.com/spring-injecting-collections) - [Design Patterns in the Spring Framework](https://www.baeldung.com/spring-framework-design-patterns) - [Injecting a Value in a Static Field in Spring](https://www.baeldung.com/spring-inject-static-field) +- [Difference Between BeanFactory and ApplicationContext](https://www.baeldung.com/spring-beanfactory-vs-applicationcontext) - More articles: [[<-- prev]](/spring-core-2) diff --git a/spring-core-3/src/main/java/com/baeldung/factorybean/README.md b/spring-core-3/src/main/java/com/baeldung/factorybean/README.md deleted file mode 100644 index 13f9f379e0..0000000000 --- a/spring-core-3/src/main/java/com/baeldung/factorybean/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java new file mode 100644 index 0000000000..65e249b15b --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java @@ -0,0 +1,21 @@ +package com.baeldung.ioccontainer.bean; + +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; + +public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor { + private static boolean isBeanFactoryPostProcessorRegistered = false; + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory){ + setBeanFactoryPostProcessorRegistered(true); + } + + public static boolean isBeanFactoryPostProcessorRegistered() { + return isBeanFactoryPostProcessorRegistered; + } + + public static void setBeanFactoryPostProcessorRegistered(boolean isBeanFactoryPostProcessorRegistered) { + CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered = isBeanFactoryPostProcessorRegistered; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java new file mode 100644 index 0000000000..6f99a5f0db --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java @@ -0,0 +1,21 @@ +package com.baeldung.ioccontainer.bean; + +import org.springframework.beans.factory.config.BeanPostProcessor; + +public class CustomBeanPostProcessor implements BeanPostProcessor { + private static boolean isBeanPostProcessorRegistered = false; + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName){ + setBeanPostProcessorRegistered(true); + return bean; + } + + public static boolean isBeanPostProcessorRegistered() { + return isBeanPostProcessorRegistered; + } + + public static void setBeanPostProcessorRegistered(boolean isBeanPostProcessorRegistered) { + CustomBeanPostProcessor.isBeanPostProcessorRegistered = isBeanPostProcessorRegistered; + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java new file mode 100644 index 0000000000..404f323b66 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java @@ -0,0 +1,17 @@ +package com.baeldung.ioccontainer.bean; + +public class Student { + private static boolean isBeanInstantiated = false; + + public void postConstruct() { + setBeanInstantiated(true); + } + + public static boolean isBeanInstantiated() { + return isBeanInstantiated; + } + + public static void setBeanInstantiated(boolean isBeanInstantiated) { + Student.isBeanInstantiated = isBeanInstantiated; + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java new file mode 100644 index 0000000000..e9b491813e --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.ioccontainer; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import com.baeldung.ioccontainer.bean.CustomBeanFactoryPostProcessor; +import com.baeldung.ioccontainer.bean.CustomBeanPostProcessor; +import com.baeldung.ioccontainer.bean.Student; + +public class IOCContainerAppUnitTest { + + @BeforeEach + @AfterEach + public void resetInstantiationFlag() { + Student.setBeanInstantiated(false); + CustomBeanPostProcessor.setBeanPostProcessorRegistered(false); + CustomBeanFactoryPostProcessor.setBeanFactoryPostProcessorRegistered(false); + } + + @Test + public void whenBFInitialized_thenStudentNotInitialized() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + BeanFactory factory = new XmlBeanFactory(res); + + assertFalse(Student.isBeanInstantiated()); + } + + @Test + public void whenBFInitialized_thenStudentInitialized() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + BeanFactory factory = new XmlBeanFactory(res); + Student student = (Student) factory.getBean("student"); + + assertTrue(Student.isBeanInstantiated()); + } + + @Test + public void whenAppContInitialized_thenStudentInitialized() { + ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); + + assertTrue(Student.isBeanInstantiated()); + } + + @Test + public void whenBFInitialized_thenBFPProcessorAndBPProcessorNotRegAutomatically() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); + + assertFalse(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + assertFalse(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); + } + + @Test + public void whenBFPostProcessorAndBPProcessorRegisteredManually_thenReturnTrue() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); + + CustomBeanFactoryPostProcessor beanFactoryPostProcessor = new CustomBeanFactoryPostProcessor(); + beanFactoryPostProcessor.postProcessBeanFactory(factory); + assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + + CustomBeanPostProcessor beanPostProcessor = new CustomBeanPostProcessor(); + factory.addBeanPostProcessor(beanPostProcessor); + Student student = (Student) factory.getBean("student"); + assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); + } + + @Test + public void whenAppContInitialized_thenBFPostProcessorAndBPostProcessorRegisteredAutomatically() { + ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); + + assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); + } +} diff --git a/spring-core-3/src/test/resources/ioc-container-difference-example.xml b/spring-core-3/src/test/resources/ioc-container-difference-example.xml new file mode 100644 index 0000000000..e53dc11f89 --- /dev/null +++ b/spring-core-3/src/test/resources/ioc-container-difference-example.xml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file diff --git a/spring-core-4/README.md b/spring-core-4/README.md new file mode 100644 index 0000000000..f882c77179 --- /dev/null +++ b/spring-core-4/README.md @@ -0,0 +1,7 @@ +## Spring Core + +This module contains articles about core Spring functionality + +## Relevant Articles: + +- More articles: [[<-- prev]](/spring-core-3) diff --git a/spring-core-4/pom.xml b/spring-core-4/pom.xml new file mode 100644 index 0000000000..53f7ca6912 --- /dev/null +++ b/spring-core-4/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + spring-core-4 + spring-core-4 + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-test + ${spring.version} + test + + + 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 + ${maven.surefire.version} + + + + + + 2.22.1 + 1.3.2 + 2.2.2.RELEASE + + + \ No newline at end of file diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/Bar.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/Bar.java new file mode 100644 index 0000000000..22ef5b3429 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/Bar.java @@ -0,0 +1,18 @@ +package com.baeldung.factorymethod; + +public class Bar { + + private String name; + + public Bar(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/Foo.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/Foo.java new file mode 100644 index 0000000000..54bd0c9ff4 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/Foo.java @@ -0,0 +1,5 @@ +package com.baeldung.factorymethod; + +public class Foo { + +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java new file mode 100644 index 0000000000..f834b82aee --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceBarFactory.java @@ -0,0 +1,8 @@ +package com.baeldung.factorymethod; + +public class InstanceBarFactory { + + public Bar createInstance(String name) { + return new Bar(name); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java new file mode 100644 index 0000000000..c3125d3339 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/InstanceFooFactory.java @@ -0,0 +1,8 @@ +package com.baeldung.factorymethod; + +public class InstanceFooFactory { + + public Foo createInstance() { + return new Foo(); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java new file mode 100644 index 0000000000..93802819b1 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonBarFactory.java @@ -0,0 +1,11 @@ +package com.baeldung.factorymethod; + +public class SingletonBarFactory { + + private static final Bar INSTANCE = new Bar("unnamed"); + + public static Bar createInstance(String name) { + INSTANCE.setName(name); + return INSTANCE; + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java b/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java new file mode 100644 index 0000000000..77d56cc7f6 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/factorymethod/SingletonFooFactory.java @@ -0,0 +1,10 @@ +package com.baeldung.factorymethod; + +public class SingletonFooFactory { + + private static final Foo INSTANCE = new Foo(); + + public static Foo createInstance() { + return INSTANCE; + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java new file mode 100644 index 0000000000..b5728316e7 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceBarFactoryIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.factorymethod; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +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; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/instance-bar-config.xml") +public class InstanceBarFactoryIntegrationTest { + + @Autowired + private Bar instance; + + @Test + public void givenValidInstanceFactoryConfig_whenCreateInstance_thenNameIsCorrect() { + assertNotNull(instance); + assertEquals("someName", instance.getName()); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java new file mode 100644 index 0000000000..6b1857c2f2 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/factorymethod/InstanceFooFactoryIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.factorymethod; + +import static org.junit.Assert.assertNotNull; + +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; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/instance-foo-config.xml") +public class InstanceFooFactoryIntegrationTest { + + @Autowired + private Foo foo; + + @Test + public void givenValidInstanceFactoryConfig_whenCreateFooInstance_thenInstanceIsNotNull() { + assertNotNull(foo); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java new file mode 100644 index 0000000000..403b46156b --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonBarFactoryIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.factorymethod; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +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; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/static-bar-config.xml") +public class SingletonBarFactoryIntegrationTest { + + @Autowired + private Bar instance; + + @Test + public void givenValidStaticFactoryConfig_whenCreateInstance_thenNameIsCorrect() { + assertNotNull(instance); + assertEquals("someName", instance.getName()); + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java new file mode 100644 index 0000000000..52154b81ab --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/factorymethod/SingletonFooFactoryIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.factorymethod; + +import static org.junit.Assert.assertNotNull; + +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; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/factorymethod/static-foo-config.xml") +public class SingletonFooFactoryIntegrationTest { + + @Autowired + private Foo singleton; + + @Test + public void givenValidStaticFactoryConfig_whenCreateInstance_thenInstanceIsNotNull() { + assertNotNull(singleton); + } +} diff --git a/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml b/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml new file mode 100644 index 0000000000..a4281aee4e --- /dev/null +++ b/spring-core-4/src/test/resources/factorymethod/instance-bar-config.xml @@ -0,0 +1,20 @@ + + + + + + + + + + \ No newline at end of file diff --git a/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml b/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml new file mode 100644 index 0000000000..0f21f06f5a --- /dev/null +++ b/spring-core-4/src/test/resources/factorymethod/instance-foo-config.xml @@ -0,0 +1,18 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml b/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml new file mode 100644 index 0000000000..2cacc293bc --- /dev/null +++ b/spring-core-4/src/test/resources/factorymethod/static-bar-config.xml @@ -0,0 +1,17 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml b/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml new file mode 100644 index 0000000000..ffe1480638 --- /dev/null +++ b/spring-core-4/src/test/resources/factorymethod/static-foo-config.xml @@ -0,0 +1,15 @@ + + + + + + \ No newline at end of file diff --git a/spring-ejb/ejb-beans/pom.xml b/spring-ejb/ejb-beans/pom.xml index eecf8c1d23..c9edfc21f8 100644 --- a/spring-ejb/ejb-beans/pom.xml +++ b/spring-ejb/ejb-beans/pom.xml @@ -121,6 +121,8 @@ 5.2.3.RELEASE 5.10.2 5.13.1 + 2.21.0 + 1.8.5 diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index f3e0b04808..5d2cd7c445 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -28,7 +28,7 @@ - 2.21.0 + 2.24.0 diff --git a/spring-mvc-basics-2/README.md b/spring-mvc-basics-2/README.md index 9d1402a210..e52459bd6e 100644 --- a/spring-mvc-basics-2/README.md +++ b/spring-mvc-basics-2/README.md @@ -9,6 +9,7 @@ This module contains articles about Spring MVC - [Servlet Redirect vs Forward](https://www.baeldung.com/servlet-redirect-forward) - [Apache Tiles Integration with Spring MVC](https://www.baeldung.com/spring-mvc-apache-tiles) - [Guide to Spring Email](https://www.baeldung.com/spring-email) +- [Using ThymeLeaf and FreeMarker Emails Templates with Spring](https://www.baeldung.com/thymeleaf-freemarker-email) - [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405) - [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param) - More articles: [[more -->]](/spring-mvc-basics-3) diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java index 941a984684..e70e801577 100644 --- a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -2,7 +2,6 @@ package com.baeldung.spring.configuration; import java.util.ArrayList; import java.util.List; -import java.util.Properties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -10,9 +9,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.feed.RssChannelHttpMessageConverter; -import org.springframework.mail.SimpleMailMessage; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; @@ -65,29 +61,5 @@ public class ApplicationConfiguration implements WebMvcConfigurer { converters.add(new RssChannelHttpMessageConverter()); converters.add(new JsonChannelHttpMessageConverter()); } - - @Bean - public SimpleMailMessage templateSimpleMessage() { - SimpleMailMessage message = new SimpleMailMessage(); - message.setText("This is the test email template for your email:\n%s\n"); - return message; - } - - @Bean - public JavaMailSender getJavaMailSender() { - JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); - mailSender.setHost("smtp.gmail.com"); - mailSender.setPort(587); - - mailSender.setUsername("my.gmail@gmail.com"); - mailSender.setPassword("password"); - - Properties props = mailSender.getJavaMailProperties(); - props.put("mail.transport.protocol", "smtp"); - props.put("mail.smtp.auth", "true"); - props.put("mail.smtp.starttls.enable", "true"); - props.put("mail.debug", "true"); - - return mailSender; - } + } diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/EmailConfiguration.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/EmailConfiguration.java new file mode 100644 index 0000000000..1bbbc51304 --- /dev/null +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/EmailConfiguration.java @@ -0,0 +1,89 @@ +package com.baeldung.spring.configuration; + +import java.util.Properties; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; +import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; + +@Configuration +@ComponentScan(basePackages = { "com.baeldung.spring.mail" }) +public class EmailConfiguration { + + @Bean + public JavaMailSender getJavaMailSender() { + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + + mailSender.setHost("smtp.gmail.com"); + mailSender.setPort(587); + + mailSender.setUsername("my.gmail@gmail.com"); + mailSender.setPassword("password"); + + Properties props = mailSender.getJavaMailProperties(); + props.put("mail.transport.protocol", "smtp"); + props.put("mail.smtp.auth", "true"); + props.put("mail.smtp.starttls.enable", "false"); + props.put("mail.debug", "true"); + + return mailSender; + } + + @Bean + public SimpleMailMessage templateSimpleMessage() { + SimpleMailMessage message = new SimpleMailMessage(); + message.setText("This is the test email template for your email:\n%s\n"); + return message; + } + + @Bean + public SpringTemplateEngine thymeleafTemplateEngine() { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(thymeleafTemplateResolver()); + templateEngine.setTemplateEngineMessageSource(emailMessageSource()); + return templateEngine; + } + + @Bean + public SpringResourceTemplateResolver thymeleafTemplateResolver() { + SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/views/mail/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML"); + templateResolver.setCharacterEncoding("UTF-8"); + return templateResolver; + } + + @Bean + public FreeMarkerConfigurer freemarkerConfig() { + FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); + freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/mail"); + return freeMarkerConfigurer; + } + + @Bean + public FreeMarkerViewResolver freemarkerViewResolver() { + FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); + resolver.setCache(true); + resolver.setPrefix(""); + resolver.setSuffix(".ftl"); + return resolver; + } + + + @Bean + public ResourceBundleMessageSource emailMessageSource() { + final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("/mailMessages"); + return messageSource; + } + +} diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/WebInitializer.java index 74094a11c7..4d43549440 100644 --- a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/WebInitializer.java +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -20,6 +20,7 @@ public class WebInitializer implements WebApplicationInitializer { // ctx.register(GroovyConfiguration.class); // ctx.register(JadeTemplateConfiguration.class); // ctx.register(PushConfiguration.class); + ctx.register(EmailConfiguration.class); // ctx.setServletContext(container); //ctx.register(TilesApplicationConfiguration.class); diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java index 16d1202eef..b6e19a4c39 100644 --- a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/controller/MailController.java @@ -1,10 +1,17 @@ package com.baeldung.spring.controller; -import com.baeldung.spring.mail.EmailServiceImpl; -import com.baeldung.spring.domain.MailObject; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.mail.MessagingException; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.mail.SimpleMailMessage; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; @@ -12,26 +19,21 @@ import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; +import com.baeldung.spring.domain.MailObject; +import com.baeldung.spring.mail.EmailService; + +import freemarker.template.TemplateException; @Controller @RequestMapping("/mail") public class MailController { @Autowired - public EmailServiceImpl emailService; + public EmailService emailService; @Value("${attachment.invoice}") private String attachmentPath; - @Autowired - public SimpleMailMessage template; - private static final Map> labels; static { @@ -46,7 +48,7 @@ public class MailController { //Email with template props = new HashMap<>(); - props.put("headerText", "Send Email Using Template"); + props.put("headerText", "Send Email Using Text Template"); props.put("messageLabel", "Template Parameter"); props.put("additionalInfo", "The parameter value will be added to the following message template:
" + @@ -60,6 +62,7 @@ public class MailController { props.put("messageLabel", "Message"); props.put("additionalInfo", "To make sure that you send an attachment with this email, change the value for the 'attachment.invoice' in the application.properties file to the path to the attachment."); labels.put("sendAttachment", props); + } @RequestMapping(method = RequestMethod.GET) @@ -85,6 +88,7 @@ public class MailController { return "mail/send"; } + @RequestMapping(value = "/send", method = RequestMethod.POST) public String createMail(Model model, @ModelAttribute("mailObject") @Valid MailObject mailObject, @@ -95,7 +99,7 @@ public class MailController { emailService.sendSimpleMessage(mailObject.getTo(), mailObject.getSubject(), mailObject.getText()); - return "redirect:/home"; + return "emails"; } @RequestMapping(value = "/sendTemplate", method = RequestMethod.POST) @@ -107,10 +111,9 @@ public class MailController { } emailService.sendSimpleMessageUsingTemplate(mailObject.getTo(), mailObject.getSubject(), - template, mailObject.getText()); - return "redirect:/home"; + return "redirect:/mail"; } @RequestMapping(value = "/sendAttachment", method = RequestMethod.POST) @@ -127,6 +130,47 @@ public class MailController { attachmentPath ); - return "redirect:/home"; + return "redirect:/mail"; + } + + + @RequestMapping(value = {"/sendHtml"}, method = RequestMethod.GET) + public String getHtmlMailView(Model model, + HttpServletRequest request) { + + Map templateEngines = new HashMap<>(); + templateEngines.put("Thymeleaf", "Thymeleaf"); + templateEngines.put("Freemarker", "Freemarker"); + model.addAttribute("mailObject", new MailObject()); + model.addAttribute("templateEngines", templateEngines); + return "mail/sendHtml"; + } + + @RequestMapping(value = "/sendHtml", method = RequestMethod.POST) + public String createHtmlMail(Model model, + @ModelAttribute("mailObject") @Valid MailObject mailObject, + Errors errors) throws IOException, MessagingException, TemplateException { + if (errors.hasErrors()) { + return "mail/send"; + } + + Map templateModel = new HashMap<>(); + templateModel.put("recipientName", mailObject.getRecipientName()); + templateModel.put("text", mailObject.getText()); + templateModel.put("senderName", mailObject.getSenderName()); + + if (mailObject.getTemplateEngine().equalsIgnoreCase("thymeleaf")) { + emailService.sendMessageUsingThymeleafTemplate( + mailObject.getTo(), + mailObject.getSubject(), + templateModel); + } else { + emailService.sendMessageUsingFreemarkerTemplate( + mailObject.getTo(), + mailObject.getSubject(), + templateModel); + } + + return "redirect:/mail"; } } diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java index aceaf685fa..d425ca9a26 100644 --- a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/domain/MailObject.java @@ -12,8 +12,11 @@ public class MailObject { @NotNull @Size(min = 1, message = "Please, set an email address to send the message to it") private String to; + private String recipientName; private String subject; private String text; + private String senderName; + private String templateEngine; public String getTo() { return to; @@ -38,4 +41,30 @@ public class MailObject { public void setText(String text) { this.text = text; } + + public String getRecipientName() { + return recipientName; + } + + public void setRecipientName(String recipientName) { + this.recipientName = recipientName; + } + + public String getSenderName() { + return senderName; + } + + public void setSenderName(String senderName) { + this.senderName = senderName; + } + + public String getTemplateEngine() { + return templateEngine; + } + + public void setTemplateEngine(String templateEngine) { + this.templateEngine = templateEngine; + } + + } diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailService.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailService.java index 43d7378227..b7d5be09c8 100644 --- a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailService.java +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailService.java @@ -1,6 +1,11 @@ package com.baeldung.spring.mail; -import org.springframework.mail.SimpleMailMessage; +import java.io.IOException; +import java.util.Map; + +import javax.mail.MessagingException; + +import freemarker.template.TemplateException; /** * Created by Olga on 8/22/2016. @@ -11,10 +16,19 @@ public interface EmailService { String text); void sendSimpleMessageUsingTemplate(String to, String subject, - SimpleMailMessage template, - String ...templateArgs); + String ...templateModel); void sendMessageWithAttachment(String to, String subject, String text, String pathToAttachment); + + void sendMessageUsingThymeleafTemplate(String to, + String subject, + Map templateModel) + throws IOException, MessagingException; + + void sendMessageUsingFreemarkerTemplate(String to, + String subject, + Map templateModel) + throws IOException, TemplateException, MessagingException; } diff --git a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java index 039b970d8e..0592415ab5 100644 --- a/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java +++ b/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java @@ -1,26 +1,49 @@ package com.baeldung.spring.mail; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.FileSystemResource; -import org.springframework.mail.MailException; -import org.springframework.mail.SimpleMailMessage; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.mail.javamail.MimeMessageHelper; -import org.springframework.stereotype.Component; - import java.io.File; +import java.io.IOException; +import java.util.Map; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.mail.MailException; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.stereotype.Service; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; +import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; +import org.thymeleaf.context.Context; +import org.thymeleaf.spring4.SpringTemplateEngine; + +import freemarker.template.Template; +import freemarker.template.TemplateException; + /** * Created by Olga on 7/15/2016. */ -@Component +@Service("EmailService") public class EmailServiceImpl implements EmailService { @Autowired public JavaMailSender emailSender; + + @Autowired + public SimpleMailMessage template; + + @Autowired + private SpringTemplateEngine thymeleafTemplateEngine; + + @Autowired + private FreeMarkerConfigurer freemarkerConfigurer; + + @Value("classpath:/mail-logo.png") + Resource resourceFile; public void sendSimpleMessage(String to, String subject, String text) { try { @@ -38,9 +61,8 @@ public class EmailServiceImpl implements EmailService { @Override public void sendSimpleMessageUsingTemplate(String to, String subject, - SimpleMailMessage template, - String ...templateArgs) { - String text = String.format(template.getText(), templateArgs); + String ...templateModel) { + String text = String.format(template.getText(), templateModel); sendSimpleMessage(to, subject, text); } @@ -66,4 +88,42 @@ public class EmailServiceImpl implements EmailService { e.printStackTrace(); } } + + + @Override + public void sendMessageUsingThymeleafTemplate( + String to, String subject, Map templateModel) + throws MessagingException { + + Context thymeleafContext = new Context(); + thymeleafContext.setVariables(templateModel); + + String htmlBody = thymeleafTemplateEngine.process("template-thymeleaf.html", thymeleafContext); + + sendHtmlMessage(to, subject, htmlBody); + } + + @Override + public void sendMessageUsingFreemarkerTemplate( + String to, String subject, Map templateModel) + throws IOException, TemplateException, MessagingException { + + Template freemarkerTemplate = freemarkerConfigurer.createConfiguration().getTemplate("template-freemarker.ftl"); + String htmlBody = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerTemplate, templateModel); + + sendHtmlMessage(to, subject, htmlBody); + } + + private void sendHtmlMessage(String to, String subject, String htmlBody) throws MessagingException { + + MimeMessage message = emailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); + helper.setTo(to); + helper.setSubject(subject); + helper.setText(htmlBody, true); + helper.addInline("attachment.png", resourceFile); + emailSender.send(message); + + } + } diff --git a/spring-mvc-basics-2/src/main/resources/mail-logo.png b/spring-mvc-basics-2/src/main/resources/mail-logo.png new file mode 100644 index 0000000000..edb83efbe3 Binary files /dev/null and b/spring-mvc-basics-2/src/main/resources/mail-logo.png differ diff --git a/spring-mvc-basics-2/src/main/resources/mailMessages.properties b/spring-mvc-basics-2/src/main/resources/mailMessages.properties new file mode 100644 index 0000000000..46f7a80ed3 --- /dev/null +++ b/spring-mvc-basics-2/src/main/resources/mailMessages.properties @@ -0,0 +1,5 @@ +greetings=Hi {0}, +subscriptions=Please find below your current subscriptions to our forum: +regards=Regards, +unsubscribe=Unsubscribe from these emails here +signature={0} at Baeldung \ No newline at end of file diff --git a/spring-mvc-basics-2/src/main/resources/mailMessages_fr_FR.properties b/spring-mvc-basics-2/src/main/resources/mailMessages_fr_FR.properties new file mode 100644 index 0000000000..6f300a9ab7 --- /dev/null +++ b/spring-mvc-basics-2/src/main/resources/mailMessages_fr_FR.properties @@ -0,0 +1,5 @@ +greetings=Bonjour {0}, +subscriptions=Voici vos différentes souscriptions sur notre forum : +regards=Cordialement, +unsubscribe=Se désinscrire de ces emails ici +signature={0} à Baeldung \ No newline at end of file diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/emails.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/emails.jsp index 63351bbf3a..dafa71cbb0 100644 --- a/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/emails.jsp +++ b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/emails.jsp @@ -26,7 +26,7 @@ - + @@ -34,6 +34,11 @@ + + + + + diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/sendHtml.jsp b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/sendHtml.jsp new file mode 100644 index 0000000000..f91a8826d1 --- /dev/null +++ b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/sendHtml.jsp @@ -0,0 +1,73 @@ +<%-- + User: Benjamin CAURE + Date: 4/14/2020 +--%> +<%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> + + + Send HTML Email + + +
+

Send Email Using Text Template

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Enter email address
+ +
+ Enter the recipient name
+ +
+ Enter the subject
+ +
+ +
+ Enter the sender name
+ +
+ Select the template engine
+ +
+ +
+
+
+
+
+ + diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-freemarker.ftl b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-freemarker.ftl new file mode 100644 index 0000000000..066fc0302c --- /dev/null +++ b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-freemarker.ftl @@ -0,0 +1,15 @@ + + + + + + +

Hi ${recipientName}

+

${text}

+

Regards,

+

+ ${senderName} at Baeldung
+ +

+ + diff --git a/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-thymeleaf.html b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-thymeleaf.html new file mode 100644 index 0000000000..b255b5dee5 --- /dev/null +++ b/spring-mvc-basics-2/src/main/webapp/WEB-INF/views/mail/template-thymeleaf.html @@ -0,0 +1,15 @@ + + + + + + +

+

+

+

+
+ +

+ + diff --git a/spring-mvc-basics-2/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-basics-2/src/test/java/com/baeldung/SpringContextTest.java index ab0b23c4a5..5c276254d3 100644 --- a/spring-mvc-basics-2/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-mvc-basics-2/src/test/java/com/baeldung/SpringContextTest.java @@ -7,10 +7,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.baeldung.spring.configuration.ApplicationConfiguration; +import com.baeldung.spring.configuration.EmailConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes={ApplicationConfiguration.class}) +@ContextConfiguration(classes={ApplicationConfiguration.class, EmailConfiguration.class}) @WebAppConfiguration public class SpringContextTest { diff --git a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java b/spring-mvc-basics-2/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java index fe7aeeb570..2ed70489c0 100644 --- a/spring-mvc-basics-2/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java +++ b/spring-mvc-basics-2/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java @@ -1,6 +1,8 @@ package com.baeldung.controller.rss; import com.baeldung.spring.configuration.ApplicationConfiguration; +import com.baeldung.spring.configuration.EmailConfiguration; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -13,7 +15,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@SpringJUnitWebConfig(ApplicationConfiguration.class) +@SpringJUnitWebConfig(classes={ApplicationConfiguration.class, EmailConfiguration.class}) public class ArticleRssIntegrationTest { public static final String APPLICATION_RSS_XML = "application/rss+xml"; public static final String APPLICATION_RSS_JSON = "application/rss+json"; diff --git a/spring-mvc-basics-3/README.md b/spring-mvc-basics-3/README.md index 180cee498b..074c60152c 100644 --- a/spring-mvc-basics-3/README.md +++ b/spring-mvc-basics-3/README.md @@ -12,4 +12,5 @@ This module contains articles about Spring MVC - [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter) - [Guide to Flash Attributes in a Spring Web Application](https://www.baeldung.com/spring-web-flash-attributes) - [Handling URL Encoded Form Data in Spring REST](https://www.baeldung.com/spring-url-encoded-form-data) +- [Reading HttpServletRequest Multiple Times in Spring](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times) - More articles: [[<-- prev]](/spring-mvc-basics-2)[[more -->]](/spring-mvc-basics-4) diff --git a/spring-mvc-crash/.gitignore b/spring-mvc-crash/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-mvc-crash/.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-crash/README.md b/spring-mvc-crash/README.md new file mode 100644 index 0000000000..f158a947b6 --- /dev/null +++ b/spring-mvc-crash/README.md @@ -0,0 +1,11 @@ +## Spring MVC XML + +This module contains articles about Spring MVC with XML configuration + +### Relevant Articles: + +- [Getting Started with CRaSH](https://www.baeldung.com/jvm-crash-shell) + +## Spring MVC with XML Configuration Example Project + +- access a sample jsp page at: `http://localhost:8080/spring-mvc-crash/welcome.htm \ No newline at end of file diff --git a/spring-mvc-crash/pom.xml b/spring-mvc-crash/pom.xml new file mode 100644 index 0000000000..d23e18361b --- /dev/null +++ b/spring-mvc-crash/pom.xml @@ -0,0 +1,176 @@ + + + 4.0.0 + spring-mvc-crash + 0.1-SNAPSHOT + spring-mvc-xml + war + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + + + + javax.servlet + jstl + ${jstl.version} + runtime + + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + commons-io + commons-io + ${commons-io.version} + + + com.maxmind.geoip2 + geoip2 + ${geoip2.version} + + + com.fasterxml.jackson.core + jackson-databind + + + commons-logging + commons-logging + + + + + org.glassfish + javax.el + ${javax.el.version} + + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + + + + org.crashub + crash.embed.spring + ${crash.version} + + + org.crashub + crash.cli + ${crash.version} + + + org.crashub + crash.connectors.telnet + ${crash.version} + + + log4j + log4j + + + + + + + org.codehaus.groovy + groovy + ${groovy.version} + + + + + spring-mvc-xml + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + + + + + + + 5.0.2.RELEASE + 1.5.10.RELEASE + + + 5.1.40 + + + 4.4.5 + 4.5.2 + + + 6.0.10.Final + 3.0.1-b08 + + + 19.0 + 2.8.0 + + + 1.6.1 + + 1.3.2 + 3.0.0-rc-3 + + + + diff --git a/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java new file mode 100644 index 0000000000..cc60a1ff8f --- /dev/null +++ b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@ImportResource("classpath:webMvcConfig.xml") +@Configuration +@ComponentScan +public class ClientWebConfig implements WebMvcConfigurer { + + public ClientWebConfig() { + super(); + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java new file mode 100644 index 0000000000..55af23034f --- /dev/null +++ b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java @@ -0,0 +1,33 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@ComponentScan("com.baeldung.spring") +public class ClientWebConfigJava implements WebMvcConfigurer { + + public ClientWebConfigJava() { + super(); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } + + @Bean + public MethodValidationPostProcessor methodValidationPostProcessor() { + return new MethodValidationPostProcessor(); + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java b/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java new file mode 100644 index 0000000000..526833611b --- /dev/null +++ b/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class WelcomeController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + + ModelAndView model = new ModelAndView("welcome"); + model.addObject("msg", "Welcome to Introduction to CRaSH article from Baeldung"); + + return model; + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/resources/contentManagementWebMvcConfig.xml b/spring-mvc-crash/src/main/resources/contentManagementWebMvcConfig.xml new file mode 100644 index 0000000000..8a0671ca87 --- /dev/null +++ b/spring-mvc-crash/src/main/resources/contentManagementWebMvcConfig.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-mvc-crash/src/main/resources/logback.xml b/spring-mvc-crash/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/spring-mvc-crash/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/resources/messages.properties b/spring-mvc-crash/src/main/resources/messages.properties new file mode 100644 index 0000000000..2a3cccf76c --- /dev/null +++ b/spring-mvc-crash/src/main/resources/messages.properties @@ -0,0 +1,2 @@ +required.name = Name is required! +NotEmpty.person.password = Password is required! \ No newline at end of file diff --git a/spring-mvc-crash/src/main/resources/webMvcConfig.xml b/spring-mvc-crash/src/main/resources/webMvcConfig.xml new file mode 100644 index 0000000000..4bdb405237 --- /dev/null +++ b/spring-mvc-crash/src/main/resources/webMvcConfig.xml @@ -0,0 +1,38 @@ + + + + + + + + + image/jpeg + image/png + + + + + + + + + + + + + + + + + + + diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message.groovy b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message.groovy new file mode 100644 index 0000000000..d66ab13d96 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message.groovy @@ -0,0 +1,14 @@ +import org.crsh.cli.Command; +import org.crsh.cli.Usage; +import org.crsh.cli.Option; + +class message { + + @Usage("show my own message") + @Command + Object main(@Usage("custom message") @Option(names=["m","message"]) String message) { + if (message == null) + message = "No message given..."; + return message; + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java new file mode 100644 index 0000000000..d1ead88024 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java @@ -0,0 +1,14 @@ +import org.crsh.command.BaseCommand; +import org.crsh.cli.Usage; +import org.crsh.cli.Command; +import org.crsh.cli.Option; + +public class message2 extends BaseCommand { + @Usage("show my own message using java") + @Command + public Object main(@Usage("custom message") @Option(names = { "m", "message" }) String message) { + if (message == null) + message = "No message given..."; + return message; + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/crash.properties b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/crash.properties new file mode 100644 index 0000000000..f9ad0d7cf6 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/crash.properties @@ -0,0 +1 @@ +crash.telnet.port=50001 diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/telnet.properties b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/telnet.properties new file mode 100644 index 0000000000..99071d09ff --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/telnet.properties @@ -0,0 +1,65 @@ +############################ +# Telnet daemon properties # +############################ + +##################### +# Terminals Section # +##################### + +# List of terminals available and defined below +terminals=vt100,ansi,windoof,xterm + +# vt100 implementation and aliases +term.vt100.class=net.wimpi.telnetd.io.terminal.vt100 +term.vt100.aliases=default,vt100-am,vt102,dec-vt100 + +# ansi implementation and aliases +term.ansi.class=net.wimpi.telnetd.io.terminal.ansi +term.ansi.aliases=color-xterm,xterm-color,vt320,vt220,linux,screen + +# windoof implementation and aliases +term.windoof.class=net.wimpi.telnetd.io.terminal.Windoof +term.windoof.aliases= + +# xterm implementation and aliases +term.xterm.class=net.wimpi.telnetd.io.terminal.xterm +term.xterm.aliases= + +################## +# Shells Section # +################## + +# List of shells available and defined below +shells=simple + +# shell implementations +shell.simple.class=org.crsh.telnet.term.TelnetHandler + +##################### +# Listeners Section # +##################### +listeners=std + + +# std listener specific properties + +#Basic listener and connection management settings (port is commented because CRaSH configures it) +# std.port=5000 +std.floodprotection=5 +std.maxcon=25 + + +# Timeout Settings for connections (ms) +std.time_to_warning=3600000 +std.time_to_timedout=60000 + +# Housekeeping thread active every 1 secs +std.housekeepinginterval=1000 + +std.inputmode=character + +# Login shell +std.loginshell=simple + +# Connection filter class +std.connectionfilter=none \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-mvc-crash/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..46b159d984 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + welcomeController + welcomeController + + + + + + + + + + + + + + 5000 + + + + diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/view/error.jsp b/spring-mvc-crash/src/main/webapp/WEB-INF/view/error.jsp new file mode 100644 index 0000000000..8f3d83af17 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/view/error.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +SpringMVCExample + + + +

Pleas enter the correct details

+ + + + +
Retry
+ + + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/view/errorPage.jsp b/spring-mvc-crash/src/main/webapp/WEB-INF/view/errorPage.jsp new file mode 100644 index 0000000000..ba8a836285 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/view/errorPage.jsp @@ -0,0 +1,10 @@ +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> +<%@ page session="false"%> + + + Home + + +

${errorMsg}

+ + diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-crash/src/main/webapp/WEB-INF/view/welcome.jsp new file mode 100644 index 0000000000..348ca652ff --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/view/welcome.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Welcome Page + + +

Welcome to ${msg}

+
+

+ Go to spring handler mappings homepage + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/web.xml b/spring-mvc-crash/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..4a3d6cb321 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,70 @@ + + + Spring MVC XML Application + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + com.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + org.crsh.plugin.WebPluginLifeCycle + + + + + mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc + / + + + + + + ExampleOne + com.baeldung.jsp.ExampleOne + + + ExampleOne + /jsp/ExampleOne + + + ExampleThree + com.baeldung.jsp.ExampleThree + + + ExampleThree + /jsp/ExampleThree + + + + + + 10 + + + index.jsp + + + + /errors + + diff --git a/spring-mvc-crash/src/main/webapp/index.jsp b/spring-mvc-crash/src/main/webapp/index.jsp new file mode 100644 index 0000000000..149fc5fe0b --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/index.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC Examples + + + +

Spring MVC Examples

+ + + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/jsp/ExampleThree.jsp b/spring-mvc-crash/src/main/webapp/jsp/ExampleThree.jsp new file mode 100644 index 0000000000..665eb86a30 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/jsp/ExampleThree.jsp @@ -0,0 +1,10 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Java Binding Example + + +

Bound Value

+

You said: ${text}

+ + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/jsp/ExampleTwo.jsp b/spring-mvc-crash/src/main/webapp/jsp/ExampleTwo.jsp new file mode 100644 index 0000000000..7b2247638d --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/jsp/ExampleTwo.jsp @@ -0,0 +1,13 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Java in Static Page Example + + +

Java in Static Page Example

+ <% String[] arr = {"What's up?", "Hello", "It's a nice day today!"}; + String greetings = arr[(int)(Math.random() * arr.length)]; + %> +

<%= greetings %>

+ + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/jsp/index.jsp b/spring-mvc-crash/src/main/webapp/jsp/index.jsp new file mode 100644 index 0000000000..58c464125d --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/jsp/index.jsp @@ -0,0 +1,12 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + JSP Examples + + +

Simple JSP Examples

+

Invoke HTML rendered by Servlet: here

+

Java in static page: here

+

Java injected by Servlet: here

+ + \ No newline at end of file diff --git a/spring-mvc-crash/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-crash/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..62e34859ee --- /dev/null +++ b/spring-mvc-crash/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.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-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java new file mode 100644 index 0000000000..3623217130 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.web.config; + +import javax.servlet.MultipartConfigElement; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class MainWebAppInitializer implements WebApplicationInitializer { + + private String TMP_FOLDER = "/tmp"; + private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; + + @Override + public void onStartup(ServletContext sc) throws ServletException { + + ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet( + new GenericWebApplicationContext())); + + appServlet.setLoadOnStartup(1); + + MultipartConfigElement multipartConfigElement = new MultipartConfigElement(TMP_FOLDER, + MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); + + appServlet.setMultipartConfig(multipartConfigElement); + + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 96e300464b..768fda1c4a 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,6 +12,7 @@ import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; @@ -121,4 +122,11 @@ public class WebConfig implements WebMvcConfigurer { public ExcelPOIHelper excelPOIHelper() { return new ExcelPOIHelper(); } + + @Bean(name = "multipartResolver") + public CommonsMultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(100000); + return multipartResolver; + } } \ No newline at end of file diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 685e7686b1..0adf127aaa 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -17,7 +17,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) - [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable) - [Debugging the Spring MVC 404 “No mapping found for HTTP request” Error](https://www.baeldung.com/spring-mvc-404-error) -- [Getting Started with CRaSH](https://www.baeldung.com/jvm-crash-shell) ## Spring MVC with XML Configuration Example Project diff --git a/spring-reactive-kotlin/README.md b/spring-reactive-kotlin/README.md index 629f7e7f58..d6ce3b7645 100644 --- a/spring-reactive-kotlin/README.md +++ b/spring-reactive-kotlin/README.md @@ -4,3 +4,4 @@ This module contains articles about reactive Kotlin ### Relevant Articles: - [Spring Webflux with Kotlin](https://www.baeldung.com/spring-webflux-kotlin) +- [Kotlin Reactive Microservice With Spring Boot](https://www.baeldung.com/spring-boot-kotlin-reactive-microservice) diff --git a/spring-reactive-kotlin/pom.xml b/spring-reactive-kotlin/pom.xml index 3a693837df..cbb143f6ec 100644 --- a/spring-reactive-kotlin/pom.xml +++ b/spring-reactive-kotlin/pom.xml @@ -5,6 +5,7 @@ spring-reactive-kotlin spring-reactive-kotlin Demo project for Spring Boot + jar @@ -23,6 +24,18 @@ org.springframework.boot spring-boot-starter-webflux + + org.springframework.boot.experimental + spring-boot-starter-data-r2dbc + + + org.springframework.boot + spring-boot-starter-actuator + + + io.r2dbc + r2dbc-h2 + com.fasterxml.jackson.module jackson-module-kotlin @@ -38,21 +51,95 @@ reactor-test test + + + org.springframework.boot.experimental + spring-boot-test-autoconfigure-r2dbc + test + + + io.projectreactor + reactor-test + test + + + + + + org.springframework.boot.experimental + spring-boot-bom-r2dbc + 0.1.0.M3 + pom + import + + + + + src/main/kotlin + src/test/kotlin kotlin-maven-plugin + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + org.jetbrains.kotlin ${kotlin.version} -Xjsr305=strict + 1.8 + + spring + jpa + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-maven-noarg + ${kotlin.version} + + + + 1.8 + 1.3.70 + 2.2.5.RELEASE + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + +
diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt new file mode 100644 index 0000000000..c70057b5de --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt @@ -0,0 +1,11 @@ +package com.baeldung.bootmicroservice + +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication +class HealthTrackerApplication + +fun main(args: Array) { + runApplication(*args) +} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt new file mode 100644 index 0000000000..b14682cc5c --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt @@ -0,0 +1,28 @@ +package com.baeldung.bootmicroservice.config; + +import org.springframework.context.annotation.Configuration +import org.springframework.data.r2dbc.core.DatabaseClient + +@Configuration +class DBConfiguration(db: DatabaseClient) { + init { + val initDb = db.execute { + """ CREATE TABLE IF NOT EXISTS profile ( + id SERIAL PRIMARY KEY, + first_name VARCHAR(20) NOT NULL, + last_name VARCHAR(20) NOT NULL, + birth_date DATE NOT NULL + ); + CREATE TABLE IF NOT EXISTS health_record( + id SERIAL PRIMARY KEY, + profile_id LONG NOT NULL, + temperature DECIMAL NOT NULL, + blood_pressure DECIMAL NOT NULL, + heart_rate DECIMAL, + date DATE NOT NULL + ); + """ + } + initDb.then().subscribe() + } +} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt new file mode 100644 index 0000000000..620f187b7b --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt @@ -0,0 +1,44 @@ +package com.baeldung.bootmicroservice.controller + +import com.baeldung.bootmicroservice.model.AverageHealthStatus +import com.baeldung.bootmicroservice.model.HealthRecord +import com.baeldung.bootmicroservice.repository.HealthRecordRepository +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.RestController +import reactor.core.publisher.Mono + +@RestController +class HealthRecordController(val repository: HealthRecordRepository) { + + @PostMapping("/health/{profileId}/record") + fun storeHealthRecord(@PathVariable("profileId") profileId: Long, @RequestBody record: HealthRecord): Mono = + repository.save(HealthRecord(null + , profileId + , record.temperature + , record.bloodPressure + , record.heartRate + , record.date)) + + @GetMapping("/health/{profileId}/avg") + fun fetchHealthRecordAverage(@PathVariable("profileId") profileId: Long): Mono = + repository.findByProfileId(profileId) + .reduce( + AverageHealthStatus(0, 0.0, 0.0, 0.0) + , { s, r -> + AverageHealthStatus(s.cnt + 1 + , s.temperature + r.temperature + , s.bloodPressure + r.bloodPressure + , s.heartRate + r.heartRate + ) + } + ).map { s -> + AverageHealthStatus(s.cnt + , if (s.cnt != 0) s.temperature / s.cnt else 0.0 + , if (s.cnt != 0) s.bloodPressure / s.cnt else 0.0 + , if (s.cnt != 0) s.heartRate / s.cnt else 0.0) + } + +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt new file mode 100644 index 0000000000..1dc3bcdc50 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt @@ -0,0 +1,15 @@ +package com.baeldung.bootmicroservice.controller + +import com.baeldung.bootmicroservice.model.Profile +import com.baeldung.bootmicroservice.repository.ProfileRepository +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RestController +import reactor.core.publisher.Mono + +@RestController +class ProfileController(val repository: ProfileRepository) { + + @PostMapping("/profile") + fun save(@RequestBody profile: Profile): Mono = repository.save(profile) +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt new file mode 100644 index 0000000000..3141146b9c --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt @@ -0,0 +1,3 @@ +package com.baeldung.bootmicroservice.model; + +class AverageHealthStatus(var cnt: Int, var temperature: Double, var bloodPressure: Double, var heartRate: Double) diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt new file mode 100644 index 0000000000..71c534027f --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt @@ -0,0 +1,8 @@ +package com.baeldung.bootmicroservice.model + +import org.springframework.data.annotation.Id +import org.springframework.data.relational.core.mapping.Table +import java.time.LocalDate + +@Table +data class HealthRecord(@Id var id: Long?, var profileId: Long?, var temperature: Double, var bloodPressure: Double, var heartRate: Double, var date: LocalDate) \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt new file mode 100644 index 0000000000..cbb7e675ea --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt @@ -0,0 +1,8 @@ +package com.baeldung.bootmicroservice.model + +import org.springframework.data.annotation.Id +import org.springframework.data.relational.core.mapping.Table +import java.time.LocalDateTime + +@Table +data class Profile(@Id var id:Long?, var firstName : String, var lastName : String, var birthDate: LocalDateTime) \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt new file mode 100644 index 0000000000..8cc91f06e4 --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt @@ -0,0 +1,13 @@ +package com.baeldung.bootmicroservice.repository + +import com.baeldung.bootmicroservice.model.HealthRecord +import org.springframework.data.r2dbc.repository.Query +import org.springframework.data.repository.reactive.ReactiveCrudRepository +import org.springframework.stereotype.Repository +import reactor.core.publisher.Flux + +@Repository +interface HealthRecordRepository: ReactiveCrudRepository { + @Query("select p.* from health_record p where p.profile_id = :profileId ") + fun findByProfileId(profileId: Long): Flux +} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt new file mode 100644 index 0000000000..eee8c5fcbe --- /dev/null +++ b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt @@ -0,0 +1,8 @@ +package com.baeldung.bootmicroservice.repository + +import com.baeldung.bootmicroservice.model.Profile +import org.springframework.data.repository.reactive.ReactiveCrudRepository +import org.springframework.stereotype.Repository + +@Repository +interface ProfileRepository: ReactiveCrudRepository \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/resources/application.yml b/spring-reactive-kotlin/src/main/resources/application.yml new file mode 100644 index 0000000000..d75683f905 --- /dev/null +++ b/spring-reactive-kotlin/src/main/resources/application.yml @@ -0,0 +1 @@ +management.endpoints.web.exposure.include: health,metrics \ No newline at end of file diff --git a/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt b/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt new file mode 100644 index 0000000000..51481af3d7 --- /dev/null +++ b/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt @@ -0,0 +1,51 @@ +package com.baeldung.bootmicroservice.controller; + +import com.baeldung.bootmicroservice.model.Profile +import com.fasterxml.jackson.databind.ObjectMapper +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.http.MediaType +import org.springframework.test.web.reactive.server.WebTestClient +import java.time.LocalDateTime + +@SpringBootTest +class ProfileControllerTest { + @Autowired + lateinit var controller: ProfileController + + @Autowired + lateinit var mapper: ObjectMapper ; + + lateinit var client: WebTestClient + lateinit var profile: String + + @BeforeEach + fun setup() { + client = WebTestClient.bindToController(controller).build() + profile = mapper.writeValueAsString(Profile(null, "kotlin", "reactive", LocalDateTime.now())) + } + + @Test + fun whenRequestProfile_thenStatusShouldBeOk() { + client.post() + .uri("/profile") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(profile) + .exchange() + .expectStatus().isOk + } + + @Test + fun whenRequestProfile_thenIdShouldBeNotNull() { + client.post() + .uri("/profile") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(profile) + .exchange() + .expectBody() + .jsonPath("$.id") + .isNotEmpty + } +} diff --git a/spring-reactor/README.md b/spring-reactor/README.md index b92478f6fb..f8cf2898f1 100644 --- a/spring-reactor/README.md +++ b/spring-reactor/README.md @@ -4,4 +4,4 @@ This module contains articles about Spring Reactor ## Relevant articles: -- [Introduction to Spring Reactor](https://www.baeldung.com/spring-reactor) +- [Introduction to Project Reactor Bus](https://www.baeldung.com/reactor-bus) diff --git a/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java b/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java index 543ba76273..cafd9a38e3 100644 --- a/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java +++ b/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java @@ -72,7 +72,7 @@ public class FooMappingExamplesController { @RequestMapping(value = "/foos", produces = { "application/json", "application/xml" }) @ResponseBody - public String getFoosAsJsonFromREST() { + public String getFoosAsJsonFromBrowser() { return "Get some Foos with Header New"; } diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java similarity index 92% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java index 9a361e92c9..3e4d1ffa00 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate; +package com.baeldung.resttemplate; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java similarity index 95% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java index a39994ae67..bef8af3725 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java similarity index 89% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java index 5e8220d064..75ce02ea04 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.springframework.boot.web.client.RestTemplateCustomizer; import org.springframework.web.client.RestTemplate; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java similarity index 97% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java index a9d400b199..dbef16b592 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/FooController.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; @@ -6,7 +6,7 @@ import java.net.URI; import java.util.Collection; import java.util.Map; -import org.baeldung.resttemplate.web.dto.Foo; +import com.baeldung.resttemplate.web.dto.Foo; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java similarity index 95% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java index ee404db4f8..854ca1a1c1 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/HelloController.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java similarity index 82% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java index 966d5bcaa1..7866a4abcd 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/configuration/SpringConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package com.baeldung.resttemplate.configuration; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -11,7 +11,7 @@ import org.springframework.web.client.RestTemplate; @Configuration @EnableAutoConfiguration -@ComponentScan("org.baeldung.resttemplate.configuration") +@ComponentScan("com.baeldung.resttemplate.configuration") public class SpringConfig { @Bean @@ -26,8 +26,4 @@ public class SpringConfig { return new RestTemplateBuilder(customRestTemplateCustomizer()); } - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } } diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java index 226134787f..8a1773483a 100644 --- a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java @@ -7,7 +7,7 @@ import com.baeldung.resttemplate.lists.dto.Employee; import java.util.ArrayList; import java.util.List; -@Service +@Service("EmployeeListService") public class EmployeeService { public List getAllEmployees() diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/controller/PersonAPI.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java similarity index 88% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/controller/PersonAPI.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java index b1b56ec2f3..b3131cc00c 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/controller/PersonAPI.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java @@ -1,9 +1,9 @@ -package org.baeldung.resttemplate.web.controller; +package com.baeldung.resttemplate.web.controller; import javax.servlet.http.HttpServletResponse; -import org.baeldung.resttemplate.web.dto.Person; -import org.baeldung.resttemplate.web.service.PersonService; +import com.baeldung.resttemplate.web.service.PersonService; +import com.baeldung.resttemplate.web.dto.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java similarity index 93% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java index ed0a42c429..ede91dab1a 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.web.dto; +package com.baeldung.resttemplate.web.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Person.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Person.java similarity index 91% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Person.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Person.java index 4b7679638f..11e56fc6e2 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Person.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Person.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.web.dto; +package com.baeldung.resttemplate.web.dto; public class Person { private Integer id; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java similarity index 55% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java index 3e606e9314..8eb217978c 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/exception/NotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.web.exception; +package com.baeldung.resttemplate.web.exception; public class NotFoundException extends RuntimeException { } diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java similarity index 92% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java index 214de38746..02260438c7 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java @@ -1,8 +1,8 @@ -package org.baeldung.resttemplate.web.handler; +package com.baeldung.resttemplate.web.handler; import java.io.IOException; -import org.baeldung.resttemplate.web.exception.NotFoundException; +import com.baeldung.resttemplate.web.exception.NotFoundException; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.stereotype.Component; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java similarity index 87% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java index cf5279697f..7f8902e2fc 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Bar.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.web.model; +package com.baeldung.resttemplate.web.model; public class Bar { private String id; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Employee.java similarity index 93% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Employee.java index a9b84a77b4..bb1ad8cbfa 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/model/Employee.java @@ -1,6 +1,5 @@ -package org.baeldung.resttemplate.web.model; +package com.baeldung.resttemplate.web.model; -import java.util.Date; import java.util.Objects; public class Employee { diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java similarity index 80% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java index 54a66ea591..485143b0a1 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/BarConsumerService.java @@ -1,7 +1,7 @@ -package org.baeldung.resttemplate.web.service; +package com.baeldung.resttemplate.web.service; -import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; -import org.baeldung.resttemplate.web.model.Bar; +import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.model.Bar; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Service; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java similarity index 89% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java index c6562fbc94..18dff3db1b 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java @@ -1,6 +1,6 @@ -package org.baeldung.resttemplate.web.service; +package com.baeldung.resttemplate.web.service; -import org.baeldung.resttemplate.web.model.Employee; +import com.baeldung.resttemplate.web.model.Employee; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java similarity index 58% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonService.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java index c5ad39e101..e91d2adc5c 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java @@ -1,6 +1,6 @@ -package org.baeldung.resttemplate.web.service; +package com.baeldung.resttemplate.web.service; -import org.baeldung.resttemplate.web.dto.Person; +import com.baeldung.resttemplate.web.dto.Person; public interface PersonService { diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonServiceImpl.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java similarity index 77% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonServiceImpl.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java index 658e0fade0..d7a1bfc2db 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/PersonServiceImpl.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java @@ -1,6 +1,6 @@ -package org.baeldung.resttemplate.web.service; +package com.baeldung.resttemplate.web.service; -import org.baeldung.resttemplate.web.dto.Person; +import com.baeldung.resttemplate.web.dto.Person; import org.springframework.stereotype.Component; @Component diff --git a/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java index 11ea5b70c9..5c385edb07 100644 --- a/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java +++ b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java @@ -20,7 +20,7 @@ import com.baeldung.sampleapp.web.dto.Foo; import com.baeldung.sampleapp.web.exception.ResourceNotFoundException; @Controller -@RequestMapping(value = "/foos") +@RequestMapping(value = "/foo") public class MyFooController { private final Map myfoos; diff --git a/spring-resttemplate/src/main/java/com/baeldung/SpringContextTest.java b/spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/SpringContextTest.java rename to spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java b/spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java similarity index 71% rename from spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java rename to spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java index 7c4bbb4e5e..c626d1021d 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java +++ b/spring-resttemplate/src/test/java/com/baeldung/SpringTestConfig.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; @@ -8,12 +8,7 @@ import org.springframework.web.client.RestTemplate; @Configuration @EnableAutoConfiguration -@ComponentScan("org.baeldung") +@ComponentScan("com.baeldung") public class SpringTestConfig { - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } - } diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java b/spring-resttemplate/src/test/java/com/baeldung/client/Consts.java similarity index 68% rename from spring-resttemplate/src/test/java/org/baeldung/client/Consts.java rename to spring-resttemplate/src/test/java/com/baeldung/client/Consts.java index b40561d9c3..b392c4d199 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/Consts.java +++ b/spring-resttemplate/src/test/java/com/baeldung/client/Consts.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package com.baeldung.client; public interface Consts { int APPLICATION_PORT = 8082; diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java similarity index 98% rename from spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java index 967c4a6188..9f4b3c9b35 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java @@ -1,10 +1,10 @@ -package org.baeldung.client; +package com.baeldung.client; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; -import org.baeldung.resttemplate.web.dto.Foo; +import com.baeldung.resttemplate.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.web.client.TestRestTemplate; diff --git a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java similarity index 99% rename from spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java rename to spring-resttemplate/src/test/java/com/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java index 21639818db..eb5d01d06f 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/LargeFileDownloadIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate; +package com.baeldung.resttemplate; import org.assertj.core.api.Assertions; import org.junit.Assert; diff --git a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java similarity index 98% rename from spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java index 54e416d008..0dab124316 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java @@ -1,7 +1,7 @@ -package org.baeldung.resttemplate; +package com.baeldung.resttemplate; import static org.apache.commons.codec.binary.Base64.encodeBase64; -import static org.baeldung.client.Consts.APPLICATION_PORT; +import static com.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; @@ -14,8 +14,8 @@ import java.net.URI; import java.util.Arrays; import java.util.Set; -import org.baeldung.resttemplate.web.dto.Foo; -import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpEntity; diff --git a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/postjson/PersonAPILiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java similarity index 95% rename from spring-resttemplate/src/test/java/org/baeldung/resttemplate/postjson/PersonAPILiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java index 1347cb0c7a..f1861ede92 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/resttemplate/postjson/PersonAPILiveTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.resttemplate.postjson; +package com.baeldung.resttemplate.postjson; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.URI; -import org.baeldung.resttemplate.RestTemplateConfigurationApplication; -import org.baeldung.resttemplate.web.dto.Person; +import com.baeldung.resttemplate.RestTemplateConfigurationApplication; +import com.baeldung.resttemplate.web.dto.Person; import org.json.JSONException; import org.json.JSONObject; import org.junit.BeforeClass; diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java similarity index 90% rename from spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java index 60069cea71..688b6e9d56 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.web.handler; +package com.baeldung.web.handler; -import org.baeldung.resttemplate.web.exception.NotFoundException; -import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; -import org.baeldung.resttemplate.web.model.Bar; +import com.baeldung.resttemplate.web.exception.NotFoundException; +import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import com.baeldung.resttemplate.web.model.Bar; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java similarity index 88% rename from spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java index f93ba71666..ee01cb6a50 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; @@ -6,9 +6,9 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat import java.net.URI; -import org.baeldung.SpringTestConfig; -import org.baeldung.resttemplate.web.model.Employee; -import org.baeldung.resttemplate.web.service.EmployeeService; +import com.baeldung.SpringTestConfig; +import com.baeldung.resttemplate.web.model.Employee; +import com.baeldung.resttemplate.web.service.EmployeeService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -16,6 +16,7 @@ import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -28,7 +29,7 @@ import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class) -@ContextConfiguration(classes = SpringTestConfig.class) +@SpringBootTest(classes = SpringTestConfig.class) public class EmployeeServiceMockRestServiceServerUnitTest { private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceMockRestServiceServerUnitTest.class); diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java similarity index 84% rename from spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java index f4b391573a..6eb040414b 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java @@ -1,15 +1,13 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; -import org.baeldung.resttemplate.web.model.Employee; -import org.baeldung.resttemplate.web.service.EmployeeService; +import com.baeldung.resttemplate.web.model.Employee; +import com.baeldung.resttemplate.web.service.EmployeeService; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; import org.mockito.runners.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java b/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e52d249f0b..0000000000 --- a/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -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-scheduling/README.md b/spring-scheduling/README.md index bf34fb60de..4ee306c0e0 100644 --- a/spring-scheduling/README.md +++ b/spring-scheduling/README.md @@ -4,4 +4,4 @@ - [Guide to Spring Retry](https://www.baeldung.com/spring-retry) - [How To Do @Async in Spring](https://www.baeldung.com/spring-async) - [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) - +- [Remote Debugging with IntelliJ IDEA](https://www.baeldung.com/intellij-remote-debugging) diff --git a/spring-security-modules/spring-security-acl/pom.xml b/spring-security-modules/spring-security-acl/pom.xml index 3c613f9d92..5c04aaa9ca 100644 --- a/spring-security-modules/spring-security-acl/pom.xml +++ b/spring-security-modules/spring-security-acl/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/Application.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/Application.java similarity index 91% rename from spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/Application.java rename to spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/Application.java index 665ca64076..b18a3a6527 100644 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/Application.java +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.acl; +package com.baeldung.acl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/ACLContext.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/ACLContext.java similarity index 99% rename from spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/ACLContext.java rename to spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/ACLContext.java index 337e745c3c..cb60ef1d45 100644 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/ACLContext.java +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/ACLContext.java @@ -1,4 +1,4 @@ -package org.baeldung.acl.config; +package com.baeldung.acl.config; import javax.sql.DataSource; diff --git a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/AclMethodSecurityConfiguration.java similarity index 96% rename from spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java rename to spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/AclMethodSecurityConfiguration.java index e503cb1a41..1a8788b906 100644 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/AclMethodSecurityConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.acl.config; +package com.baeldung.acl.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/JPAPersistenceConfig.java similarity index 66% rename from spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java rename to spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/JPAPersistenceConfig.java index 24d170e56c..5f7fff5ff3 100644 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/config/JPAPersistenceConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.acl.config; +package com.baeldung.acl.config; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.Configuration; @@ -8,9 +8,9 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement -@EnableJpaRepositories(basePackages = "org.baeldung.acl.persistence.dao") -@PropertySource("classpath:org.baeldung.acl.datasource.properties") -@EntityScan(basePackages={ "org.baeldung.acl.persistence.entity" }) +@EnableJpaRepositories(basePackages = "com.baeldung.acl.persistence.dao") +@PropertySource("classpath:com.baeldung.acl.datasource.properties") +@EntityScan(basePackages={ "com.baeldung.acl.persistence.entity" }) public class JPAPersistenceConfig { } diff --git a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/dao/NoticeMessageRepository.java similarity index 88% rename from spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java rename to spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/dao/NoticeMessageRepository.java index 91a2af7d83..be1a0118fc 100644 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/dao/NoticeMessageRepository.java @@ -1,8 +1,8 @@ -package org.baeldung.acl.persistence.dao; +package com.baeldung.acl.persistence.dao; import java.util.List; -import org.baeldung.acl.persistence.entity.NoticeMessage; +import com.baeldung.acl.persistence.entity.NoticeMessage; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.springframework.security.access.prepost.PostAuthorize; diff --git a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/entity/NoticeMessage.java similarity index 92% rename from spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java rename to spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/entity/NoticeMessage.java index bd1e866f83..80c04146e4 100644 --- a/spring-security-modules/spring-security-acl/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java +++ b/spring-security-modules/spring-security-acl/src/main/java/com/baeldung/acl/persistence/entity/NoticeMessage.java @@ -1,4 +1,4 @@ -package org.baeldung.acl.persistence.entity; +package com.baeldung.acl.persistence.entity; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-modules/spring-security-acl/src/main/resources/acl-data.sql b/spring-security-modules/spring-security-acl/src/main/resources/acl-data.sql index a4e0011834..3b48c83f3c 100644 --- a/spring-security-modules/spring-security-acl/src/main/resources/acl-data.sql +++ b/spring-security-modules/spring-security-acl/src/main/resources/acl-data.sql @@ -4,7 +4,7 @@ INSERT INTO acl_sid (id, principal, sid) VALUES (3, 0, 'ROLE_EDITOR'); INSERT INTO acl_class (id, class) VALUES -(1, 'org.baeldung.acl.persistence.entity.NoticeMessage'); +(1, 'com.baeldung.acl.persistence.entity.NoticeMessage'); INSERT INTO system_message(id,content) VALUES (1,'First Level Message'), diff --git a/spring-security-modules/spring-security-acl/src/main/resources/org.baeldung.acl.datasource.properties b/spring-security-modules/spring-security-acl/src/main/resources/com.baeldung.acl.datasource.properties similarity index 100% rename from spring-security-modules/spring-security-acl/src/main/resources/org.baeldung.acl.datasource.properties rename to spring-security-modules/spring-security-acl/src/main/resources/com.baeldung.acl.datasource.properties diff --git a/spring-security-modules/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-acl/src/test/java/com/baeldung/SpringContextTest.java similarity index 86% rename from spring-security-modules/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-acl/src/test/java/com/baeldung/SpringContextTest.java index 74f26e2e5a..e60983733e 100644 --- a/spring-security-modules/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-acl/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.acl.Application; +import com.baeldung.acl.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-modules/spring-security-acl/src/test/java/org/baeldung/acl/SpringACLIntegrationTest.java b/spring-security-modules/spring-security-acl/src/test/java/com/baeldung/acl/SpringACLIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-acl/src/test/java/org/baeldung/acl/SpringACLIntegrationTest.java rename to spring-security-modules/spring-security-acl/src/test/java/com/baeldung/acl/SpringACLIntegrationTest.java index 1460d4f47b..dfdeafe059 100644 --- a/spring-security-modules/spring-security-acl/src/test/java/org/baeldung/acl/SpringACLIntegrationTest.java +++ b/spring-security-modules/spring-security-acl/src/test/java/com/baeldung/acl/SpringACLIntegrationTest.java @@ -1,12 +1,12 @@ -package org.baeldung.acl; +package com.baeldung.acl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.List; -import org.baeldung.acl.persistence.dao.NoticeMessageRepository; -import org.baeldung.acl.persistence.entity.NoticeMessage; +import com.baeldung.acl.persistence.dao.NoticeMessageRepository; +import com.baeldung.acl.persistence.entity.NoticeMessage; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -39,7 +39,7 @@ public class SpringACLIntegrationTest extends AbstractJUnit4SpringContextTests{ private static String EDITTED_CONTENT = "EDITED"; @Configuration - @ComponentScan("org.baeldung.acl.*") + @ComponentScan("com.baeldung.acl.*") public static class SpringConfig { } diff --git a/spring-security-modules/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-angular/server/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-security-modules/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-angular/server/src/test/java/com/baeldung/SpringContextTest.java index e61d512bca..49314c0575 100644 --- a/spring-security-modules/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-angular/server/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-cache-control/pom.xml b/spring-security-modules/spring-security-cache-control/pom.xml index acc37b41ef..743b3c291d 100644 --- a/spring-security-modules/spring-security-cache-control/pom.xml +++ b/spring-security-modules/spring-security-cache-control/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -23,41 +23,15 @@ spring-boot-starter-web - org.springframework.security - spring-security-core - - - org.springframework.security - spring-security-config - - - org.springframework.security - spring-security-web - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} + org.springframework.boot + spring-boot-starter-security - org.hamcrest - hamcrest - ${hamcrest.version} + org.springframework.boot + spring-boot-starter-test test - - - org.mockito - mockito-core - test - - - - org.springframework - spring-test - -
\ No newline at end of file diff --git a/spring-security-modules/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-security-modules/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/SpringContextTest.java index 8fbaa7169b..0cde5d829d 100644 --- a/spring-security-modules/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java b/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java index d6a1a97773..d4d24a4986 100644 --- a/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java +++ b/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java @@ -4,8 +4,8 @@ import static io.restassured.RestAssured.given; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; import io.restassured.http.ContentType; diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java index a084f14eca..67072b5d61 100644 --- a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/app/controller/TaskController.java @@ -1,8 +1,15 @@ package com.baeldung.app.controller; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -10,6 +17,8 @@ import org.springframework.web.bind.annotation.RequestMethod; import com.baeldung.app.entity.Task; import com.baeldung.app.service.TaskService; +import javax.servlet.http.HttpServletRequest; + @Controller @RequestMapping("api/tasks") public class TaskController { @@ -17,6 +26,9 @@ public class TaskController { @Autowired private TaskService taskService; + @Autowired(required = false) + private UserDetailsService userDetailsService; + @RequestMapping(method = RequestMethod.GET) public ResponseEntity> findAllTasks() { Iterable tasks = taskService.findAll(); @@ -30,4 +42,62 @@ public class TaskController { return ResponseEntity.ok().body(tasks); } + + /** + * Example of restricting specific endpoints to specific roles using @PreAuthorize. + */ + @GetMapping("/manager") + @PreAuthorize("hasRole('ROLE_MANAGER')") + public ResponseEntity> getAlManagerTasks() { + Iterable tasks = taskService.findAll(); + + return ResponseEntity.ok().body(tasks); + } + + /** + * Example of restricting specific endpoints to specific roles using SecurityContext. + */ + @GetMapping("/actuator") + public ResponseEntity> getAlActuatorTasks() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ACTUATOR"))) + { + return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + } + + Iterable tasks = taskService.findAll(); + + return ResponseEntity.ok().body(tasks); + } + + /** + * Example of restricting specific endpoints to specific roles using UserDetailsService. + */ + @GetMapping("/admin") + public ResponseEntity> getAlAdminTasks() { + if(userDetailsService != null) { + UserDetails details = userDetailsService.loadUserByUsername("pam"); + if (details != null && details.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + } + } + + Iterable tasks = taskService.findAll(); + + return ResponseEntity.ok().body(tasks); + } + + /** + * Example of restricting specific endpoints to specific roles using HttpServletRequest. + */ + @GetMapping("/admin2") + public ResponseEntity> getAlAdminTasksUsingServlet(HttpServletRequest request) { + if (!request.isUserInRole("ROLE_ADMIN")) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + } + + Iterable tasks = taskService.findAll(); + + return ResponseEntity.ok().body(tasks); + } } diff --git a/spring-security-modules/spring-security-kerberos/pom.xml b/spring-security-modules/spring-security-kerberos/pom.xml index 6846bdf063..51a48a78c6 100644 --- a/spring-security-modules/spring-security-kerberos/pom.xml +++ b/spring-security-modules/spring-security-kerberos/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/Application.java b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/Application.java similarity index 92% rename from spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/Application.java rename to spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/Application.java index 39c2b51356..37dbe7dab8 100644 --- a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/Application.java +++ b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/Application.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/config/WebSecurityConfig.java b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/config/WebSecurityConfig.java similarity index 97% rename from spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/config/WebSecurityConfig.java rename to spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/config/WebSecurityConfig.java index 49a1cf0a8e..c1c206e5c9 100644 --- a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/config/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/config/WebSecurityConfig.java @@ -1,6 +1,6 @@ -package org.baeldung.config; +package com.baeldung.config; -import org.baeldung.security.DummyUserDetailsService; +import com.baeldung.security.DummyUserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.FileSystemResource; diff --git a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/security/DummyUserDetailsService.java b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/security/DummyUserDetailsService.java similarity index 95% rename from spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/security/DummyUserDetailsService.java rename to spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/security/DummyUserDetailsService.java index 10d71fca8f..6ddd6c8969 100644 --- a/spring-security-modules/spring-security-kerberos/src/main/java/org/baeldung/security/DummyUserDetailsService.java +++ b/spring-security-modules/spring-security-kerberos/src/main/java/com/baeldung/security/DummyUserDetailsService.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; diff --git a/spring-security-modules/spring-security-ldap/pom.xml b/spring-security-modules/spring-security-ldap/pom.xml index f5e8856648..baed682186 100644 --- a/spring-security-modules/spring-security-ldap/pom.xml +++ b/spring-security-modules/spring-security-ldap/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -21,6 +21,10 @@ org.springframework.boot spring-boot-starter-security + + org.springframework.boot + spring-boot-starter-web + org.springframework.boot spring-boot-starter-thymeleaf diff --git a/spring-security-modules/spring-security-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/SampleLDAPApplication.java similarity index 62% rename from spring-security-modules/spring-security-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java rename to spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/SampleLDAPApplication.java index 5936aa30ef..2d619cccfa 100644 --- a/spring-security-modules/spring-security-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/SampleLDAPApplication.java @@ -1,8 +1,8 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -19,15 +19,4 @@ public class SampleLDAPApplication extends SpringBootServletInitializer { SpringApplication.run(SampleLDAPApplication.class, args); } - @Bean - public WebMvcConfigurerAdapter adapter() { - return new WebMvcConfigurerAdapter() { - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/login") - .setViewName("login"); - } - }; - } - } \ No newline at end of file diff --git a/spring-security-modules/spring-security-ldap/src/main/java/org/baeldung/security/SecurityConfig.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/SecurityConfig.java similarity index 53% rename from spring-security-modules/spring-security-ldap/src/main/java/org/baeldung/security/SecurityConfig.java rename to spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/SecurityConfig.java index 0d444e36ff..69f90d9de9 100644 --- a/spring-security-modules/spring-security-ldap/src/main/java/org/baeldung/security/SecurityConfig.java +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; @@ -14,13 +14,26 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.ldapAuthentication().userSearchBase("ou=people").userSearchFilter("(uid={0})").groupSearchBase("ou=groups").groupSearchFilter("(member={0})").contextSource().root("dc=baeldung,dc=com").ldif("classpath:users.ldif"); + auth.ldapAuthentication() + .userSearchBase("ou=people") + .userSearchFilter("(uid={0})") + .groupSearchBase("ou=groups") + .groupSearchFilter("(member={0})") + .contextSource() + .root("dc=baeldung,dc=com") + .ldif("classpath:users.ldif"); } @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().antMatchers("/", "/home").permitAll().anyRequest().authenticated(); - http.formLogin().loginPage("/login").permitAll().and().logout().logoutSuccessUrl("/"); + http + .authorizeRequests() + .antMatchers("/", "/home", "/css/**") + .permitAll() + .anyRequest() + .authenticated() + .and().formLogin().loginPage("/login").permitAll() + .and().logout().logoutSuccessUrl("/"); } } diff --git a/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/WebConfig.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..9809be1844 --- /dev/null +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/WebConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login") + .setViewName("login"); + } +} diff --git a/spring-security-modules/spring-security-ldap/src/main/java/org/baeldung/controller/MyController.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/controller/MyController.java similarity index 98% rename from spring-security-modules/spring-security-ldap/src/main/java/org/baeldung/controller/MyController.java rename to spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/controller/MyController.java index e347bd8633..7c746cfb31 100644 --- a/spring-security-modules/spring-security-ldap/src/main/java/org/baeldung/controller/MyController.java +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/controller/MyController.java @@ -1,4 +1,4 @@ -package org.baeldung.controller; +package com.baeldung.controller; import java.security.Principal; import java.util.Arrays; diff --git a/spring-security-modules/spring-security-ldap/src/main/resources/application.properties b/spring-security-modules/spring-security-ldap/src/main/resources/application.properties new file mode 100644 index 0000000000..3d0221bb7b --- /dev/null +++ b/spring-security-modules/spring-security-ldap/src/main/resources/application.properties @@ -0,0 +1 @@ +management.health.ldap.enabled=false \ No newline at end of file diff --git a/spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml index c13f65de5e..adfd603e54 100644 --- a/spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml @@ -10,6 +10,7 @@ + diff --git a/spring-security-modules/spring-security-ldap/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-ldap/src/test/java/com/baeldung/SpringContextTest.java similarity index 85% rename from spring-security-modules/spring-security-ldap/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-ldap/src/test/java/com/baeldung/SpringContextTest.java index 30ba7671d8..a15ca31980 100644 --- a/spring-security-modules/spring-security-ldap/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-ldap/src/test/java/com/baeldung/SpringContextTest.java @@ -1,5 +1,6 @@ -package org.baeldung; +package com.baeldung; +import com.baeldung.SampleLDAPApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-modules/spring-security-mvc-boot-1/pom.xml b/spring-security-modules/spring-security-mvc-boot-1/pom.xml index 7dfee200d4..7ad18376ec 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/pom.xml +++ b/spring-security-modules/spring-security-mvc-boot-1/pom.xml @@ -222,10 +222,10 @@ - org.baeldung.custom.Application + com.baeldung.roles.custom.Application - + 1.1.2 1.6.1 diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/AppConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/AppConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java index 8719e39a20..ab2cc71fec 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/AppConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.relationships; import java.util.Properties; @@ -19,7 +19,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @SpringBootApplication @PropertySource({"classpath:persistence-h2.properties", "classpath:application-defaults.properties"}) -@EnableJpaRepositories(basePackages = { "com.baeldung.data.repositories" }) +@EnableJpaRepositories(basePackages = {"com.baeldung.relationships.repositories"}) @EnableWebMvc @Import(SpringSecurityConfig.class) public class AppConfig extends WebMvcConfigurerAdapter { @@ -41,7 +41,7 @@ public class AppConfig extends WebMvcConfigurerAdapter { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.models" }); + em.setPackagesToScan(new String[] { "com.baeldung.relationships.models" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/SpringSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java similarity index 94% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/SpringSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java index ee13678a24..88814038a8 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/SpringSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.relationships; import javax.annotation.PostConstruct; import javax.sql.DataSource; @@ -18,8 +18,8 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.security.AuthenticationSuccessHandlerImpl; -import com.baeldung.security.CustomUserDetailsService; +import com.baeldung.relationships.security.AuthenticationSuccessHandlerImpl; +import com.baeldung.relationships.security.CustomUserDetailsService; @Configuration @EnableWebSecurity diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/AppUser.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/AppUser.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java index e48233f90a..2efd24e879 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/AppUser.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.relationships.models; import java.util.Date; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/Tweet.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/Tweet.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java index 54a96deaf3..d8496f89be 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/models/Tweet.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.relationships.models; import java.util.HashSet; import java.util.Set; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/TweetRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java similarity index 84% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/TweetRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java index 7d6446ed0d..4e4b16a151 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/TweetRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java @@ -1,11 +1,11 @@ -package com.baeldung.data.repositories; +package com.baeldung.relationships.repositories; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; -import com.baeldung.models.Tweet; +import com.baeldung.relationships.models.Tweet; public interface TweetRepository extends PagingAndSortingRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/UserRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/UserRepository.java similarity index 76% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/UserRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/UserRepository.java index 5240c683e0..883ea332f8 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/data/repositories/UserRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/repositories/UserRepository.java @@ -1,18 +1,15 @@ -package com.baeldung.data.repositories; +package com.baeldung.relationships.repositories; import java.util.Date; import java.util.List; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; -import com.baeldung.models.AppUser; +import com.baeldung.relationships.models.AppUser; public interface UserRepository extends CrudRepository { AppUser findByUsername(String username); diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AppUserPrincipal.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AppUserPrincipal.java similarity index 93% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AppUserPrincipal.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AppUserPrincipal.java index 195f9f7bf6..1ae7d95e41 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AppUserPrincipal.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AppUserPrincipal.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.relationships.security; import java.util.Collection; import java.util.Collections; @@ -8,7 +8,7 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; -import com.baeldung.models.AppUser; +import com.baeldung.relationships.models.AppUser; public class AppUserPrincipal implements UserDetails { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java similarity index 88% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java index 3fc2bc6559..1b85294467 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.relationships.security; import java.io.IOException; import java.util.Date; @@ -12,7 +12,7 @@ import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; -import com.baeldung.data.repositories.UserRepository; +import com.baeldung.relationships.repositories.UserRepository; @Component public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/CustomUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java similarity index 87% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/CustomUserDetailsService.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java index 016f4f7fa9..10c266bb74 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/security/CustomUserDetailsService.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.relationships.security; import javax.annotation.PostConstruct; @@ -9,8 +9,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.data.repositories.UserRepository; -import com.baeldung.models.AppUser; +import com.baeldung.relationships.repositories.UserRepository; +import com.baeldung.relationships.models.AppUser; @Service public class CustomUserDetailsService implements UserDetailsService { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/util/DummyContentUtil.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/util/DummyContentUtil.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/util/DummyContentUtil.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/util/DummyContentUtil.java index f1640264d2..b8e5192b48 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/util/DummyContentUtil.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/relationships/util/DummyContentUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.util; +package com.baeldung.relationships.util; import java.util.ArrayList; import java.util.Collection; @@ -10,8 +10,8 @@ import java.util.stream.IntStream; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import com.baeldung.models.AppUser; -import com.baeldung.models.Tweet; +import com.baeldung.relationships.models.AppUser; +import com.baeldung.relationships.models.Tweet; public class DummyContentUtil { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/Application.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/Application.java similarity index 88% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/Application.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/Application.java index e051e5a853..e7ace1f962 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/Application.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.custom; +package com.baeldung.roles.custom; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; @SpringBootApplication -@ComponentScan("org.baeldung.custom") +@ComponentScan("com.baeldung.roles.custom") @PropertySource("classpath:application-defaults.properties") public class Application extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MethodSecurityConfig.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MethodSecurityConfig.java index 6a005153dc..57ab8b120f 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MethodSecurityConfig.java @@ -1,7 +1,7 @@ -package org.baeldung.custom.config; +package com.baeldung.roles.custom.config; -import org.baeldung.custom.security.CustomMethodSecurityExpressionHandler; -import org.baeldung.custom.security.CustomPermissionEvaluator; +import com.baeldung.roles.custom.security.CustomMethodSecurityExpressionHandler; +import com.baeldung.roles.custom.security.CustomPermissionEvaluator; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MvcConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MvcConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MvcConfig.java index 58d11ea9ae..c99d1e38a5 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/MvcConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/MvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.config; +package com.baeldung.roles.custom.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/SecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java index 06357650dc..6bf04120ab 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.config; +package com.baeldung.roles.custom.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/SetupData.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/SetupData.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java index f0fcce3908..ab57e7436c 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/SetupData.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java @@ -1,16 +1,16 @@ -package org.baeldung.custom.persistence; +package com.baeldung.roles.custom.persistence; import java.util.Arrays; import java.util.HashSet; import javax.annotation.PostConstruct; -import org.baeldung.custom.persistence.dao.OrganizationRepository; -import org.baeldung.custom.persistence.dao.PrivilegeRepository; -import org.baeldung.custom.persistence.dao.UserRepository; -import org.baeldung.custom.persistence.model.Organization; -import org.baeldung.custom.persistence.model.Privilege; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.dao.OrganizationRepository; +import com.baeldung.roles.custom.persistence.dao.PrivilegeRepository; +import com.baeldung.roles.custom.persistence.dao.UserRepository; +import com.baeldung.roles.custom.persistence.model.Organization; +import com.baeldung.roles.custom.persistence.model.Privilege; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/OrganizationRepository.java similarity index 63% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/OrganizationRepository.java index 1319a7b9f8..2f585f3527 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/OrganizationRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.custom.persistence.dao; +package com.baeldung.roles.custom.persistence.dao; -import org.baeldung.custom.persistence.model.Organization; +import com.baeldung.roles.custom.persistence.model.Organization; import org.springframework.data.jpa.repository.JpaRepository; public interface OrganizationRepository extends JpaRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/PrivilegeRepository.java similarity index 62% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/PrivilegeRepository.java index c232bb986c..c83e0f505e 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/PrivilegeRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.custom.persistence.dao; +package com.baeldung.roles.custom.persistence.dao; -import org.baeldung.custom.persistence.model.Privilege; +import com.baeldung.roles.custom.persistence.model.Privilege; import org.springframework.data.jpa.repository.JpaRepository; public interface PrivilegeRepository extends JpaRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/UserRepository.java similarity index 74% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/UserRepository.java index 68dd1d756c..884a998219 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/dao/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.custom.persistence.dao; +package com.baeldung.roles.custom.persistence.dao; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Foo.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Foo.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java index f139382eea..3dbf48f7ce 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Foo.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.persistence.model; +package com.baeldung.roles.custom.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Organization.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Organization.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java index 1fdb88e320..0d0220b6b2 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Organization.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.persistence.model; +package com.baeldung.roles.custom.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Privilege.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Privilege.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java index ed3edd5085..60e0506641 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/Privilege.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.persistence.model; +package com.baeldung.roles.custom.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/User.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java similarity index 98% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/User.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java index c14ef034b4..219f40a3df 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/persistence/model/User.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.persistence.model; +package com.baeldung.roles.custom.persistence.model; import java.util.Set; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionHandler.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionHandler.java index 646f5a387f..76e94a9dd4 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import org.aopalliance.intercept.MethodInvocation; import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionRoot.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionRoot.java index b2f2be8cf5..dd9f6a5786 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomMethodSecurityExpressionRoot.java @@ -1,6 +1,6 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.security.access.expression.SecurityExpressionRoot; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.core.Authentication; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomPermissionEvaluator.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomPermissionEvaluator.java index f436b4488b..d69e405b28 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/CustomPermissionEvaluator.java @@ -1,4 +1,4 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import java.io.Serializable; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MySecurityExpressionRoot.java similarity index 98% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MySecurityExpressionRoot.java index 03d18cb755..8448ad9075 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MySecurityExpressionRoot.java @@ -1,11 +1,11 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Set; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.security.access.PermissionEvaluator; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserDetailsService.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserDetailsService.java index b9b40fbcb9..c6514d6c05 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserDetailsService.java @@ -1,7 +1,7 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; -import org.baeldung.custom.persistence.dao.UserRepository; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.dao.UserRepository; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserPrincipal.java similarity index 89% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserPrincipal.java index 7d57227316..41741c64f4 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/security/MyUserPrincipal.java @@ -1,11 +1,11 @@ -package org.baeldung.custom.security; +package com.baeldung.roles.custom.security; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.baeldung.custom.persistence.model.Privilege; -import org.baeldung.custom.persistence.model.User; +import com.baeldung.roles.custom.persistence.model.Privilege; +import com.baeldung.roles.custom.persistence.model.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/web/MainController.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/web/MainController.java similarity index 87% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/web/MainController.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/web/MainController.java index 74de45d1a8..beb12f7749 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/custom/web/MainController.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/custom/web/MainController.java @@ -1,9 +1,9 @@ -package org.baeldung.custom.web; +package com.baeldung.roles.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 com.baeldung.roles.custom.persistence.dao.OrganizationRepository; +import com.baeldung.roles.custom.persistence.model.Foo; +import com.baeldung.roles.custom.persistence.model.Organization; +import com.baeldung.roles.custom.security.MyUserPrincipal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/IpApplication.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/IpApplication.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/IpApplication.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/IpApplication.java index d77414c54e..b9a86fee3e 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/IpApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/IpApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.ip; +package com.baeldung.roles.ip; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; @SpringBootApplication -@ComponentScan("org.baeldung.ip") +@ComponentScan("com.baeldung.ip") @PropertySource("classpath:application-defaults.properties") public class IpApplication extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/CustomIpAuthenticationProvider.java similarity index 98% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/CustomIpAuthenticationProvider.java index 078dd81259..adcadb65e8 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/CustomIpAuthenticationProvider.java @@ -1,4 +1,4 @@ -package org.baeldung.ip.config; +package com.baeldung.roles.ip.config; import java.util.ArrayList; import java.util.HashSet; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java index 3a8032a734..46ba62afb3 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ip.config; +package com.baeldung.roles.ip.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityXmlConfig.java similarity index 78% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityXmlConfig.java index 1d22ca4c67..4b2cf43f6a 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityXmlConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ip.config; +package com.baeldung.roles.ip.config; //@Configuration diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/web/MainController.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java similarity index 94% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/web/MainController.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java index 940194c421..438b668c5f 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/ip/web/MainController.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java @@ -1,11 +1,11 @@ -package org.baeldung.ip.web; +package com.baeldung.roles.ip.web; import java.util.List; import javax.servlet.Filter; import javax.servlet.http.HttpServletRequest; -import org.baeldung.custom.persistence.model.Foo; +import com.baeldung.roles.custom.persistence.model.Foo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.web.FilterChainProxy; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/CustomAuthenticationProvider.java similarity index 89% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/CustomAuthenticationProvider.java index d7195ac358..5168e64b4a 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/CustomAuthenticationProvider.java @@ -1,7 +1,7 @@ -package org.baeldung.rolesauthorities; +package com.baeldung.roles.rolesauthorities; -import org.baeldung.rolesauthorities.model.User; -import org.baeldung.rolesauthorities.persistence.UserRepository; +import com.baeldung.roles.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.persistence.UserRepository; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java index b0dc0b7537..23104e5292 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities; +package com.baeldung.roles.rolesauthorities; import java.io.IOException; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyUserDetailsService.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyUserDetailsService.java index f38b867a75..18230ba794 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyUserDetailsService.java @@ -1,13 +1,13 @@ -package org.baeldung.rolesauthorities; +package com.baeldung.roles.rolesauthorities; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; -import org.baeldung.rolesauthorities.model.Role; -import org.baeldung.rolesauthorities.model.User; -import org.baeldung.rolesauthorities.persistence.UserRepository; +import com.baeldung.roles.rolesauthorities.model.Role; +import com.baeldung.roles.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.persistence.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/RolesAuthoritiesApplication.java similarity index 87% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/RolesAuthoritiesApplication.java index 3c4e6f7b5a..d3e54b4303 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/RolesAuthoritiesApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities; +package com.baeldung.roles.rolesauthorities; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -8,7 +8,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration -@ComponentScan("org.baeldung.rolesauthorities") +@ComponentScan("com.baeldung.rolesauthorities") public class RolesAuthoritiesApplication extends SpringBootServletInitializer { public static void main(String[] args) { System.setProperty("spring.profiles.default", "rolesauthorities"); diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/MvcConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/MvcConfig.java index c42958457e..61394b6178 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/MvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities.config; +package com.baeldung.roles.rolesauthorities.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java index 7624dd7d39..cb8476fcc7 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java @@ -1,7 +1,7 @@ -package org.baeldung.rolesauthorities.config; +package com.baeldung.roles.rolesauthorities.config; -import org.baeldung.rolesauthorities.CustomAuthenticationProvider; -import org.baeldung.rolesauthorities.persistence.UserRepository; +import com.baeldung.roles.rolesauthorities.CustomAuthenticationProvider; +import com.baeldung.roles.rolesauthorities.persistence.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -18,7 +18,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; @Configuration -@ComponentScan(basePackages = { "org.baeldung.rolesauthorities" }) +@ComponentScan(basePackages = {"com.baeldung.rolesauthorities"}) @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @@ -76,7 +76,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public DaoAuthenticationProvider authProvider() { - final CustomAuthenticationProvider authProvider + final CustomAuthenticationProvider authProvider = new CustomAuthenticationProvider(userRepository, userDetailsService); authProvider.setPasswordEncoder(encoder()); return authProvider; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java index ab2cd08610..507beaffa8 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities.model; +package com.baeldung.roles.rolesauthorities.model; import java.util.Collection; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Role.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Role.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java index ac33e32fcf..a284d92090 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/Role.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities.model; +package com.baeldung.roles.rolesauthorities.model; import java.util.Collection; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/User.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java similarity index 98% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/User.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java index dc1096541d..ebf0c9b310 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/model/User.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.rolesauthorities.model; +package com.baeldung.roles.rolesauthorities.model; import java.util.Collection; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/IUserService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/IUserService.java new file mode 100644 index 0000000000..be9cb911d7 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/IUserService.java @@ -0,0 +1,9 @@ +package com.baeldung.roles.rolesauthorities.persistence; + +import com.baeldung.roles.rolesauthorities.model.User; + +public interface IUserService { + + User findUserByEmail(String email); + +} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/PrivilegeRepository.java similarity index 65% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/PrivilegeRepository.java index 05d5f2b870..f8ba7def49 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/PrivilegeRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; -import org.baeldung.rolesauthorities.model.Privilege; +import com.baeldung.roles.rolesauthorities.model.Privilege; import org.springframework.data.jpa.repository.JpaRepository; public interface PrivilegeRepository extends JpaRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/RoleRepository.java similarity index 63% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/RoleRepository.java index 25e3b3a1f6..e5833712fe 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/RoleRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; -import org.baeldung.rolesauthorities.model.Role; +import com.baeldung.roles.rolesauthorities.model.Role; import org.springframework.data.jpa.repository.JpaRepository; public interface RoleRepository extends JpaRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/SetupDataLoader.java similarity index 93% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/SetupDataLoader.java index 46dad4f06d..140fc56e53 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/SetupDataLoader.java @@ -1,13 +1,13 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; -import org.baeldung.rolesauthorities.model.Privilege; -import org.baeldung.rolesauthorities.model.Role; -import org.baeldung.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.model.Privilege; +import com.baeldung.roles.rolesauthorities.model.Role; +import com.baeldung.roles.rolesauthorities.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserRepository.java similarity index 64% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserRepository.java index bca2953153..6801eec01d 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; -import org.baeldung.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java similarity index 77% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java index 3b16c78898..17770e5cd0 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java @@ -1,8 +1,8 @@ -package org.baeldung.rolesauthorities.persistence; +package com.baeldung.roles.rolesauthorities.persistence; import javax.transaction.Transactional; -import org.baeldung.rolesauthorities.model.User; +import com.baeldung.roles.rolesauthorities.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/MinuteBasedVoter.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/MinuteBasedVoter.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java index 2beda1e557..6970441a4e 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/MinuteBasedVoter.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java @@ -1,4 +1,4 @@ -package org.baeldung.voter; +package com.baeldung.roles.voter; import java.time.LocalDateTime; import java.util.Collection; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterApplication.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterApplication.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java index d2078e6115..d3e0652ae9 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.voter; +package com.baeldung.roles.voter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -7,7 +7,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration -@ComponentScan(basePackages = { "org.baeldung.voter" }) +@ComponentScan(basePackages = {"com.baeldung.voter"}) public class VoterApplication { public static void main(String[] args) { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterMvcConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java similarity index 71% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterMvcConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java index 8f41153f06..f11a4ae06c 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/VoterMvcConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java @@ -1,10 +1,8 @@ -package org.baeldung.voter; +package com.baeldung.roles.voter; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by ambrusadrianz on 30/09/2016. diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/WebSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/WebSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java index 84ed070e8e..8a0f438b49 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.voter; +package com.baeldung.roles.voter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -15,7 +15,6 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.access.expression.WebExpressionVoter; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import java.util.Arrays; import java.util.List; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/XmlSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/XmlSecurityConfig.java similarity index 60% rename from spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/XmlSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/XmlSecurityConfig.java index 8041585f42..0ef2ef51c7 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/voter/XmlSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/XmlSecurityConfig.java @@ -1,7 +1,4 @@ -package org.baeldung.voter; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +package com.baeldung.roles.voter; /** * Created by ambrusadrianz on 09/10/2016. diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java deleted file mode 100644 index 2c508cbd20..0000000000 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.rolesauthorities.persistence; - -import org.baeldung.rolesauthorities.model.User; - -public interface IUserService { - - User findUserByEmail(String email); - -} diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml index 0b334a3694..9f510280a1 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/resources/spring-security-custom-voter.xml @@ -22,12 +22,12 @@ - + - + diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java index b2def82c51..54120650d9 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java @@ -1,12 +1,11 @@ package com.baeldung.relationships; -import com.baeldung.AppConfig; -import com.baeldung.data.repositories.TweetRepository; -import com.baeldung.data.repositories.UserRepository; -import com.baeldung.models.AppUser; -import com.baeldung.models.Tweet; -import com.baeldung.security.AppUserPrincipal; -import com.baeldung.util.DummyContentUtil; +import com.baeldung.relationships.repositories.TweetRepository; +import com.baeldung.relationships.repositories.UserRepository; +import com.baeldung.relationships.models.AppUser; +import com.baeldung.relationships.models.Tweet; +import com.baeldung.relationships.security.AppUserPrincipal; +import com.baeldung.relationships.util.DummyContentUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/SpringContextTest.java similarity index 83% rename from spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/SpringContextTest.java index 2041249b71..7b23b878c8 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung.roles; -import org.baeldung.custom.Application; +import com.baeldung.roles.custom.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/ApplicationLiveTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java similarity index 94% rename from spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/ApplicationLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java index e199411e58..5a040b8dea 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/ApplicationLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java @@ -1,9 +1,9 @@ -package org.baeldung.web; +package com.baeldung.roles.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.baeldung.custom.persistence.model.Foo; +import com.baeldung.roles.custom.persistence.model.Foo; import io.restassured.RestAssured; import io.restassured.authentication.FormAuthConfig; @@ -13,7 +13,7 @@ import io.restassured.specification.RequestSpecification; import org.junit.Test; import org.springframework.http.MediaType; -// In order to execute these tests, org.baeldung.custom.Application needs to be running. +// In order to execute these tests, com.baeldung.custom.Application needs to be running. public class ApplicationLiveTest { @Test diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java index a69b52c0dd..df7645150f 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.roles.web; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -7,8 +7,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.http.HttpHeaders; -import org.baeldung.custom.Application; -import org.baeldung.custom.persistence.model.Foo; +import com.baeldung.roles.custom.Application; +import com.baeldung.roles.custom.persistence.model.Foo; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -59,7 +59,7 @@ public class CustomUserDetailsServiceIntegrationTest { @WithAnonymousUser public void givenAnonymous_whenRequestFoo_thenRetrieveUnauthorized() throws Exception { this.mvc.perform(get("/foos/1").with(csrf())) - .andExpect(status().isFound()); + .andExpect(status().isFound()); } @Test diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/IpLiveTest.java b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/IpLiveTest.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/IpLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/IpLiveTest.java index 761f5450f7..2d0e2e5402 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/test/java/org/baeldung/web/IpLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/test/java/com/baeldung/roles/web/IpLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.roles.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -8,7 +8,7 @@ import io.restassured.response.Response; import org.junit.Test; -// In order to execute these tests, org.baeldung.ip.IpApplication needs to be running. +// In order to execute these tests, com.baeldung.ip.IpApplication needs to be running. public class IpLiveTest { @Test diff --git a/spring-security-modules/spring-security-mvc-boot-2/pom.xml b/spring-security-modules/spring-security-mvc-boot-2/pom.xml index 565528e070..668eb04cd9 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/pom.xml +++ b/spring-security-modules/spring-security-mvc-boot-2/pom.xml @@ -222,16 +222,15 @@ - org.baeldung.custom.Application - - + + + com.baeldung.multiplelogin.MultipleLoginApplication - + - + 1.1.2 1.6.1 diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/CustomLogoutApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/CustomLogoutApplication.java new file mode 100644 index 0000000000..39d867b1f4 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/CustomLogoutApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.customlogouthandler; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CustomLogoutApplication { + + public static void main(String[] args) { + SpringApplication.run(CustomLogoutApplication.class, args); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java new file mode 100644 index 0000000000..c363effb4e --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/MvcConfiguration.java @@ -0,0 +1,55 @@ +package com.baeldung.customlogouthandler; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +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.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler; + +import com.baeldung.customlogouthandler.web.CustomLogoutHandler; + +@Configuration +@EnableWebSecurity +public class MvcConfiguration extends WebSecurityConfigurerAdapter { + + @Autowired + private DataSource dataSource; + + @Autowired + private CustomLogoutHandler logoutHandler; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.httpBasic() + .and() + .authorizeRequests() + .antMatchers(HttpMethod.GET, "/user/**") + .hasRole("USER") + .and() + .logout() + .logoutUrl("/user/logout") + .addLogoutHandler(logoutHandler) + .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)) + .permitAll() + .and() + .csrf() + .disable() + .formLogin() + .disable(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .usersByUsernameQuery("select login, password, true from users where login=?") + .authoritiesByUsernameQuery("select login, role from users where login=?"); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java new file mode 100644 index 0000000000..b86edc0dee --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/services/UserCache.java @@ -0,0 +1,35 @@ +package com.baeldung.customlogouthandler.services; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.springframework.stereotype.Service; + +import com.baeldung.customlogouthandler.user.User; + +@Service +public class UserCache { + + @PersistenceContext + private EntityManager entityManager; + + private final ConcurrentMap store = new ConcurrentHashMap<>(256); + + public User getByUserName(String userName) { + return store.computeIfAbsent(userName, k -> entityManager.createQuery("from User where login=:login", User.class) + .setParameter("login", k) + .getSingleResult()); + } + + public void evictUser(String userName) { + store.remove(userName); + } + + public int size() { + return store.size(); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/User.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/User.java new file mode 100644 index 0000000000..ca3a998c5c --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/User.java @@ -0,0 +1,61 @@ +package com.baeldung.customlogouthandler.user; + +import javax.persistence.*; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + @Column(unique = true) + private String login; + + private String password; + + private String role; + + private String language; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java new file mode 100644 index 0000000000..aa9a521b01 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/user/UserUtils.java @@ -0,0 +1,14 @@ +package com.baeldung.customlogouthandler.user; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +public class UserUtils { + + public static String getAuthenticatedUserName() { + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); + return auth != null ? ((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername() : null; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java new file mode 100644 index 0000000000..a89c9a570d --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/CustomLogoutHandler.java @@ -0,0 +1,28 @@ +package com.baeldung.customlogouthandler.web; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutHandler; +import org.springframework.stereotype.Service; + +import com.baeldung.customlogouthandler.services.UserCache; +import com.baeldung.customlogouthandler.user.UserUtils; + +@Service +public class CustomLogoutHandler implements LogoutHandler { + + private final UserCache userCache; + + public CustomLogoutHandler(UserCache userCache) { + this.userCache = userCache; + } + + @Override + public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + String userName = UserUtils.getAuthenticatedUserName(); + userCache.evictUser(userName); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java new file mode 100644 index 0000000000..b2d332a1bb --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/customlogouthandler/web/UserController.java @@ -0,0 +1,30 @@ +package com.baeldung.customlogouthandler.web; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.customlogouthandler.services.UserCache; +import com.baeldung.customlogouthandler.user.User; +import com.baeldung.customlogouthandler.user.UserUtils; + +@Controller +@RequestMapping(path = "/user") +public class UserController { + + private final UserCache userCache; + + public UserController(UserCache userCache) { + this.userCache = userCache; + } + + @GetMapping(path = "/language") + @ResponseBody + public String getLanguage() { + String userName = UserUtils.getAuthenticatedUserName(); + User user = userCache.getByUserName(userName); + return user.getLanguage(); + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java index 6936cdc560..d71885d73c 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.h2; +package com.baeldung.jdbcauthentication.h2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java index 8b8696f0b2..50dc5b6958 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.h2.config; +package com.baeldung.jdbcauthentication.h2.config; import javax.sql.DataSource; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/web/UserController.java similarity index 89% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/web/UserController.java index 0955061614..03271677a4 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/h2/web/UserController.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.h2.web; +package com.baeldung.jdbcauthentication.h2.web; import java.security.Principal; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java index 52934e0096..1f4c54e512 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.mysql; +package com.baeldung.jdbcauthentication.mysql; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java index 157c0be748..a0584818cd 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.mysql.config; +package com.baeldung.jdbcauthentication.mysql.config; import javax.sql.DataSource; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java similarity index 88% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java index f1060b5f78..ed15f8bfe6 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.mysql.web; +package com.baeldung.jdbcauthentication.mysql.web; import java.security.Principal; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java similarity index 90% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java index 2c4d1a5255..4b074ef51d 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.postgre; +package com.baeldung.jdbcauthentication.postgre; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java similarity index 93% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java index ba79635852..85dc9d364c 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.postgre.config; +package com.baeldung.jdbcauthentication.postgre.config; import javax.sql.DataSource; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java similarity index 88% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java index c8fd3812b1..da85a46562 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.postgre.web; +package com.baeldung.jdbcauthentication.postgre.web; import java.security.Principal; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/CustomAuthenticationProvider.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/CustomAuthenticationProvider.java index 1a89c362cd..97a8d8ac2a 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/CustomAuthenticationProvider.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import java.util.Collections; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthController.java similarity index 85% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthController.java index b63169bb00..0079c84c6c 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthController.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java index 1f641298c3..e1a437e9a9 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java index 3819e981a2..aa2ffc9046 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleauthproviders; +package com.baeldung.multipleauthproviders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java similarity index 92% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java index 847dab073e..4ed36f770f 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleentrypoints; +package com.baeldung.multipleentrypoints; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java similarity index 99% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java index dc89c83cde..b6155fc100 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleentrypoints; +package com.baeldung.multipleentrypoints; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/PagesController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/PagesController.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/PagesController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/PagesController.java index b3462d4061..ba5028aea7 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multipleentrypoints/PagesController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multipleentrypoints/PagesController.java @@ -1,4 +1,4 @@ -package org.baeldung.multipleentrypoints; +package com.baeldung.multipleentrypoints; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginApplication.java similarity index 85% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginApplication.java index 90bb5e4260..abba2ba339 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -7,7 +7,6 @@ import org.springframework.context.annotation.PropertySource; @SpringBootApplication @PropertySource("classpath:application-defaults.properties") -@ComponentScan("org.baeldung.multiplelogin") public class MultipleLoginApplication { public static void main(String[] args) { SpringApplication.run(MultipleLoginApplication.class, args); diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginMvcConfig.java similarity index 89% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginMvcConfig.java index 204b186411..86b3314c7c 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginMvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -6,14 +6,12 @@ import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import org.springframework.context.annotation.ComponentScan; @EnableWebMvc @Configuration -@ComponentScan("org.baeldung.controller") public class MultipleLoginMvcConfig implements WebMvcConfigurer { public MultipleLoginMvcConfig() { diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginSecurityConfig.java similarity index 99% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginSecurityConfig.java index 9962bf41a9..3d12951f39 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/MultipleLoginSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/UsersController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/UsersController.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/UsersController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/UsersController.java index 61d7da127c..03be0fd6b2 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/multiplelogin/UsersController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/multiplelogin/UsersController.java @@ -1,4 +1,4 @@ -package org.baeldung.multiplelogin; +package com.baeldung.multiplelogin; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/HttpsEnabledApplication.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/HttpsEnabledApplication.java index 17c249067c..f6a550ae54 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/HttpsEnabledApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.ssl; +package com.baeldung.ssl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/SecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/SecurityConfig.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/SecurityConfig.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/SecurityConfig.java index 92f92d8fc7..4bddf0592a 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/SecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.ssl; +package com.baeldung.ssl; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/WelcomeController.java b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/WelcomeController.java similarity index 74% rename from spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/WelcomeController.java rename to spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/WelcomeController.java index 72ad8abb85..2bd8c8cfde 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/main/java/org/baeldung/ssl/WelcomeController.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/java/com/baeldung/ssl/WelcomeController.java @@ -1,8 +1,7 @@ -package org.baeldung.ssl; +package com.baeldung.ssl; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; @Controller public class WelcomeController { diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-customlogouthandler.properties b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-customlogouthandler.properties new file mode 100644 index 0000000000..2cb766378d --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/main/resources/application-customlogouthandler.properties @@ -0,0 +1,5 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/test +spring.datasource.username=test +spring.datasource.password=test + +spring.jpa.hibernate.ddl-auto=create \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java new file mode 100644 index 0000000000..cd8a1a72d6 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/customlogouthandler/CustomLogoutHandlerIntegrationTest.java @@ -0,0 +1,108 @@ +package com.baeldung.customlogouthandler; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.jdbc.SqlGroup; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.customlogouthandler.services.UserCache; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = { CustomLogoutApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SqlGroup({ @Sql(value = "classpath:customlogouthandler/before.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD), @Sql(value = "classpath:customlogouthandler/after.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) }) +@TestPropertySource(locations="classpath:customlogouthandler/application.properties") +class CustomLogoutHandlerIntegrationTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Autowired + private UserCache userCache; + + @LocalServerPort + private int port; + + @Test + public void whenLogin_thenUseUserCache() { + // User cache should be empty on start + assertThat(userCache.size()).isEqualTo(0); + + // Request using first login + ResponseEntity response = restTemplate.withBasicAuth("user", "pass") + .getForEntity(getLanguageUrl(), String.class); + + assertThat(response.getBody()).contains("english"); + + // User cache must contain the user + assertThat(userCache.size()).isEqualTo(1); + + // Getting the session cookie + HttpHeaders requestHeaders = new HttpHeaders(); + requestHeaders.add("Cookie", response.getHeaders() + .getFirst(HttpHeaders.SET_COOKIE)); + + // Request with the session cookie + response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getBody()).contains("english"); + + // Logging out using the session cookies + response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode() + .value()).isEqualTo(200); + } + + @Test + public void whenLogout_thenCacheIsEmpty() { + // User cache should be empty on start + assertThat(userCache.size()).isEqualTo(0); + + // Request using first login + ResponseEntity response = restTemplate.withBasicAuth("user", "pass") + .getForEntity(getLanguageUrl(), String.class); + + assertThat(response.getBody()).contains("english"); + + // User cache must contain the user + assertThat(userCache.size()).isEqualTo(1); + + // Getting the session cookie + HttpHeaders requestHeaders = new HttpHeaders(); + requestHeaders.add("Cookie", response.getHeaders() + .getFirst(HttpHeaders.SET_COOKIE)); + + // Logging out using the session cookies + response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode() + .value()).isEqualTo(200); + + // User cache must be empty now + // this is the reaction on custom logout filter execution + assertThat(userCache.size()).isEqualTo(0); + + // Assert unauthorized request + response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); + assertThat(response.getStatusCode() + .value()).isEqualTo(401); + } + + private String getLanguageUrl() { + return "http://localhost:" + port + "/user/language"; + } + + private String getLogoutUrl() { + return "http://localhost:" + port + "/user/logout"; + } + +} diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/SpringContextTest.java similarity index 76% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/SpringContextTest.java index 659dad9155..5bd2a0ce27 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/SpringContextTest.java @@ -1,6 +1,5 @@ -package org.baeldung.jdbcauthentication.h2; +package com.baeldung.jdbcauthentication.h2; -import org.baeldung.jdbcauthentication.h2.H2JdbcAuthenticationApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java index 638e9d7919..12b5ca5867 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.h2.web; +package com.baeldung.jdbcauthentication.h2.web; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java index 261063cbb6..79bc84ea69 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.mysql.web; +package com.baeldung.jdbcauthentication.mysql.web; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java index 82bf6df8db..e6426a843e 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jdbcauthentication.postgre.web; +package com.baeldung.jdbcauthentication.postgre.web; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/HttpsApplicationIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/HttpsApplicationIntegrationTest.java index fe7883ec94..63d47e6a46 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/HttpsApplicationIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web; +package com.baeldung.web; import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; -import org.baeldung.ssl.HttpsEnabledApplication; +import com.baeldung.ssl.HttpsEnabledApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java index 9ef09f1f67..c5ef469fe8 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web; +package com.baeldung.web; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; -import org.baeldung.multipleauthproviders.MultipleAuthProvidersApplication; +import com.baeldung.multipleauthproviders.MultipleAuthProvidersApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleEntryPointsIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java rename to spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleEntryPointsIntegrationTest.java index 422be2ac88..352b4af244 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/java/com/baeldung/web/MultipleEntryPointsIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import org.junit.Before; import org.junit.Test; @@ -15,7 +15,7 @@ import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -import org.baeldung.multipleentrypoints.MultipleEntryPointsApplication; +import com.baeldung.multipleentrypoints.MultipleEntryPointsApplication; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/after.sql b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/after.sql new file mode 100644 index 0000000000..df6f312987 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/after.sql @@ -0,0 +1 @@ +delete from users; \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties new file mode 100644 index 0000000000..9edd853f2c --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/application.properties @@ -0,0 +1,5 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/test +spring.datasource.username=test +spring.datasource.password=test + +spring.jpa.hibernate.ddl-auto=create diff --git a/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/before.sql b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/before.sql new file mode 100644 index 0000000000..bb0a85f613 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-boot-2/src/test/resources/customlogouthandler/before.sql @@ -0,0 +1 @@ +insert into users (login, password, role, language) values ('user', '{noop}pass', 'ROLE_USER', 'english'); \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 76% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 19f49ea59d..728445952e 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -1,7 +1,9 @@ -package org.baeldung.security; +package com.baeldung.security; import java.io.IOException; import java.util.Collection; +import java.util.HashMap; +import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -47,26 +49,21 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu } protected String determineTargetUrl(final Authentication authentication) { - boolean isUser = false; - boolean isAdmin = false; + + Map roleTargetUrlMap = new HashMap<>(); + roleTargetUrlMap.put("ROLE_USER", "/homepage.html"); + roleTargetUrlMap.put("ROLE_ADMIN", "/console.html"); + final Collection authorities = authentication.getAuthorities(); for (final GrantedAuthority grantedAuthority : authorities) { - if (grantedAuthority.getAuthority().equals("ROLE_USER")) { - isUser = true; - break; - } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { - isAdmin = true; - break; + + String authorityName = grantedAuthority.getAuthority(); + if(roleTargetUrlMap.containsKey(authorityName)) { + return roleTargetUrlMap.get(authorityName); } } - if (isUser) { - return "/homepage.html"; - } else if (isAdmin) { - return "/console.html"; - } else { - throw new IllegalStateException(); - } + throw new IllegalStateException(); } /** @@ -83,12 +80,4 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); } - public void setRedirectStrategy(final RedirectStrategy redirectStrategy) { - this.redirectStrategy = redirectStrategy; - } - - protected RedirectStrategy getRedirectStrategy() { - return redirectStrategy; - } - } diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MvcConfig.java similarity index 87% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MvcConfig.java index db6141d43e..583825a66a 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MvcConfig.java @@ -1,8 +1,8 @@ -package org.baeldung.spring; +package com.baeldung.spring; -import org.baeldung.web.interceptor.LoggerInterceptor; -import org.baeldung.web.interceptor.SessionTimerInterceptor; -import org.baeldung.web.interceptor.UserInterceptor; +import com.baeldung.web.interceptor.LoggerInterceptor; +import com.baeldung.web.interceptor.SessionTimerInterceptor; +import com.baeldung.web.interceptor.UserInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -16,7 +16,7 @@ import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration -@ComponentScan("org.baeldung.web.controller") +@ComponentScan("com.baeldung.web.controller") public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MyUserDetailsService.java new file mode 100644 index 0000000000..ee80ad12d7 --- /dev/null +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/MyUserDetailsService.java @@ -0,0 +1,32 @@ +package com.baeldung.spring; + +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.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.*; + +@Service +public class MyUserDetailsService implements UserDetailsService { + + private Map roles = new HashMap<>(); + + @PostConstruct + public void init() { + roles.put("admin", new User("admin", "{noop}admin1", getAuthority("ROLE_ADMIN"))); + roles.put("user", new User("user", "{noop}user1", getAuthority("ROLE_USER"))); + } + + @Override + public UserDetails loadUserByUsername(String username) { + return roles.get(username); + } + + private List getAuthority(String role) { + return Collections.singletonList(new SimpleGrantedAuthority(role)); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/SecSecurityConfig.java similarity index 55% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/SecSecurityConfig.java index ebe23950a7..9cee909ad4 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -1,11 +1,10 @@ -package org.baeldung.spring; +package com.baeldung.spring; -import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; +import com.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @@ -15,7 +14,7 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand //@ImportResource({ "classpath:webSecurityConfig.xml" }) @EnableWebSecurity public class SecSecurityConfig extends WebSecurityConfigurerAdapter { - + public SecSecurityConfig() { super(); } @@ -26,43 +25,34 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { return super.authenticationManagerBean(); } - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.inMemoryAuthentication() - .withUser("user1").password("{noop}user1Pass").roles("USER") - .and() - .withUser("admin1").password("{noop}admin1Pass").roles("ADMIN"); - // @formatter:on - } - @Override protected void configure(final HttpSecurity http) throws Exception { // @formatter:off - http.authorizeRequests() - .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*").permitAll() - .anyRequest().authenticated() - + http + .authorizeRequests() + .antMatchers("/anonymous*").anonymous() + .antMatchers("/login*").permitAll() + .anyRequest().authenticated() + .and() .formLogin() - .loginPage("/login.html") - .loginProcessingUrl("/login") - .successHandler(myAuthenticationSuccessHandler()) - .failureUrl("/login.html?error=true") - + .loginPage("/login.html") + .loginProcessingUrl("/login") + .successHandler(myAuthenticationSuccessHandler()) + .failureUrl("/login.html?error=true") + .and() - .logout().deleteCookies("JSESSIONID") - + .logout().deleteCookies("JSESSIONID") + .and() - .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400) - + .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400) + .and() - .csrf().disable() + .csrf().disable() ; // @formatter:on } - + @Bean public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){ return new MySimpleUrlAuthenticationSuccessHandler(); diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/BankController.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/BankController.java similarity index 96% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/BankController.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/BankController.java index 1a4322c611..c4bbde21f2 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/BankController.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/BankController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/FooController.java similarity index 96% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/FooController.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/FooController.java index 5a3c85d220..6f9268c976 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/FooController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; @@ -7,7 +7,7 @@ import java.util.List; import javax.servlet.http.HttpServletResponse; -import org.baeldung.web.dto.Foo; +import com.baeldung.web.dto.Foo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.http.HttpStatus; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/LoginController.java similarity index 97% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/LoginController.java index 99bf345a41..8a823cdf7e 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/LoginController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/PrintUserController.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/PrintUserController.java similarity index 95% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/PrintUserController.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/PrintUserController.java index 78f164c7f1..9623471f12 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/PrintUserController.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/controller/PrintUserController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/dto/Foo.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/dto/Foo.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/dto/Foo.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/dto/Foo.java index 02283e7df9..b349e75b72 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/dto/Foo.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/dto/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.web.dto; import java.io.Serializable; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/LoggerInterceptor.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/LoggerInterceptor.java index 7c68d3e9c7..b54fda5a82 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/LoggerInterceptor.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/LoggerInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import com.google.common.base.Strings; import org.slf4j.Logger; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/SessionTimerInterceptor.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/SessionTimerInterceptor.java index 90199347b4..38e852305c 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/SessionTimerInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/UserInterceptor.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java rename to spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/UserInterceptor.java index 6b808d885e..cd64a20842 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java +++ b/spring-security-modules/spring-security-mvc-custom/src/main/java/com/baeldung/web/interceptor/UserInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml index e79e14abeb..eb2dc719f5 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml @@ -22,7 +22,7 @@ - + @@ -33,8 +33,7 @@ - - \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-custom/src/main/webapp/WEB-INF/web.xml b/spring-security-modules/spring-security-mvc-custom/src/main/webapp/WEB-INF/web.xml index e805828809..61fd248f53 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-modules/spring-security-mvc-custom/src/main/webapp/WEB-INF/web.xml @@ -20,7 +20,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring diff --git a/spring-security-modules/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/SpringContextTest.java similarity index 82% rename from spring-security-modules/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/SpringContextTest.java index cfef3322dc..3a73503bca 100644 --- a/spring-security-modules/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/SpringContextTest.java @@ -1,7 +1,7 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.SecSecurityConfig; +import com.baeldung.spring.MvcConfig; +import com.baeldung.spring.SecSecurityConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -9,8 +9,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration @ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration public class SpringContextTest { @Test diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfAbstractIntegrationTest.java similarity index 95% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index 44424bf7f9..97972b7358 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -1,11 +1,11 @@ -package org.baeldung.security.csrf; +package com.baeldung.security.csrf; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import javax.servlet.Filter; -import org.baeldung.web.dto.Foo; +import com.baeldung.web.dto.Foo; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfDisabledIntegrationTest.java similarity index 87% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfDisabledIntegrationTest.java index 1d16e08514..a1c8be9daf 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfDisabledIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.security.csrf; +package com.baeldung.security.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.security.spring.SecurityWithoutCsrfConfig; -import org.baeldung.spring.MvcConfig; +import com.baeldung.security.spring.SecurityWithoutCsrfConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfEnabledIntegrationTest.java similarity index 88% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index 9d882973bd..87e5005e17 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -1,11 +1,11 @@ -package org.baeldung.security.csrf; +package com.baeldung.security.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.security.spring.SecurityWithCsrfConfig; -import org.baeldung.spring.MvcConfig; +import com.baeldung.security.spring.SecurityWithCsrfConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityConfig.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityConfig.java index 23d13a0ff1..438cec38bb 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.security.spring; +package com.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityIntegrationTest.java similarity index 96% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityIntegrationTest.java index afc86bd74c..002ba8df3e 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/ManualSecurityIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityIntegrationTest.java @@ -1,11 +1,11 @@ -package org.baeldung.security.spring; +package com.baeldung.security.spring; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import javax.servlet.http.HttpSession; -import org.baeldung.spring.MvcConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java index ca401622c0..9b3ac50546 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.security.spring; +package com.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java similarity index 98% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java index 1067c70fea..4a1263b498 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.security.spring; +package com.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java similarity index 91% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index c33c9a04e8..9e850861bf 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.security.spring.SecurityWithoutCsrfConfig; -import org.baeldung.spring.MvcConfig; +import com.baeldung.security.spring.SecurityWithoutCsrfConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java similarity index 93% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index bdc1be2c44..07bc22f184 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java @@ -1,12 +1,12 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import javax.servlet.http.HttpSession; -import org.baeldung.security.spring.SecurityWithoutCsrfConfig; -import org.baeldung.spring.MvcConfig; +import com.baeldung.security.spring.SecurityWithoutCsrfConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/UserInterceptorIntegrationTest.java similarity index 92% rename from spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java rename to spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/UserInterceptorIntegrationTest.java index a85fd999a6..b7547cb23a 100644 --- a/spring-security-modules/spring-security-mvc-custom/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-custom/src/test/java/com/baeldung/web/interceptor/UserInterceptorIntegrationTest.java @@ -1,10 +1,10 @@ -package org.baeldung.web.interceptor; +package com.baeldung.web.interceptor; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.security.spring.SecurityWithoutCsrfConfig; -import org.baeldung.spring.MvcConfig; +import com.baeldung.security.spring.SecurityWithoutCsrfConfig; +import com.baeldung.spring.MvcConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java similarity index 97% rename from spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java rename to spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java index c51c0a0bc8..1b9ffc3db8 100644 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/basic/MyBasicAuthenticationEntryPoint.java +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -1,4 +1,4 @@ -package org.baeldung.basic; +package com.baeldung.basic; import java.io.IOException; import java.io.PrintWriter; diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java similarity index 98% rename from spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java rename to spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java index 1e6f213305..67c2d6031f 100644 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryDigestAuth.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package com.baeldung.client; import org.apache.http.HttpHost; import org.apache.http.client.AuthCache; diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/ClientConfig.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/ClientConfig.java similarity index 94% rename from spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/ClientConfig.java rename to spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/ClientConfig.java index f305321f13..b7145daaea 100644 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/ClientConfig.java +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/ClientConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; @@ -7,7 +7,7 @@ import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.baeldung.client.HttpComponentsClientHttpRequestFactoryDigestAuth; +import com.baeldung.client.HttpComponentsClientHttpRequestFactoryDigestAuth; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/MvcConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/MvcConfig.java rename to spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/MvcConfig.java index 74c11478ee..0d9962cda0 100644 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/MvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/SecSecurityConfig.java similarity index 83% rename from spring-security-modules/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/SecSecurityConfig.java index 4ce80dab9f..4ba9d47f8d 100644 --- a/spring-security-modules/spring-security-rest-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource({ "classpath:webSecurityConfig.xml" }) -@ComponentScan("org.baeldung.security") +@ComponentScan("com.baeldung.security") public class SecSecurityConfig { public SecSecurityConfig() { diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/main/webapp/WEB-INF/web.xml b/spring-security-modules/spring-security-mvc-digest-auth/src/main/webapp/WEB-INF/web.xml index bebd5d9cd3..25f5a91932 100644 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/main/webapp/WEB-INF/web.xml @@ -16,7 +16,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/SpringContextTest.java similarity index 78% rename from spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/SpringContextTest.java index cd2b796308..080935c8c1 100644 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/SpringContextTest.java @@ -1,8 +1,8 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.spring.ClientConfig; -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.SecSecurityConfig; +import com.baeldung.spring.ClientConfig; +import com.baeldung.spring.MvcConfig; +import com.baeldung.spring.SecSecurityConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java b/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/client/RawClientLiveTest.java similarity index 94% rename from spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java rename to spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/client/RawClientLiveTest.java index e8dcf82ebc..de6dca3ec4 100644 --- a/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java +++ b/spring-security-modules/spring-security-mvc-digest-auth/src/test/java/com/baeldung/client/RawClientLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package com.baeldung.client; import java.io.IOException; @@ -6,7 +6,7 @@ import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.baeldung.spring.ClientConfig; +import com.baeldung.spring.ClientConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml b/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml index eff3e1a1a1..8b8b4cd2f3 100644 --- a/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml +++ b/spring-security-modules/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml @@ -23,7 +23,7 @@ - + diff --git a/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml index 8a83bf5e93..543792fadc 100644 --- a/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml @@ -25,11 +25,11 @@ - + - + - + diff --git a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java index 4cf3b736ea..dfc83a40b0 100644 --- a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml" }) @WebAppConfiguration public class SpringContextTest { @Test diff --git a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java index 1235e2e69f..e2b444de20 100644 --- a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java @@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml" }) @WebAppConfiguration public class RedirectionSecurityIntegrationTest { diff --git a/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml b/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml deleted file mode 100644 index 4568d319b8..0000000000 --- a/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/controller/MyController.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/controller/MyController.java similarity index 96% rename from spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/controller/MyController.java rename to spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/controller/MyController.java index 51202225ee..0ef07a2c19 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/controller/MyController.java +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/controller/MyController.java @@ -1,4 +1,4 @@ -package org.baeldung.controller; +package com.baeldung.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 99% rename from spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 22fd2cdcb6..5d3c59be11 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.io.IOException; import java.util.Collection; diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityRole.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityRole.java similarity index 78% rename from spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityRole.java rename to spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityRole.java index e41e7a4c4f..ffe385996d 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityRole.java +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityRole.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; /** * Simple enum of Security Roles available. diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java similarity index 90% rename from spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java rename to spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java index 75f782e7dc..98eb4cd41c 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/service/MyUserDetailsService.java similarity index 96% rename from spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java rename to spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/service/MyUserDetailsService.java index e6c77110b3..34782bdfab 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/service/MyUserDetailsService.java @@ -1,8 +1,8 @@ -package org.baeldung.service; +package com.baeldung.service; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.baeldung.security.SecurityRole; +import com.baeldung.security.SecurityRole; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/MvcConfig.java similarity index 95% rename from spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/MvcConfig.java rename to spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/MvcConfig.java index d4e0c55004..6fa3b522e7 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/MvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -14,7 +14,7 @@ import org.springframework.web.servlet.view.JstlView; * Spring Web Configuration. */ @EnableWebMvc -@ComponentScan("org.baeldung") +@ComponentScan("com.baeldung") @Configuration public class MvcConfig extends WebMvcConfigurerAdapter { diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/PersistenceConfig.java similarity index 97% rename from spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/PersistenceConfig.java rename to spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/PersistenceConfig.java index 02308e64fb..fe7b82b63d 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import javax.sql.DataSource; diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/SecurityConfig.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/SecurityConfig.java similarity index 95% rename from spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/SecurityConfig.java rename to spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/SecurityConfig.java index 2d9bb8e731..d3cfff81cb 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/SecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/java/com/baeldung/spring/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/web.xml b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/web.xml index aa52205420..11b922a801 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/web.xml @@ -19,7 +19,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring diff --git a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/com/baeldung/SpringContextTest.java similarity index 78% rename from spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/com/baeldung/SpringContextTest.java index 8113ed0fbe..bf4951c83a 100644 --- a/spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-persisted-remember-me/src/test/java/com/baeldung/SpringContextTest.java @@ -1,8 +1,8 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityConfig; +import com.baeldung.spring.MvcConfig; +import com.baeldung.spring.PersistenceConfig; +import com.baeldung.spring.SecurityConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-security-modules/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-socket/src/test/java/com/baeldung/SpringContextTest.java similarity index 97% rename from spring-security-modules/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-mvc-socket/src/test/java/com/baeldung/SpringContextTest.java index 7b9c738904..4ef4948601 100644 --- a/spring-security-modules/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-socket/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-mvc/README.md b/spring-security-modules/spring-security-mvc/README.md index 7d1a492cd3..bb4cfe1a4f 100644 --- a/spring-security-modules/spring-security-mvc/README.md +++ b/spring-security-modules/spring-security-mvc/README.md @@ -10,6 +10,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [HttpSessionListener Example – Monitoring](https://www.baeldung.com/httpsessionlistener_with_metrics) - [Control the Session with Spring Security](https://www.baeldung.com/spring-security-session) +- [The Clear-Site-Data Header in Spring Security](https://www.baeldung.com/spring-security-clear-site-data-header) ### Build the Project diff --git a/spring-security-modules/spring-security-mvc/pom.xml b/spring-security-modules/spring-security-mvc/pom.xml index 7da047707a..517aa83270 100644 --- a/spring-security-modules/spring-security-mvc/pom.xml +++ b/spring-security-modules/spring-security-mvc/pom.xml @@ -64,9 +64,36 @@ org.springframework.security spring-security-test + ${spring.mvc.version} test + + org.springframework.security + spring-security-web + ${spring.mvc.version} + + + org.springframework.security + spring-security-config + ${spring.mvc.version} + + + org.springframework + spring-webmvc + ${spring.mvc.version} + + + javax.servlet + javax.servlet-api + ${javax.version} + + + + 5.2.2.RELEASE + 4.0.1 + + diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/LogoutClearSiteDataController.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/LogoutClearSiteDataController.java new file mode 100644 index 0000000000..fcf78ac82f --- /dev/null +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/LogoutClearSiteDataController.java @@ -0,0 +1,16 @@ +package com.baeldung.clearsitedata; + +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +@Controller +public class LogoutClearSiteDataController { + + @GetMapping(value = "/baeldung/logout") + public ResponseEntity logout(@PathVariable String name) { + return ResponseEntity.ok().build(); + } + +} diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/SpringSecurityConfig.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/SpringSecurityConfig.java new file mode 100644 index 0000000000..13011da9e4 --- /dev/null +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/SpringSecurityConfig.java @@ -0,0 +1,35 @@ +package com.baeldung.clearsitedata; + + +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.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; + +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.CACHE; +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.COOKIES; +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + + http.csrf() + .disable() + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/perform_login") + .defaultSuccessUrl("/homepage.html", true) + .and() + .logout().logoutUrl("/baeldung/logout") + .addLogoutHandler(new HeaderWriterLogoutHandler( + new ClearSiteDataHeaderWriter(CACHE, COOKIES, STORAGE))); + } +} diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/WebConfig.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/WebConfig.java new file mode 100644 index 0000000000..a523efa554 --- /dev/null +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/clearsitedata/WebConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.clearsitedata; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.CacheControl; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.mvc.WebContentInterceptor; + +import java.util.concurrent.TimeUnit; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = {"com.baeldung.clearsitedata"}) +public class WebConfig implements WebMvcConfigurer { +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java index e2224996c2..ce122db609 100644 --- a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java @@ -13,7 +13,7 @@ public final class MetricRegistrySingleton { public static final MetricRegistry metrics = new MetricRegistry(); static { - Logger logger = LoggerFactory.getLogger("org.baeldung.monitoring"); + Logger logger = LoggerFactory.getLogger("com.baeldung.monitoring"); final Slf4jReporter reporter = Slf4jReporter.forRegistry(metrics).outputTo(logger).convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build(); reporter.start(5, TimeUnit.MINUTES); } diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/session/web/config/MainWebAppInitializer.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/session/web/config/MainWebAppInitializer.java new file mode 100644 index 0000000000..f85f9f3fb0 --- /dev/null +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/session/web/config/MainWebAppInitializer.java @@ -0,0 +1,16 @@ +package com.baeldung.session.web.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +import org.springframework.web.WebApplicationInitializer; + +public class MainWebAppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext sc) throws ServletException { + sc.getSessionCookieConfig().setHttpOnly(true); + sc.getSessionCookieConfig().setSecure(true); + } + +} diff --git a/spring-security-modules/spring-security-mvc/src/main/webapp/WEB-INF/web.xml b/spring-security-modules/spring-security-mvc/src/main/webapp/WEB-INF/web.xml index 88087c92ed..ec6bc0d3b4 100644 --- a/spring-security-modules/spring-security-mvc/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-modules/spring-security-mvc/src/main/webapp/WEB-INF/web.xml @@ -30,7 +30,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring @@ -60,7 +60,7 @@ - + 1 diff --git a/spring-security-modules/spring-security-rest/README.md b/spring-security-modules/spring-security-rest/README.md index f7e91b85dc..26c101d32c 100644 --- a/spring-security-modules/spring-security-rest/README.md +++ b/spring-security-modules/spring-security-rest/README.md @@ -8,12 +8,11 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: -- [Spring REST Service Security](https://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/) + - [Setting Up Swagger 2 with a Spring REST API](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Custom Error Message Handling for REST API](https://www.baeldung.com/global-error-handler-in-a-spring-rest-api) - [Spring Security Context Propagation with @Async](https://www.baeldung.com/spring-security-async-principal-propagation) - [Servlet 3 Async Support with Spring MVC and Spring Security](https://www.baeldung.com/spring-mvc-async-security) - [Intro to Spring Security Expressions](https://www.baeldung.com/spring-security-expressions) -- [Spring Security for a REST API](https://www.baeldung.com/securing-a-restful-web-service-with-spring-security) - [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) - [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/ApiError.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/ApiError.java similarity index 97% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/ApiError.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/ApiError.java index 8a1ddd8882..0fba2deca5 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/ApiError.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/ApiError.java @@ -1,4 +1,4 @@ -package org.baeldung.errorhandling; +package com.baeldung.errorhandling; import java.util.Arrays; import java.util.List; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/CustomRestExceptionHandler.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/CustomRestExceptionHandler.java similarity index 99% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/CustomRestExceptionHandler.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/CustomRestExceptionHandler.java index cd4d58e60c..02bc0a2512 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/errorhandling/CustomRestExceptionHandler.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/errorhandling/CustomRestExceptionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.errorhandling; +package com.baeldung.errorhandling; import java.util.ArrayList; import java.util.List; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/persistence/model/Foo.java similarity index 97% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/persistence/model/Foo.java index 05a7c7b9a0..d85cca1dcc 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/persistence/model/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package com.baeldung.persistence.model; import java.io.Serializable; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityJavaConfig.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityJavaConfig.java similarity index 92% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityJavaConfig.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityJavaConfig.java index 74623080b5..d20198c2bb 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityJavaConfig.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityJavaConfig.java @@ -1,8 +1,8 @@ -package org.baeldung.security; +package com.baeldung.security; -import org.baeldung.security.web.MySavedRequestAwareAuthenticationSuccessHandler; -import org.baeldung.security.web.RestAuthenticationEntryPoint; -import org.baeldung.web.error.CustomAccessDeniedHandler; +import com.baeldung.security.web.MySavedRequestAwareAuthenticationSuccessHandler; +import com.baeldung.security.web.RestAuthenticationEntryPoint; +import com.baeldung.web.error.CustomAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -20,7 +20,7 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) -@ComponentScan("org.baeldung.security") +@ComponentScan("com.baeldung.security") public class SecurityJavaConfig extends WebSecurityConfigurerAdapter { @Autowired diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java similarity index 90% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java index 33978962bb..77e70d5b84 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/SecurityWebApplicationInitializer.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/SecurityWebApplicationInitializer.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java similarity index 98% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java index c56568e979..2d74ed9dca 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.security.web; +package com.baeldung.security.web; import java.io.IOException; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/RestAuthenticationEntryPoint.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/RestAuthenticationEntryPoint.java similarity index 95% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/RestAuthenticationEntryPoint.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/RestAuthenticationEntryPoint.java index 643e2f0575..162ee46727 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/security/web/RestAuthenticationEntryPoint.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/security/web/RestAuthenticationEntryPoint.java @@ -1,4 +1,4 @@ -package org.baeldung.security.web; +package com.baeldung.security.web; import java.io.IOException; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/ClientWebConfig.java similarity index 91% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/ClientWebConfig.java index 8e20358a5a..db24817f5b 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/SecurityXmlConfig.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/SecurityXmlConfig.java similarity index 77% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/SecurityXmlConfig.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/SecurityXmlConfig.java index 0830a1ebe1..92f7cea784 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/SecurityXmlConfig.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/SecurityXmlConfig.java @@ -1,10 +1,10 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.ComponentScan; // @Configuration // @ImportResource({ "classpath:webSecurityConfig.xml" }) -@ComponentScan("org.baeldung.security") +@ComponentScan("com.baeldung.security") public class SecurityXmlConfig { public SecurityXmlConfig() { diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/WebConfig.java similarity index 95% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/WebConfig.java index dba07dc4e5..84b211a9bd 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/spring/WebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -12,7 +12,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration -@ComponentScan("org.baeldung.web") +@ComponentScan("com.baeldung.web") @EnableWebMvc @EnableAsync public class WebConfig implements WebMvcConfigurer { diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/swagger2/SwaggerConfig.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/swagger2/SwaggerConfig.java similarity index 94% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/swagger2/SwaggerConfig.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/swagger2/SwaggerConfig.java index 67c760353d..c8c4227ebf 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/swagger2/SwaggerConfig.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/swagger2/SwaggerConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.swagger2; +package com.baeldung.swagger2; import static com.google.common.collect.Lists.newArrayList; @@ -25,7 +25,7 @@ public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).select() - .apis(RequestHandlerSelectors.basePackage("org.baeldung.web.controller")) + .apis(RequestHandlerSelectors.basePackage("com.baeldung.web.controller")) .paths(PathSelectors.ant("/foos/*")) .build() .apiInfo(apiInfo()) diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/AsyncController.java similarity index 94% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/AsyncController.java index f6f1c392cb..c2123913c6 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/AsyncController.java @@ -1,11 +1,11 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import java.util.concurrent.Callable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.baeldung.web.service.AsyncService; +import com.baeldung.web.service.AsyncService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/CustomController.java similarity index 90% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/CustomController.java index 7d40b9bb8d..d833d3af7a 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/CustomController.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.RequestMapping; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/FooController.java similarity index 94% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/FooController.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/FooController.java index f914f82215..033bf2d1e3 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/FooController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; @@ -6,7 +6,7 @@ import java.util.List; import javax.servlet.http.HttpServletResponse; -import org.baeldung.persistence.model.Foo; +import com.baeldung.persistence.model.Foo; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/RootController.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/RootController.java similarity index 94% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/RootController.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/RootController.java index 4253ed7a59..3abbe8a309 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/controller/RootController.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/controller/RootController.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.RequestMapping; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/CustomAccessDeniedHandler.java similarity index 96% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/CustomAccessDeniedHandler.java index cc07417427..6c686cd9e9 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/CustomAccessDeniedHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.web.error; +package com.baeldung.web.error; import java.io.IOException; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java similarity index 99% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java index 9ff4f040fe..9e6ae78d27 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.web.error; +package com.baeldung.web.error; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java similarity index 92% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java index 14b61f9832..fd002efc28 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/exception/MyResourceNotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.exception; +package com.baeldung.web.exception; public final class MyResourceNotFoundException extends RuntimeException { diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncService.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncService.java similarity index 81% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncService.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncService.java index 1ba4dfa4cb..ee07313ee8 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncService.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncService.java @@ -1,4 +1,4 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; import java.util.concurrent.Callable; diff --git a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncServiceImpl.java b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncServiceImpl.java similarity index 97% rename from spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncServiceImpl.java rename to spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncServiceImpl.java index d6d7f53dd7..8aebbc3234 100644 --- a/spring-security-modules/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncServiceImpl.java +++ b/spring-security-modules/spring-security-rest/src/main/java/com/baeldung/web/service/AsyncServiceImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.web.service; +package com.baeldung.web.service; import java.util.concurrent.Callable; diff --git a/spring-security-modules/spring-security-rest/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-rest/src/main/resources/webSecurityConfig.xml index edd3cba39c..2c0a0bc774 100644 --- a/spring-security-modules/spring-security-rest/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-rest/src/main/resources/webSecurityConfig.xml @@ -30,7 +30,7 @@ + class="com.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler" /> diff --git a/spring-security-modules/spring-security-rest/src/main/webapp/WEB-INF/web.xml b/spring-security-modules/spring-security-rest/src/main/webapp/WEB-INF/web.xml index 3195603837..663c17bc56 100644 --- a/spring-security-modules/spring-security-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-modules/spring-security-rest/src/main/webapp/WEB-INF/web.xml @@ -17,7 +17,7 @@ contextConfigLocation - org.baeldung.spring + com.baeldung.spring diff --git a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/SpringContextTest.java similarity index 77% rename from spring-security-modules/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-rest/src/test/java/com/baeldung/SpringContextTest.java index 11586ce670..bcc66558cb 100644 --- a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/SpringContextTest.java @@ -1,8 +1,8 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.security.SecurityJavaConfig; -import org.baeldung.spring.ClientWebConfig; -import org.baeldung.spring.WebConfig; +import com.baeldung.security.SecurityJavaConfig; +import com.baeldung.spring.ClientWebConfig; +import com.baeldung.spring.WebConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/errorhandling/FooLiveTest.java b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/errorhandling/FooLiveTest.java similarity index 96% rename from spring-security-modules/spring-security-rest/src/test/java/org/baeldung/errorhandling/FooLiveTest.java rename to spring-security-modules/spring-security-rest/src/test/java/com/baeldung/errorhandling/FooLiveTest.java index 8d1db5736f..e08a24676a 100644 --- a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/errorhandling/FooLiveTest.java +++ b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/errorhandling/FooLiveTest.java @@ -1,10 +1,9 @@ -package org.baeldung.errorhandling; +package com.baeldung.errorhandling; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.baeldung.errorhandling.ApiError; -import org.baeldung.web.TestConfig; +import com.baeldung.web.TestConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.http.HttpStatus; diff --git a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerIntegrationTest.java b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/AsyncControllerIntegrationTest.java similarity index 87% rename from spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerIntegrationTest.java rename to spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/AsyncControllerIntegrationTest.java index 1e5e1b7d85..bf93c14f1f 100644 --- a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerIntegrationTest.java +++ b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/AsyncControllerIntegrationTest.java @@ -1,9 +1,9 @@ -package org.baeldung.web; +package com.baeldung.web; -import org.baeldung.security.SecurityJavaConfig; -import org.baeldung.spring.ClientWebConfig; -import org.baeldung.spring.WebConfig; -import org.baeldung.web.controller.AsyncController; +import com.baeldung.security.SecurityJavaConfig; +import com.baeldung.spring.ClientWebConfig; +import com.baeldung.spring.WebConfig; +import com.baeldung.web.controller.AsyncController; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/SwaggerLiveTest.java similarity index 95% rename from spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java rename to spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/SwaggerLiveTest.java index 792b3e28ce..3f86b63503 100644 --- a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java +++ b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/SwaggerLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import static org.junit.Assert.assertEquals; diff --git a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/TestConfig.java similarity index 89% rename from spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java rename to spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/TestConfig.java index 61bd6e776b..ddb7240611 100644 --- a/spring-security-modules/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java +++ b/spring-security-modules/spring-security-rest/src/test/java/com/baeldung/web/TestConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -7,7 +7,7 @@ import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; @Configuration -@ComponentScan({ "org.baeldung.web" }) +@ComponentScan({ "com.baeldung.web" }) public class TestConfig { @Bean diff --git a/spring-security-modules/spring-security-sso/pom.xml b/spring-security-modules/spring-security-sso/pom.xml index 3d9c1bf595..4e5bb49aa3 100644 --- a/spring-security-modules/spring-security-sso/pom.xml +++ b/spring-security-modules/spring-security-sso/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-security-sso 1.0.0-SNAPSHOT spring-security-sso diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/pom.xml b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/pom.xml index 933cb6a2b2..3537c01e46 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/pom.xml +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/pom.xml @@ -7,7 +7,7 @@ war - org.baeldung + com.baeldung spring-security-sso 1.0.0-SNAPSHOT diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthServerConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthServerConfig.java similarity index 98% rename from spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthServerConfig.java rename to spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthServerConfig.java index 0835f3d721..9a6400abdf 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthServerConfig.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthServerConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthorizationServerApplication.java similarity index 95% rename from spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java rename to spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthorizationServerApplication.java index b74d2f144c..5cfcb2bb5b 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/AuthorizationServerApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/SecurityConfig.java similarity index 98% rename from spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/SecurityConfig.java rename to spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/SecurityConfig.java index 2254de8e39..29c7549753 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/UserController.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/UserController.java similarity index 92% rename from spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/UserController.java rename to spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/UserController.java index 28128f9d97..80415fbd30 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/org/baeldung/config/UserController.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/main/java/com/baeldung/config/UserController.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import java.security.Principal; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/SpringContextTest.java similarity index 86% rename from spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/SpringContextTest.java index f677f683b2..1f07837da9 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.config.AuthorizationServerApplication; +import com.baeldung.config.AuthorizationServerApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/UserInfoEndpointLiveTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/UserInfoEndpointLiveTest.java similarity index 99% rename from spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/UserInfoEndpointLiveTest.java rename to spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/UserInfoEndpointLiveTest.java index ffdb1df8fe..104f980dd2 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/UserInfoEndpointLiveTest.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-auth-server/src/test/java/com/baeldung/UserInfoEndpointLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import static org.junit.Assert.assertEquals; import java.util.HashMap; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md index 0227d9ac70..3aa092edb8 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md +++ b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/README.md @@ -1,4 +1,3 @@ ## Relevant articles: -- [Introduction to SPNEGO/Kerberos Authentication in Spring](https://www.baeldung.com/spring-security-kerberos) - [Spring Security Kerberos Integration](https://www.baeldung.com/spring-security-kerberos-integration) diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/pom.xml b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/pom.xml index 88b9354538..0864ead1c4 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/pom.xml +++ b/spring-security-modules/spring-security-sso/spring-security-sso-kerberos/pom.xml @@ -6,7 +6,7 @@ spring-security-sso-kerberos - org.baeldung + com.baeldung spring-security-sso 1.0.0-SNAPSHOT diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/pom.xml b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/pom.xml index 10592a5e92..0645ba3593 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/pom.xml +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/pom.xml @@ -7,7 +7,7 @@ war - org.baeldung + com.baeldung spring-security-sso 1.0.0-SNAPSHOT diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiApplication.java similarity index 95% rename from spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java rename to spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiApplication.java index 0c20853aed..ca178cfa7e 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiSecurityConfig.java similarity index 96% rename from spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java rename to spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiSecurityConfig.java index de81ada9e0..7ef1392659 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiWebConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiWebConfig.java similarity index 97% rename from spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiWebConfig.java rename to spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiWebConfig.java index c17bb85173..ae5008daa3 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiWebConfig.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/main/java/com/baeldung/config/UiWebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/com/baeldung/SpringContextTest.java similarity index 88% rename from spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/com/baeldung/SpringContextTest.java index 61a2a022ed..1eeab34e94 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui-2/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.config.UiApplication; +import com.baeldung.config.UiApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/pom.xml b/spring-security-modules/spring-security-sso/spring-security-sso-ui/pom.xml index 2f0ac3a42e..d34317a4b0 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui/pom.xml +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui/pom.xml @@ -7,7 +7,7 @@ war - org.baeldung + com.baeldung spring-security-sso 1.0.0-SNAPSHOT diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiApplication.java similarity index 95% rename from spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java rename to spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiApplication.java index 07d875d805..16d94d6d80 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiSecurityConfig.java similarity index 96% rename from spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java rename to spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiSecurityConfig.java index de81ada9e0..7ef1392659 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiWebConfig.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiWebConfig.java similarity index 97% rename from spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiWebConfig.java rename to spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiWebConfig.java index c17bb85173..ae5008daa3 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiWebConfig.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/main/java/com/baeldung/config/UiWebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/com/baeldung/SpringContextTest.java similarity index 88% rename from spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/com/baeldung/SpringContextTest.java index 61a2a022ed..1eeab34e94 100644 --- a/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-sso/spring-security-sso-ui/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.config.UiApplication; +import com.baeldung.config.UiApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-modules/spring-security-x509/README.md b/spring-security-modules/spring-security-x509/README.md index b1eb0debf5..da431d862c 100644 --- a/spring-security-modules/spring-security-x509/README.md +++ b/spring-security-modules/spring-security-x509/README.md @@ -4,3 +4,10 @@ This module contains articles about X.509 authentication with Spring Security ### Relevant Articles: - [X.509 Authentication in Spring Security](https://www.baeldung.com/x-509-authentication-in-spring-security) + +###### Note for the [X.509 Authentication in Spring Security](https://www.baeldung.com/x-509-authentication-in-spring-security): +All the ready to use certificates are located in the [store](store) directory. The application is already configured to use these files. +This means the app works out of the box. + +However, it's highly recommended that you follow the article step by step and generate all the needed files by yourself. +This will let you understand the topic more deeply. \ No newline at end of file diff --git a/spring-security-modules/spring-security-x509/keystore/Makefile b/spring-security-modules/spring-security-x509/keystore/Makefile deleted file mode 100644 index 2cd7c55c5b..0000000000 --- a/spring-security-modules/spring-security-x509/keystore/Makefile +++ /dev/null @@ -1,92 +0,0 @@ -PASSWORD=changeit -KEYSTORE=keystore.jks -HOSTNAME=localhost -CLIENTNAME=cid -CLIENT_PRIVATE_KEY="${CLIENTNAME}_pk" - -# CN = Common Name -# OU = Organization Unit -# O = Organization Name -# L = Locality Name -# ST = State Name -# C = Country (2-letter Country Code) -# E = Email -DNAME_CA='CN=Baeldung CA,OU=baeldung.com,O=Baeldung,L=SomeCity,ST=SomeState,C=CC' -# For server certificates, the Common Name (CN) must be the hostname -DNAME_HOST='CN=$(HOSTNAME),OU=baeldung.com,O=Baeldung,L=SomeCity,ST=SomeState,C=CC' -DNAME_CLIENT='CN=$(CLIENTNAME),OU=baeldung.com,O=Baeldung,L=SomeCity,ST=SomeState,C=CC' -TRUSTSTORE=truststore.jks - -all: clean create-keystore add-host create-truststore add-client - -create-keystore: - # Generate a certificate authority (CA) - keytool -genkey -alias ca -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \ - -keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \ - -validity 3650 -dname $(DNAME_CA) \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - -add-host: - # Generate a host certificate - keytool -genkey -alias $(HOSTNAME) -ext san=dns:localhost,ip:127.0.0.1 \ - -keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \ - -validity 3650 -dname $(DNAME_HOST) \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - # Generate a host certificate signing request - keytool -certreq -alias $(HOSTNAME) -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \ - -keyalg RSA -keysize 4096 -sigalg SHA512withRSA \ - -validity 3650 -file "$(HOSTNAME).csr" \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - # Generate signed certificate with the certificate authority - keytool -gencert -alias ca -ext san=dns:localhost,ip:127.0.0.1 \ - -validity 3650 -sigalg SHA512withRSA \ - -infile "$(HOSTNAME).csr" -outfile "$(HOSTNAME).crt" -rfc \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - # Import signed certificate into the keystore - keytool -import -trustcacerts -alias $(HOSTNAME) -ext san=dns:localhost,ip:127.0.0.1 \ - -file "$(HOSTNAME).crt" \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - -export-authority: - # Export certificate authority - keytool -export -alias ca -ext san=dns:localhost,ip:127.0.0.1 -file ca.crt -rfc \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - - -create-truststore: export-authority - # Import certificate authority into a new truststore - keytool -import -trustcacerts -noprompt -alias ca -ext san=dns:localhost,ip:127.0.0.1 -file ca.crt \ - -keystore $(TRUSTSTORE) -storepass $(PASSWORD) - -add-client: - # Generate client certificate - keytool -genkey -alias $(CLIENT_PRIVATE_KEY) -ext san=dns:localhost,ip:127.0.0.1 \ - -keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \ - -validity 3650 -dname $(DNAME_CLIENT) \ - -keystore $(TRUSTSTORE) -storepass $(PASSWORD) - # Generate a host certificate signing request - keytool -certreq -alias $(CLIENT_PRIVATE_KEY) -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \ - -keyalg RSA -keysize 4096 -sigalg SHA512withRSA \ - -validity 3650 -file "$(CLIENTNAME).csr" \ - -keystore $(TRUSTSTORE) -storepass $(PASSWORD) - # Generate signed certificate with the certificate authority - keytool -gencert -alias ca -ext san=dns:localhost,ip:127.0.0.1 \ - -validity 3650 -sigalg SHA512withRSA \ - -infile "$(CLIENTNAME).csr" -outfile "$(CLIENTNAME).crt" -rfc \ - -keystore $(KEYSTORE) -storepass $(PASSWORD) - # Import signed certificate into the truststore - keytool -import -trustcacerts -alias $(CLIENTNAME) -ext san=dns:localhost,ip:127.0.0.1 \ - -file "$(CLIENTNAME).crt" \ - -keystore $(TRUSTSTORE) -storepass $(PASSWORD) - # Export private certificate for importing into a browser - keytool -importkeystore -srcalias $(CLIENT_PRIVATE_KEY) -ext san=dns:localhost,ip:127.0.0.1 \ - -srckeystore $(TRUSTSTORE) -srcstorepass $(PASSWORD) \ - -destkeystore "$(CLIENTNAME).p12" -deststorepass $(PASSWORD) \ - -deststoretype PKCS12 - # Delete client private key as truststore should not contain any private keys - keytool -delete -alias $(CLIENT_PRIVATE_KEY) \ - -keystore $(TRUSTSTORE) -storepass $(PASSWORD) - -clean: - # Remove generated artifacts - find . \( -name "$(CLIENTNAME)*" -o -name "$(HOSTNAME)*" -o -name "$(KEYSTORE)" -o -name "$(TRUSTSTORE)" -o -name ca.crt \) -type f -exec rm -f {} \; diff --git a/spring-security-modules/spring-security-x509/keystore/keystore.jks b/spring-security-modules/spring-security-x509/keystore/keystore.jks deleted file mode 100644 index 044a820c39..0000000000 Binary files a/spring-security-modules/spring-security-x509/keystore/keystore.jks and /dev/null differ diff --git a/spring-security-modules/spring-security-x509/pom.xml b/spring-security-modules/spring-security-x509/pom.xml index a4ff908eed..d4132f058d 100644 --- a/spring-security-modules/spring-security-x509/pom.xml +++ b/spring-security-modules/spring-security-x509/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties index f293d6712d..0ba5fa1b8c 100644 --- a/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties +++ b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties @@ -1,8 +1,8 @@ -server.ssl.key-store=../keystore/keystore.jks +server.ssl.key-store=../store/keystore.jks server.ssl.key-store-password=changeit server.ssl.key-alias=localhost server.ssl.key-password=changeit server.ssl.enabled=true server.port=8443 -security.user.name=Admin -security.user.password=admin \ No newline at end of file +spring.security.user.name=Admin +spring.security.user.password=admin \ No newline at end of file diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/SpringContextTest.java index 5c65dd3e8a..1c89f706ab 100644 --- a/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java index 050423238e..18bbfba835 100644 --- a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java +++ b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/java/com/baeldung/spring/security/x509/X509AuthenticationServer.java @@ -23,7 +23,11 @@ public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().authenticated().and().x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)").userDetailsService(userDetailsService()); + http.authorizeRequests().anyRequest().authenticated() + .and() + .x509() + .subjectPrincipalRegex("CN=(.*?)(?:,|$)") + .userDetailsService(userDetailsService()); } @Bean @@ -31,7 +35,7 @@ public class X509AuthenticationServer extends WebSecurityConfigurerAdapter { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - if (username.equals("cid")) { + if (username.equals("Bob")) { return new User(username, "", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); } throw new UsernameNotFoundException("User not found!"); diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties index 174eba9f98..fc2fc89396 100644 --- a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties +++ b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties @@ -1,11 +1,11 @@ -server.ssl.key-store=../keystore/keystore.jks +server.ssl.key-store=../store/keystore.jks server.ssl.key-store-password=changeit server.ssl.key-alias=localhost server.ssl.key-password=changeit server.ssl.enabled=true server.port=8443 -security.user.name=Admin -security.user.password=admin -server.ssl.trust-store=../keystore/truststore.jks +spring.security.user.name=Admin +spring.security.user.password=admin +server.ssl.trust-store=../store/truststore.jks server.ssl.trust-store-password=changeit server.ssl.client-auth=need \ No newline at end of file diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks deleted file mode 100644 index 044a820c39..0000000000 Binary files a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/keystore.jks and /dev/null differ diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/SpringContextTest.java index 5c65dd3e8a..1c89f706ab 100644 --- a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-modules/spring-security-x509/store/clientBob.p12 b/spring-security-modules/spring-security-x509/store/clientBob.p12 new file mode 100644 index 0000000000..b5de8ab129 Binary files /dev/null and b/spring-security-modules/spring-security-x509/store/clientBob.p12 differ diff --git a/spring-security-modules/spring-security-x509/store/keystore.jks b/spring-security-modules/spring-security-x509/store/keystore.jks new file mode 100644 index 0000000000..c317c1d5ba Binary files /dev/null and b/spring-security-modules/spring-security-x509/store/keystore.jks differ diff --git a/spring-security-modules/spring-security-x509/store/localhost.ext b/spring-security-modules/spring-security-x509/store/localhost.ext new file mode 100644 index 0000000000..45324cc75a --- /dev/null +++ b/spring-security-modules/spring-security-x509/store/localhost.ext @@ -0,0 +1,5 @@ +authorityKeyIdentifier=keyid,issuer +basicConstraints=CA:FALSE +subjectAltName = @alt_names +[alt_names] +DNS.1 = localhost diff --git a/spring-security-modules/spring-security-x509/store/rootCA.crt b/spring-security-modules/spring-security-x509/store/rootCA.crt new file mode 100644 index 0000000000..b2ab681744 --- /dev/null +++ b/spring-security-modules/spring-security-x509/store/rootCA.crt @@ -0,0 +1,30 @@ +-----BEGIN CERTIFICATE----- +MIIFDzCCAvegAwIBAgIUDmhG1yLlF83ydOWPit8/MYNbaC8wDQYJKoZIhvcNAQEL +BQAwFzEVMBMGA1UEAwwMQmFlbGR1bmcuY29tMB4XDTIwMDQyMjE1MzEyMFoXDTMw +MDQyMDE1MzEyMFowFzEVMBMGA1UEAwwMQmFlbGR1bmcuY29tMIICIjANBgkqhkiG +9w0BAQEFAAOCAg8AMIICCgKCAgEAmkOSeQRQBQdoJio7Odm19kKVm4Y1ju1zscGM +LBWQ4GU8d3Y5AiOVzHtYUbKyJvmmUSYOH/mYdQ8F5nKKaXhTz92LIMnSXnusAqdD +YSvKa+mBoMLsd4Gl9lljipTvRwkkPlPXGVBDEVzXPf32l+5YxpGZzyVyj0WYT1cP +sZyThbOwue4h6gwer4SZ0HNPSts8TG7oiA4UTZSN5hhhbJmRBc87Xz+hJOMayZp6 +HA3tGTlrTkP/Vc3nii/G9tBeydmTTKj+BGFQW4qzDG6nJVvYyB4iri4ActREREGD +ycPS7SVXqEcA4rvSMR7DYoHVLkOg0uiQDWtj4zYcN9qgWVjcnIlUSPxrCgdJbakl +lRzrVpbkdlOC3hFSytoOBmCPS56gJ5npeLFh6IoPPdoXJwIXIJ1twCWtKzvlvlzb +DkMDytRVk2LYjh7IvtAWPTz5QofRdd2fW6iAWPdWbwcnq1xjO5BT8uGj+zOiA19/ +T2YebwD+pLAUM2w0ykLm+bH+DiSRa76wpKxuo6sSUefkeEt8Avojwh8nNbEOvXhf +El4zyimwTlfUYnaKEllUjRWVPhQPGCeCBHe1ES8UFf8hqGS2LRjKAZK70OcFdLyd +18sas/EXkNbd+Mpgata/zO9Oy/3h+xY426T5bPAt+wU38yMUaE+z5BS84m2GOtuQ +nC3a/HcCAwEAAaNTMFEwHQYDVR0OBBYEFFyRjr/LWlOZHv7JU7kQ1g76nq4SMB8G +A1UdIwQYMBaAFFyRjr/LWlOZHv7JU7kQ1g76nq4SMA8GA1UdEwEB/wQFMAMBAf8w +DQYJKoZIhvcNAQELBQADggIBAJWjUR/HBw5f7ogfyCVK/5fJutOFIIHqzNhExvDe +5wu9msPRAj+5ruGHtMWwOKm5qT82gZKJnAVct8XZXTIHU8mKS5Lbk02hu3e2tR/0 +RCzH4TCCD3fDJaW/jAZyU3oPtvcCaSmPwibG7SvDXtUvSSwCW8Omg7WqhnSWGUOn +WH3105lw8UKRTg57CaNu0GunqO4r0GcrgVShNKjCvNv7nGcP3+KWouZekBdn/iY5 +3Q8llL8WUMOHRwH6Raa6CV+vckCthUSpJdBAgGN44QtkA0iL/afVuE7VuTqsnCBA +nbOz/ssZOP0TUVYwoRiDN50gJdB8IKMHZu9Px2m7fJuGgZ7QDe56+tePypgM9KDq +yx4MKMP3Qc5xLE4pGM9SI1sGo+waW0+gPShNECHY4z8fOHw5bn+J1mrEWQbHfMGg +Z/352qps5Hd6PljLAHmWAJL2nXS2zlXbccdYuv4ZtNIeDUT8eX/9NuJdXrITq9QQ +oSBmyzH1bUJi2/mULcFy0Ibcu+OY/r8t67NrGKwLPLyozScwnFQE9SZR9d2cu6sC +yxQtcd68vdvAIEDTk4DcSldeT44HIJ7RYQuBNZ5NU3SngMLDleec/3AZSUXTExFW +TrbMTb+djM+XcTkRyO0wO0MYpjKGqN3sAGfppx0G9kgmJ9HB38nZfvqj3G1L9YFQ +6kSA +-----END CERTIFICATE----- diff --git a/spring-security-modules/spring-security-x509/store/truststore.jks b/spring-security-modules/spring-security-x509/store/truststore.jks new file mode 100644 index 0000000000..1d0d200580 Binary files /dev/null and b/spring-security-modules/spring-security-x509/store/truststore.jks differ diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 579d2327e8..42a414afdc 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-session 1.0.0-SNAPSHOT spring-session diff --git a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-jdbc/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java rename to spring-session/spring-session-jdbc/src/test/java/com/baeldung/SpringContextTest.java index b69855ba38..8f6c2f2889 100644 --- a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-session/spring-session-jdbc/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/SpringContextTest.java similarity index 96% rename from spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java rename to spring-session/spring-session-mongodb/src/test/java/com/baeldung/SpringContextTest.java index cc935b8cfb..babcdb2ccf 100644 --- a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import com.baeldung.springsessionmongodb.SpringSessionMongoDBApplication; import org.junit.Test; diff --git a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-session/spring-session-redis/src/test/java/com/baeldung/SpringContextLiveTest.java similarity index 96% rename from spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextLiveTest.java rename to spring-session/spring-session-redis/src/test/java/com/baeldung/SpringContextLiveTest.java index 3a4f14e9e6..2e33255e01 100644 --- a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextLiveTest.java +++ b/spring-session/spring-session-redis/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java b/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java rename to spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java index ff22398ca4..8dc2455e63 100644 --- a/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-sleuth/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index 9403b70636..d0987329c0 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -58,6 +58,28 @@ + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + 0.14.0 + + + + generate + + + + + WSDL + ${project.basedir}/src/main/java + com.baeldung.springsoap.client.gen + ${project.basedir}/src/main/resources + + countries.wsdl + + + diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java new file mode 100644 index 0000000000..e0b9172ece --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClient.java @@ -0,0 +1,26 @@ +package com.baeldung.springsoap.client; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ws.client.core.support.WebServiceGatewaySupport; + +import com.baeldung.springsoap.client.gen.GetCountryRequest; +import com.baeldung.springsoap.client.gen.GetCountryResponse; + +public class CountryClient extends WebServiceGatewaySupport { + + private static final Logger logger = LoggerFactory.getLogger(CountryClient.class); + + public GetCountryResponse getCountry(String country) { + + GetCountryRequest request = new GetCountryRequest(); + request.setName(country); + + logger.info("Requesting information for " + country); + + GetCountryResponse response = (GetCountryResponse) getWebServiceTemplate().marshalSendAndReceive(request); + + return response; + } + +} \ No newline at end of file diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java new file mode 100644 index 0000000000..8dabdbc00d --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/CountryClientConfig.java @@ -0,0 +1,25 @@ +package com.baeldung.springsoap.client; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; + +@Configuration +public class CountryClientConfig { + + @Bean + public Jaxb2Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + marshaller.setContextPath("com.baeldung.springsoap.client.gen"); + return marshaller; + } + + @Bean + public CountryClient countryClient(Jaxb2Marshaller marshaller) { + CountryClient client = new CountryClient(); + client.setDefaultUri("http://localhost:8080/ws"); + client.setMarshaller(marshaller); + client.setUnmarshaller(marshaller); + return client; + } +} \ No newline at end of file diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java new file mode 100644 index 0000000000..e17dce55f9 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java @@ -0,0 +1,146 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for country complex type. + * + *

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

+ * <complexType name="country">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="population" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ *         <element name="capital" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="currency" type="{http://www.baeldung.com/springsoap/gen}currency"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "country", propOrder = { + "name", + "population", + "capital", + "currency" +}) +public class Country { + + @XmlElement(required = true) + protected String name; + protected int population; + @XmlElement(required = true) + protected String capital; + @XmlElement(required = true) + @XmlSchemaType(name = "string") + protected Currency currency; + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the population property. + * + */ + public int getPopulation() { + return population; + } + + /** + * Sets the value of the population property. + * + */ + public void setPopulation(int value) { + this.population = value; + } + + /** + * Gets the value of the capital property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCapital() { + return capital; + } + + /** + * Sets the value of the capital property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCapital(String value) { + this.capital = value; + } + + /** + * Gets the value of the currency property. + * + * @return + * possible object is + * {@link Currency } + * + */ + public Currency getCurrency() { + return currency; + } + + /** + * Sets the value of the currency property. + * + * @param value + * allowed object is + * {@link Currency } + * + */ + public void setCurrency(Currency value) { + this.currency = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java new file mode 100644 index 0000000000..12fdef58c2 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java @@ -0,0 +1,47 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for currency. + * + *

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

+ *

+ * <simpleType name="currency">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="GBP"/>
+ *     <enumeration value="EUR"/>
+ *     <enumeration value="PLN"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "currency") +@XmlEnum +public enum Currency { + + GBP, + EUR, + PLN; + + public String value() { + return name(); + } + + public static Currency fromValue(String v) { + return valueOf(v); + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java new file mode 100644 index 0000000000..5739ee3b96 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java @@ -0,0 +1,71 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for anonymous complex type. + * + *

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

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "name" +}) +@XmlRootElement(name = "getCountryRequest") +public class GetCountryRequest { + + @XmlElement(required = true) + protected String name; + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java new file mode 100644 index 0000000000..ba1ab56cf8 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java @@ -0,0 +1,71 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for anonymous complex type. + * + *

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

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="country" type="{http://www.baeldung.com/springsoap/gen}country"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "country" +}) +@XmlRootElement(name = "getCountryResponse") +public class GetCountryResponse { + + @XmlElement(required = true) + protected Country country; + + /** + * Gets the value of the country property. + * + * @return + * possible object is + * {@link Country } + * + */ + public Country getCountry() { + return country; + } + + /** + * Sets the value of the country property. + * + * @param value + * allowed object is + * {@link Country } + * + */ + public void setCountry(Country value) { + this.country = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java new file mode 100644 index 0000000000..88b27245be --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java @@ -0,0 +1,63 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + + +package com.baeldung.springsoap.client.gen; + +import javax.xml.bind.annotation.XmlRegistry; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the com.baeldung.springsoap.client.gen package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.springsoap.client.gen + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link GetCountryRequest } + * + */ + public GetCountryRequest createGetCountryRequest() { + return new GetCountryRequest(); + } + + /** + * Create an instance of {@link GetCountryResponse } + * + */ + public GetCountryResponse createGetCountryResponse() { + return new GetCountryResponse(); + } + + /** + * Create an instance of {@link Country } + * + */ + public Country createCountry() { + return new Country(); + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java new file mode 100644 index 0000000000..eefed169a8 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java @@ -0,0 +1,9 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 +// See https://javaee.github.io/jaxb-v2/ +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2020.04.25 at 03:18:49 PM IST +// + +@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/springsoap/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package com.baeldung.springsoap.client.gen; diff --git a/spring-soap/src/main/resources/countries.wsdl b/spring-soap/src/main/resources/countries.wsdl new file mode 100644 index 0000000000..2a2eaf05bb --- /dev/null +++ b/spring-soap/src/main/resources/countries.wsdl @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java b/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java new file mode 100644 index 0000000000..63dbe2a5cf --- /dev/null +++ b/spring-soap/src/test/java/com/baeldung/springsoap/client/CountryClientLiveTest.java @@ -0,0 +1,36 @@ +package com.baeldung.springsoap.client; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.springsoap.client.gen.Currency; +import com.baeldung.springsoap.client.gen.GetCountryResponse; + +//Ensure that the server - com.baeldung.springsoap.Application - is running before executing this test +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CountryClientConfig.class, loader = AnnotationConfigContextLoader.class) +public class CountryClientLiveTest { + + @Autowired + CountryClient client; + + @Test + public void givenCountryService_whenCountryPoland_thenCapitalIsWarsaw() { + GetCountryResponse response = client.getCountry("Poland"); + assertEquals("Warsaw", response.getCountry() + .getCapital()); + } + + @Test + public void givenCountryService_whenCountrySpain_thenCurrencyEUR() { + GetCountryResponse response = client.getCountry("Spain"); + assertEquals(Currency.EUR, response.getCountry() + .getCurrency()); + } +} diff --git a/spring-social-login/src/main/java/org/baeldung/config/Application.java b/spring-social-login/src/main/java/com/baeldung/config/Application.java similarity index 80% rename from spring-social-login/src/main/java/org/baeldung/config/Application.java rename to spring-social-login/src/main/java/com/baeldung/config/Application.java index cf6251a51e..5d083d2d47 100644 --- a/spring-social-login/src/main/java/org/baeldung/config/Application.java +++ b/spring-social-login/src/main/java/com/baeldung/config/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -7,8 +7,8 @@ import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication -@EnableJpaRepositories("org.baeldung.persistence.dao") -@EntityScan("org.baeldung.persistence.model") +@EnableJpaRepositories("com.baeldung.persistence.dao") +@EntityScan("com.baeldung.persistence.model") public class Application extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java similarity index 92% rename from spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java rename to spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java index 8e439653a9..3d3081fef9 100644 --- a/spring-social-login/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java @@ -1,7 +1,7 @@ -package org.baeldung.config; +package com.baeldung.config; -import org.baeldung.security.FacebookSignInAdapter; -import org.baeldung.security.FacebookConnectionSignup; +import com.baeldung.security.FacebookSignInAdapter; +import com.baeldung.security.FacebookConnectionSignup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -18,7 +18,7 @@ import org.springframework.social.connect.web.ProviderSignInController; @Configuration @EnableWebSecurity -@ComponentScan(basePackages = { "org.baeldung.security" }) +@ComponentScan(basePackages = { "com.baeldung.security" }) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired diff --git a/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java b/spring-social-login/src/main/java/com/baeldung/config/WebConfig.java similarity index 98% rename from spring-social-login/src/main/java/org/baeldung/config/WebConfig.java rename to spring-social-login/src/main/java/com/baeldung/config/WebConfig.java index 8cfcd6cb41..d178cc28a6 100644 --- a/spring-social-login/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-social-login/src/main/java/com/baeldung/config/WebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-social-login/src/main/java/com/baeldung/persistence/dao/UserRepository.java similarity index 69% rename from spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java rename to spring-social-login/src/main/java/com/baeldung/persistence/dao/UserRepository.java index 679dd6c363..aeb443dd06 100644 --- a/spring-social-login/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ b/spring-social-login/src/main/java/com/baeldung/persistence/dao/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.dao; +package com.baeldung.persistence.dao; -import org.baeldung.persistence.model.User; +import com.baeldung.persistence.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { diff --git a/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java b/spring-social-login/src/main/java/com/baeldung/persistence/model/User.java similarity index 96% rename from spring-social-login/src/main/java/org/baeldung/persistence/model/User.java rename to spring-social-login/src/main/java/com/baeldung/persistence/model/User.java index a4cffc27d0..ce1774ca2c 100644 --- a/spring-social-login/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-social-login/src/main/java/com/baeldung/persistence/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package com.baeldung.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java b/spring-social-login/src/main/java/com/baeldung/security/FacebookConnectionSignup.java similarity index 85% rename from spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java rename to spring-social-login/src/main/java/com/baeldung/security/FacebookConnectionSignup.java index 6a9e30d7d8..e0a9fdc2e7 100644 --- a/spring-social-login/src/main/java/org/baeldung/security/FacebookConnectionSignup.java +++ b/spring-social-login/src/main/java/com/baeldung/security/FacebookConnectionSignup.java @@ -1,9 +1,9 @@ -package org.baeldung.security; +package com.baeldung.security; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.User; +import com.baeldung.persistence.dao.UserRepository; +import com.baeldung.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.social.connect.Connection; import org.springframework.social.connect.ConnectionSignUp; diff --git a/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java b/spring-social-login/src/main/java/com/baeldung/security/FacebookSignInAdapter.java similarity index 96% rename from spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java rename to spring-social-login/src/main/java/com/baeldung/security/FacebookSignInAdapter.java index b861609a01..3050941ffa 100644 --- a/spring-social-login/src/main/java/org/baeldung/security/FacebookSignInAdapter.java +++ b/spring-social-login/src/main/java/com/baeldung/security/FacebookSignInAdapter.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.util.Arrays; diff --git a/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-social-login/src/main/java/com/baeldung/security/MyUserDetailsService.java similarity index 89% rename from spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java rename to spring-social-login/src/main/java/com/baeldung/security/MyUserDetailsService.java index 5d0d5d793a..126f02e74a 100644 --- a/spring-social-login/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-social-login/src/main/java/com/baeldung/security/MyUserDetailsService.java @@ -1,9 +1,9 @@ -package org.baeldung.security; +package com.baeldung.security; import java.util.Arrays; -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.User; +import com.baeldung.persistence.dao.UserRepository; +import com.baeldung.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; diff --git a/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java b/spring-social-login/src/test/java/com/baeldung/SpringContextTest.java similarity index 88% rename from spring-social-login/src/test/java/org/baeldung/SpringContextTest.java rename to spring-social-login/src/test/java/com/baeldung/SpringContextTest.java index cfd8759c52..1d9711b5a4 100644 --- a/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-social-login/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.config.Application; +import com.baeldung.config.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-spel/src/test/java/org/baeldung/SpringContextTest.java b/spring-spel/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-spel/src/test/java/org/baeldung/SpringContextTest.java rename to spring-spel/src/test/java/com/baeldung/SpringContextTest.java index e25c1bf8e4..338b8b1e68 100644 --- a/spring-spel/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-spel/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java b/spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java similarity index 97% rename from spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java rename to spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java index 1e847c0d65..407cd8ebb0 100644 --- a/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 98% rename from spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 316642ab6f..d6c54f8099 100644 --- a/spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-static-resources/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.io.IOException; import javax.servlet.http.HttpServletRequest; diff --git a/spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java b/spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java similarity index 83% rename from spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java rename to spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java index c379d20047..97e7cf96fc 100644 --- a/spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java +++ b/spring-static-resources/src/main/java/com/baeldung/spring/AppConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -8,7 +8,7 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration -@ComponentScan(basePackages = { "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) +@ComponentScan(basePackages = { "com.baeldung.persistence.service", "com.baeldung.persistence.dao" }) @Import({ MvcConfig.class, SecSecurityConfig.class }) @PropertySource("classpath:application.properties") public class AppConfig { diff --git a/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java similarity index 96% rename from spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java rename to spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java index 7bd03617be..f23fe14fb8 100644 --- a/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-static-resources/src/main/java/com/baeldung/spring/MvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import java.util.Locale; @@ -25,7 +25,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration -@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) +@ComponentScan(basePackages = { "com.baeldung.web.controller", "com.baeldung.persistence.service", "com.baeldung.persistence.dao" }) @EnableWebMvc public class MvcConfig implements WebMvcConfigurer { @Autowired diff --git a/spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java similarity index 90% rename from spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java index 4da114c78b..3e630b8729 100644 --- a/spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-static-resources/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package com.baeldung.spring; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; diff --git a/spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java similarity index 96% rename from spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java rename to spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java index 44645a1471..dd58c7c2b6 100644 --- a/spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java +++ b/spring-static-resources/src/main/java/com/baeldung/web/controller/HomeController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import java.io.IOException; import java.text.DateFormat; diff --git a/spring-static-resources/src/main/resources/webSecurityConfig.xml b/spring-static-resources/src/main/resources/webSecurityConfig.xml index ea64ad5aea..2278cb6138 100644 --- a/spring-static-resources/src/main/resources/webSecurityConfig.xml +++ b/spring-static-resources/src/main/resources/webSecurityConfig.xml @@ -23,7 +23,7 @@ - + diff --git a/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java index 0dcbba3221..153b290de7 100644 --- a/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ package com.baeldung; -import org.baeldung.spring.SecSecurityConfig; +import com.baeldung.spring.SecSecurityConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml index dee9415679..39d8902956 100644 --- a/spring-swagger-codegen/pom.xml +++ b/spring-swagger-codegen/pom.xml @@ -15,6 +15,7 @@ spring-swagger-codegen-api-client + spring-openapi-generator-api-client spring-swagger-codegen-app diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator-ignore b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator/VERSION b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator/VERSION new file mode 100644 index 0000000000..ec87108d82 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.2.3 \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/.travis.yml b/spring-swagger-codegen/spring-openapi-generator-api-client/.travis.yml new file mode 100644 index 0000000000..e3bdf2af1b --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/README.md b/spring-swagger-codegen/spring-openapi-generator-api-client/README.md new file mode 100644 index 0000000000..01fd596268 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/README.md @@ -0,0 +1,174 @@ +# spring-openapi-generator-api-client + +Swagger Petstore + +- API version: 1.0.3 + +- Build date: 2020-03-15T06:14:01.568992-05:00[America/Chicago] + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: + +1. Java 1.8+ +2. Maven/Gradle + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + com.baeldung + spring-openapi-generator-api-client + 0.0.1-SNAPSHOT + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "com.baeldung:spring-openapi-generator-api-client:0.0.1-SNAPSHOT" +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +- `target/spring-openapi-generator-api-client-0.0.1-SNAPSHOT.jar` +- `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import com.baeldung.petstore.client.invoker.*; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.model.*; +import com.baeldung.petstore.client.api.PetApi; + +public class PetApiExample { + + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [Category](docs/Category.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### petstore_auth + + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: https://petstore.swagger.io/oauth/authorize +- **Scopes**: + - read:pets: read your pets + - write:pets: modify pets in your account + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +apiteam@swagger.io + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/build.gradle b/spring-swagger-codegen/spring-openapi-generator-api-client/build.gradle new file mode 100644 index 0000000000..d86deb75b8 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/build.gradle @@ -0,0 +1,120 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'com.baeldung' +version = '0.0.1-SNAPSHOT' + +buildscript { + repositories { + maven { url "https://repo1.maven.org/maven2" } + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + install { + repositories.mavenInstaller { + pom.artifactId = 'spring-openapi-generator-api-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.22" + jackson_version = "2.10.1" + jackson_databind_version = "2.10.1" + jackson_databind_nullable_version = "0.2.1" + spring_web_version = "4.3.9.RELEASE" + jodatime_version = "2.9.9" + junit_version = "4.13" + jackson_threeten_version = "2.9.10" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.google.code.findbugs:jsr305:3.0.2" + compile "org.springframework:spring-web:$spring_web_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" + compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" + compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_threeten_version" + testCompile "junit:junit:$junit_version" +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/build.sbt b/spring-swagger-codegen/spring-openapi-generator-api-client/build.sbt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Category.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Category.md new file mode 100644 index 0000000000..848fb61818 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Category.md @@ -0,0 +1,13 @@ + + +# Category + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/ModelApiResponse.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/ModelApiResponse.md new file mode 100644 index 0000000000..14fb7f1ed2 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/ModelApiResponse.md @@ -0,0 +1,14 @@ + + +# ModelApiResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Order.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Order.md new file mode 100644 index 0000000000..409fc4cc96 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Order.md @@ -0,0 +1,27 @@ + + +# Order + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum + +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Pet.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Pet.md new file mode 100644 index 0000000000..37ac007b79 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Pet.md @@ -0,0 +1,27 @@ + + +# Pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum + +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/PetApi.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/PetApi.md new file mode 100644 index 0000000000..56e81ea3aa --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/PetApi.md @@ -0,0 +1,581 @@ +# PetApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +## addPet + +> addPet(body) + +Add a new pet to the store + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + + +## deletePet + +> deletePet(petId, apiKey) + +Deletes a pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | Pet id to delete + String apiKey = "apiKey_example"; // String | + try { + apiInstance.deletePet(petId, apiKey); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +## findPetsByStatus + +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List status = Arrays.asList("available"); // List | Status values that need to be considered for filter + try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + + +## findPetsByTags + +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List tags = Arrays.asList(); // List | Tags to filter by + try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + + +## getPetById + +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to return + try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +## updatePet + +> updatePet(body) + +Update an existing pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.updatePet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + + +## updatePetWithForm + +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet that needs to be updated + String name = "name_example"; // String | Updated name of the pet + String status = "status_example"; // String | Updated status of the pet + try { + apiInstance.updatePetWithForm(petId, name, status); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + + +## uploadFile + +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + File file = new File("/path/to/file"); // File | file to upload + try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/StoreApi.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/StoreApi.md new file mode 100644 index 0000000000..7a70c0bdbc --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/StoreApi.md @@ -0,0 +1,276 @@ +# StoreApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +## deleteOrder + +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Long orderId = 56L; // Long | ID of the order that needs to be deleted + try { + apiInstance.deleteOrder(orderId); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## getInventory + +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.auth.*; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + StoreApi apiInstance = new StoreApi(defaultClient); + try { + Map result = apiInstance.getInventory(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Map<String, Integer>** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## getOrderById + +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Long orderId = 56L; // Long | ID of pet that needs to be fetched + try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## placeOrder + +> Order placeOrder(body) + +Place an order for a pet + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Order body = new Order(); // Order | order placed for purchasing the pet + try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Tag.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Tag.md new file mode 100644 index 0000000000..f24eba7d22 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/Tag.md @@ -0,0 +1,13 @@ + + +# Tag + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/User.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/User.md new file mode 100644 index 0000000000..c4ea94b7fc --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/User.md @@ -0,0 +1,19 @@ + + +# User + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/docs/UserApi.md b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/UserApi.md new file mode 100644 index 0000000000..ff3815e352 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/docs/UserApi.md @@ -0,0 +1,525 @@ +# UserApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +## createUser + +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + User body = new User(); // User | Created user object + try { + apiInstance.createUser(body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## createUsersWithArrayInput + +> createUsersWithArrayInput(body) + +Creates list of users with given input array + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List body = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithArrayInput(body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## createUsersWithListInput + +> createUsersWithListInput(body) + +Creates list of users with given input array + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List body = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithListInput(body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## deleteUser + +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be deleted + try { + apiInstance.deleteUser(username); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## getUserByName + +> User getUserByName(username) + +Get user by user name + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. + try { + User result = apiInstance.getUserByName(username); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## loginUser + +> String loginUser(username, password) + +Logs user into the system + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The user name for login + String password = "password_example"; // String | The password for login in clear text + try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, application/xml + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
* X-Expires-After - date in UTC when token expires
| +| **400** | Invalid username/password supplied | - | + + +## logoutUser + +> logoutUser() + +Logs out current logged in user session + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + try { + apiInstance.logoutUser(); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## updateUser + +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.invoker.ApiException; +import com.baeldung.petstore.client.invoker.Configuration; +import com.baeldung.petstore.client.invoker.models.*; +import com.baeldung.petstore.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | name that need to be updated + User body = new User(); // User | Updated user object + try { + apiInstance.updateUser(username, body); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be updated | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/git_push.sh b/spring-swagger-codegen/spring-openapi-generator-api-client/git_push.sh new file mode 100644 index 0000000000..ced3be2b0c --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradle.properties b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle.properties new file mode 100644 index 0000000000..05644f0754 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.jar b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..cc4fdc293d Binary files /dev/null and b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.jar differ diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.properties b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..94920145f3 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew new file mode 100644 index 0000000000..2fe81a7d95 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew.bat b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew.bat new file mode 100644 index 0000000000..9618d8d960 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml new file mode 100644 index 0000000000..cc70a9f654 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml @@ -0,0 +1,274 @@ + + 4.0.0 + com.baeldung + spring-openapi-generator-api-client + jar + spring-openapi-generator-api-client + 0.0.1-SNAPSHOT + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + + org.springframework + spring-web + ${spring-web-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${jackson-threetenbp-version} + + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.5.22 + 4.3.9.RELEASE + 2.10.1 + 2.10.1 + 0.2.1 + 2.9.10 + 1.0.0 + 4.13 + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/settings.gradle b/spring-swagger-codegen/spring-openapi-generator-api-client/settings.gradle new file mode 100644 index 0000000000..06a087cb49 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "spring-openapi-generator-api-client" \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/AndroidManifest.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..cd581f9f78 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java new file mode 100644 index 0000000000..b7256c81fb --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/PetApi.java @@ -0,0 +1,477 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.model.ModelApiResponse; +import com.baeldung.petstore.client.model.Pet; + +import java.io.File; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.api.PetApi") +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(new ApiClient()); + } + + @Autowired + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + *

405 - Invalid input + * @param body Pet object that needs to be added to the store (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void addPet(Pet body) throws RestClientException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + *

405 - Invalid input + * @param body Pet object that needs to be added to the store (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity addPetWithHttpInfo(Pet body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling addPet"); + } + + String path = apiClient.expandPath("/pet", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json", "application/xml" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Deletes a pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deletePet(Long petId, String apiKey) throws RestClientException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deletePetWithHttpInfo(Long petId, String apiKey) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling deletePet"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = apiClient.expandPath("/pet/{petId}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + if (apiKey != null) + headerParams.add("api_key", apiClient.parameterToString(apiKey)); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

200 - successful operation + *

400 - Invalid status value + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public List findPetsByStatus(List status) throws RestClientException { + return findPetsByStatusWithHttpInfo(status).getBody(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

200 - successful operation + *

400 - Invalid status value + * @param status Status values that need to be considered for filter (required) + * @return ResponseEntity<List<Pet>> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity> findPetsByStatusWithHttpInfo(List status) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'status' when calling findPetsByStatus"); + } + + String path = apiClient.expandPath("/pet/findByStatus", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "status", status)); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

200 - successful operation + *

400 - Invalid tag value + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + @Deprecated + public List findPetsByTags(List tags) throws RestClientException { + return findPetsByTagsWithHttpInfo(tags).getBody(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

200 - successful operation + *

400 - Invalid tag value + * @param tags Tags to filter by (required) + * @return ResponseEntity<List<Pet>> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + @Deprecated + public ResponseEntity> findPetsByTagsWithHttpInfo(List tags) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'tags' when calling findPetsByTags"); + } + + String path = apiClient.expandPath("/pet/findByTags", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "tags", tags)); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Find pet by ID + * Returns a single pet + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId ID of pet to return (required) + * @return Pet + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Pet getPetById(Long petId) throws RestClientException { + return getPetByIdWithHttpInfo(petId).getBody(); + } + + /** + * Find pet by ID + * Returns a single pet + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Pet not found + * @param petId ID of pet to return (required) + * @return ResponseEntity<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getPetByIdWithHttpInfo(Long petId) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling getPetById"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = apiClient.expandPath("/pet/{petId}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Update an existing pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + *

405 - Validation exception + * @param body Pet object that needs to be added to the store (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updatePet(Pet body) throws RestClientException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + *

400 - Invalid ID supplied + *

404 - Pet not found + *

405 - Validation exception + * @param body Pet object that needs to be added to the store (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updatePetWithHttpInfo(Pet body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updatePet"); + } + + String path = apiClient.expandPath("/pet", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json", "application/xml" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Updates a pet in the store with form data + * + *

405 - Invalid input + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updatePetWithForm(Long petId, String name, String status) throws RestClientException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + *

405 - Invalid input + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = apiClient.expandPath("/pet/{petId}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + if (name != null) + formParams.add("name", name); + if (status != null) + formParams.add("status", status); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * uploads an image + * + *

200 - successful operation + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { + return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody(); + } + + /** + * uploads an image + * + *

200 - successful operation + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ResponseEntity<ModelApiResponse> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling uploadFile"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("petId", petId); + String path = apiClient.expandPath("/pet/{petId}/uploadImage", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + if (additionalMetadata != null) + formParams.add("additionalMetadata", additionalMetadata); + if (file != null) + formParams.add("file", new FileSystemResource(file)); + + final String[] accepts = { + "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "multipart/form-data" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/StoreApi.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/StoreApi.java new file mode 100644 index 0000000000..792617bc28 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/StoreApi.java @@ -0,0 +1,240 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.model.Order; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.api.StoreApi") +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(new ApiClient()); + } + + @Autowired + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of the order that needs to be deleted (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteOrder(Long orderId) throws RestClientException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of the order that needs to be deleted (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteOrderWithHttpInfo(Long orderId) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("orderId", orderId); + String path = apiClient.expandPath("/store/order/{orderId}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

200 - successful operation + * @return Map<String, Integer> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Map getInventory() throws RestClientException { + return getInventoryWithHttpInfo().getBody(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

200 - successful operation + * @return ResponseEntity<Map<String, Integer>> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity> getInventoryWithHttpInfo() throws RestClientException { + Object postBody = null; + + String path = apiClient.expandPath("/store/inventory", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key" }; + + ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Order getOrderById(Long orderId) throws RestClientException { + return getOrderByIdWithHttpInfo(orderId).getBody(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + *

200 - successful operation + *

400 - Invalid ID supplied + *

404 - Order not found + * @param orderId ID of pet that needs to be fetched (required) + * @return ResponseEntity<Order> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getOrderByIdWithHttpInfo(Long orderId) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("orderId", orderId); + String path = apiClient.expandPath("/store/order/{orderId}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Place an order for a pet + * + *

200 - successful operation + *

400 - Invalid Order + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Order placeOrder(Order body) throws RestClientException { + return placeOrderWithHttpInfo(body).getBody(); + } + + /** + * Place an order for a pet + * + *

200 - successful operation + *

400 - Invalid Order + * @param body order placed for purchasing the pet (required) + * @return ResponseEntity<Order> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity placeOrderWithHttpInfo(Order body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling placeOrder"); + } + + String path = apiClient.expandPath("/store/order", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java new file mode 100644 index 0000000000..c7cb0b803d --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/api/UserApi.java @@ -0,0 +1,441 @@ +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.invoker.ApiClient; +import com.baeldung.petstore.client.model.User; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.api.UserApi") +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(new ApiClient()); + } + + @Autowired + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + *

0 - successful operation + * @param body Created user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUser(User body) throws RestClientException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + *

0 - successful operation + * @param body Created user object (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createUserWithHttpInfo(User body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUser"); + } + + String path = apiClient.expandPath("/user", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUsersWithArrayInput(List body) throws RestClientException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createUsersWithArrayInputWithHttpInfo(List body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + String path = apiClient.expandPath("/user/createWithArray", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void createUsersWithListInput(List body) throws RestClientException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + *

0 - successful operation + * @param body List of user object (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createUsersWithListInputWithHttpInfo(List body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + String path = apiClient.expandPath("/user/createWithList", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Delete user + * This can only be done by the logged in user. + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be deleted (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteUser(String username) throws RestClientException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be deleted (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteUserWithHttpInfo(String username) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling deleteUser"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + String path = apiClient.expandPath("/user/{username}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Get user by user name + * + *

200 - successful operation + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public User getUserByName(String username) throws RestClientException { + return getUserByNameWithHttpInfo(username).getBody(); + } + + /** + * Get user by user name + * + *

200 - successful operation + *

400 - Invalid username supplied + *

404 - User not found + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ResponseEntity<User> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getUserByNameWithHttpInfo(String username) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling getUserByName"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + String path = apiClient.expandPath("/user/{username}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Logs user into the system + * + *

200 - successful operation + *

400 - Invalid username/password supplied + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String loginUser(String username, String password) throws RestClientException { + return loginUserWithHttpInfo(username, password).getBody(); + } + + /** + * Logs user into the system + * + *

200 - successful operation + *

400 - Invalid username/password supplied + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity loginUserWithHttpInfo(String username, String password) throws RestClientException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'password' when calling loginUser"); + } + + String path = apiClient.expandPath("/user/login", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); + + final String[] accepts = { + "application/json", "application/xml" + }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Logs out current logged in user session + * + *

0 - successful operation + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void logoutUser() throws RestClientException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + *

0 - successful operation + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity logoutUserWithHttpInfo() throws RestClientException { + Object postBody = null; + + String path = apiClient.expandPath("/user/logout", Collections.emptyMap()); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } + /** + * Updated user + * This can only be done by the logged in user. + *

400 - Invalid user supplied + *

404 - User not found + * @param username name that need to be updated (required) + * @param body Updated user object (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void updateUser(String username, User body) throws RestClientException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + *

400 - Invalid user supplied + *

404 - User not found + * @param username name that need to be updated (required) + * @param body Updated user object (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateUserWithHttpInfo(String username, User body) throws RestClientException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updateUser"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("username", username); + String path = apiClient.expandPath("/user/{username}", uriVariables); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] accepts = { }; + final List accept = apiClient.selectHeaderAccept(accepts); + final String[] contentTypes = { + "application/json" + }; + final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java new file mode 100644 index 0000000000..5a10828c47 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java @@ -0,0 +1,750 @@ +package com.baeldung.petstore.client.invoker; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; + +import com.baeldung.petstore.client.invoker.auth.ApiKeyAuth; +import com.baeldung.petstore.client.invoker.auth.Authentication; +import com.baeldung.petstore.client.invoker.auth.HttpBasicAuth; +import com.baeldung.petstore.client.invoker.auth.HttpBearerAuth; +import com.baeldung.petstore.client.invoker.auth.OAuth; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TimeZone; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openapitools.jackson.nullable.JsonNullableModule; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpRequest; +import org.springframework.http.InvalidMediaTypeException; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.RequestEntity.BodyBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; +import org.threeten.bp.*; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +@Component("com.baeldung.petstore.client.invoker.ApiClient") +public class ApiClient { + public enum CollectionFormat { + CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null); + + private final String separator; + private CollectionFormat(String separator) { + this.separator = separator; + } + + private String collectionToString(Collection collection) { + return StringUtils.collectionToDelimitedString(collection, separator); + } + } + + private boolean debugging = false; + + private HttpHeaders defaultHeaders = new HttpHeaders(); + private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + + private String basePath = "https://petstore.swagger.io/v2"; + + private RestTemplate restTemplate; + + private Map authentications; + + private DateFormat dateFormat; + + public ApiClient() { + this.restTemplate = buildRestTemplate(); + init(); + } + + @Autowired + public ApiClient(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + init(); + } + + protected void init() { + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new RFC3339DateFormat(); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Set default User-Agent. + setUserAgent("Java-SDK"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get the current base path + * @return String the base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set the base path, which should include the host + * @param basePath the base path + * @return ApiClient this client + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * @return Map the currently configured authentication types + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set token for HTTP bearer authentication. + * @param bearerToken the token + */ + public void setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * @param username the username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * @param password the password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * @param apiKey the API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix the API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * @param accessToken the access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent the user agent string + * @return ApiClient this client + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param name The header's name + * @param value The header's value + * @return ApiClient this client + */ + public ApiClient addDefaultHeader(String name, String value) { + if (defaultHeaders.containsKey(name)) { + defaultHeaders.remove(name); + } + defaultHeaders.add(name, value); + return this; + } + + /** + * Add a default cookie. + * + * @param name The cookie's name + * @param value The cookie's value + * @return ApiClient this client + */ + public ApiClient addDefaultCookie(String name, String value) { + if (defaultCookies.containsKey(name)) { + defaultCookies.remove(name); + } + defaultCookies.add(name, value); + return this; + } + + public void setDebugging(boolean debugging) { + List currentInterceptors = this.restTemplate.getInterceptors(); + if(debugging) { + if (currentInterceptors == null) { + currentInterceptors = new ArrayList(); + } + ClientHttpRequestInterceptor interceptor = new ApiClientHttpRequestInterceptor(); + currentInterceptors.add(interceptor); + this.restTemplate.setInterceptors(currentInterceptors); + } else { + if (currentInterceptors != null && !currentInterceptors.isEmpty()) { + Iterator iter = currentInterceptors.iterator(); + while (iter.hasNext()) { + ClientHttpRequestInterceptor interceptor = iter.next(); + if (interceptor instanceof ApiClientHttpRequestInterceptor) { + iter.remove(); + } + } + this.restTemplate.setInterceptors(currentInterceptors); + } + } + this.debugging = debugging; + } + + /** + * Check that whether debugging is enabled for this API client. + * @return boolean true if this client is enabled for debugging, false otherwise + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Get the date format used to parse/format date parameters. + * @return DateFormat format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + for(HttpMessageConverter converter:restTemplate.getMessageConverters()){ + if(converter instanceof AbstractJackson2HttpMessageConverter){ + ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper(); + mapper.setDateFormat(dateFormat); + } + } + return this; + } + + /** + * Parse the given string into Date object. + * @param str the string to parse + * @return the Date parsed from the string + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + * @param date the date to format + * @return the formatted date as string + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * @param param the object to convert + * @return String the parameter represented as a String + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate( (Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection) param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param values The values of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(CollectionFormat collectionFormat, Collection values) { + // create the value based on the collection format + if (CollectionFormat.MULTI.equals(collectionFormat)) { + // not valid for path params + return parameterToString(values); + } + + // collectionFormat is assumed to be "csv" by default + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + return collectionFormat.collectionToString(values); + } + + /** + * Converts a parameter to a {@link MultiValueMap} for use in REST requests + * @param collectionFormat The format to convert to + * @param name The name of the parameter + * @param value The parameter's value + * @return a Map containing the String value(s) of the input parameter + */ + public MultiValueMap parameterToMultiValueMap(CollectionFormat collectionFormat, String name, Object value) { + final MultiValueMap params = new LinkedMultiValueMap(); + + if (name == null || name.isEmpty() || value == null) { + return params; + } + + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(name, parameterToString(value)); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + if (collectionFormat.equals(CollectionFormat.MULTI)) { + for (Object item : valueCollection) { + params.add(name, parameterToString(item)); + } + return params; + } + + List values = new ArrayList(); + for(Object o : valueCollection) { + values.add(parameterToString(o)); + } + params.add(name, collectionFormat.collectionToString(values)); + + return params; + } + + /** + * Check if the given {@code String} is a JSON MIME. + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(String mediaType) { + // "* / *" is default to JSON + if ("*/*".equals(mediaType)) { + return true; + } + + try { + return isJsonMime(MediaType.parseMediaType(mediaType)); + } catch (InvalidMediaTypeException e) { + } + return false; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(MediaType mediaType) { + return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return List The list of MediaTypes to use for the Accept header + */ + public List selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + MediaType mediaType = MediaType.parseMediaType(accept); + if (isJsonMime(mediaType)) { + return Collections.singletonList(mediaType); + } + } + return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts)); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return MediaType The Content-Type header to use. If the given array is empty, JSON will be used. + */ + public MediaType selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return MediaType.APPLICATION_JSON; + } + for (String contentType : contentTypes) { + MediaType mediaType = MediaType.parseMediaType(contentType); + if (isJsonMime(mediaType)) { + return mediaType; + } + } + return MediaType.parseMediaType(contentTypes[0]); + } + + /** + * Select the body to use for the request + * @param obj the body object + * @param formParams the form parameters + * @param contentType the content type of the request + * @return Object the selected body + */ + protected Object selectBody(Object obj, MultiValueMap formParams, MediaType contentType) { + boolean isForm = MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType) || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType); + return isForm ? formParams : obj; + } + + /** + * Expand path template with variables + * @param pathTemplate path template with placeholders + * @param variables variables to replace + * @return path with placeholders replaced by variables + */ + public String expandPath(String pathTemplate, Map variables) { + return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString(); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param the return type to use + * @param path The sub-path of the HTTP URL + * @param method The request method + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return ResponseEntity<T> The response of the chosen type + */ + public ResponseEntity invokeAPI(String path, HttpMethod method, MultiValueMap queryParams, Object body, HttpHeaders headerParams, MultiValueMap cookieParams, MultiValueMap formParams, List accept, MediaType contentType, String[] authNames, ParameterizedTypeReference returnType) throws RestClientException { + updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); + + final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path); + if (queryParams != null) { + //encode the query parameters in case they contain unsafe characters + for (List values : queryParams.values()) { + if (values != null) { + for (int i = 0; i < values.size(); i++) { + try { + values.set(i, URLEncoder.encode(values.get(i), "utf8")); + } catch (UnsupportedEncodingException e) { + + } + } + } + } + builder.queryParams(queryParams); + } + + URI uri; + try { + uri = new URI(builder.build().toUriString()); + } catch(URISyntaxException ex) { + throw new RestClientException("Could not build URL: " + builder.toUriString(), ex); + } + + final BodyBuilder requestBuilder = RequestEntity.method(method, uri); + if(accept != null) { + requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); + } + if(contentType != null) { + requestBuilder.contentType(contentType); + } + + addHeadersToRequest(headerParams, requestBuilder); + addHeadersToRequest(defaultHeaders, requestBuilder); + addCookiesToRequest(cookieParams, requestBuilder); + addCookiesToRequest(defaultCookies, requestBuilder); + + RequestEntity requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); + + ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + return responseEntity; + } else { + // The error handler built into the RestTemplate should handle 400 and 500 series errors. + throw new RestClientException("API returned " + responseEntity.getStatusCode() + " and it wasn't handled by the RestTemplate error handler"); + } + } + + /** + * Add headers to the request that is being built + * @param headers The headers to add + * @param requestBuilder The current request + */ + protected void addHeadersToRequest(HttpHeaders headers, BodyBuilder requestBuilder) { + for (Entry> entry : headers.entrySet()) { + List values = entry.getValue(); + for(String value : values) { + if (value != null) { + requestBuilder.header(entry.getKey(), value); + } + } + } + } + + /** + * Add cookies to the request that is being built + * @param cookies The cookies to add + * @param requestBuilder The current request + */ + protected void addCookiesToRequest(MultiValueMap cookies, BodyBuilder requestBuilder) { + if (!cookies.isEmpty()) { + requestBuilder.header("Cookie", buildCookieHeader(cookies)); + } + } + + /** + * Build cookie header. Keeps a single value per cookie (as per + * RFC6265 section 5.3). + * + * @param cookies map all cookies + * @return header string for cookies. + */ + private String buildCookieHeader(MultiValueMap cookies) { + final StringBuilder cookieValue = new StringBuilder(); + String delimiter = ""; + for (final Map.Entry> entry : cookies.entrySet()) { + final String value = entry.getValue().get(entry.getValue().size() - 1); + cookieValue.append(String.format("%s%s=%s", delimiter, entry.getKey(), value)); + delimiter = "; "; + } + return cookieValue.toString(); + } + + /** + * Build the RestTemplate used to make HTTP requests. + * @return RestTemplate + */ + protected RestTemplate buildRestTemplate() { + RestTemplate restTemplate = new RestTemplate(); + for(HttpMessageConverter converter:restTemplate.getMessageConverters()){ + if(converter instanceof AbstractJackson2HttpMessageConverter){ + ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper(); + ThreeTenModule module = new ThreeTenModule(); + module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); + module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); + mapper.registerModule(module); + mapper.registerModule(new JsonNullableModule()); + } + } + // This allows us to read the response more than once - Necessary for debugging. + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory())); + return restTemplate; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams The query parameters + * @param headerParams The header parameters + */ + private void updateParamsForAuth(String[] authNames, MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RestClientException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams); + } + } + + private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { + private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + logRequest(request, body); + ClientHttpResponse response = execution.execute(request, body); + logResponse(response); + return response; + } + + private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException { + log.info("URI: " + request.getURI()); + log.info("HTTP Method: " + request.getMethod()); + log.info("HTTP Headers: " + headersToString(request.getHeaders())); + log.info("Request Body: " + new String(body, StandardCharsets.UTF_8)); + } + + private void logResponse(ClientHttpResponse response) throws IOException { + log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("Status Text: " + response.getStatusText()); + log.info("HTTP Headers: " + headersToString(response.getHeaders())); + log.info("Response Body: " + bodyToString(response.getBody())); + } + + private String headersToString(HttpHeaders headers) { + StringBuilder builder = new StringBuilder(); + for(Entry> entry : headers.entrySet()) { + builder.append(entry.getKey()).append("=["); + for(String value : entry.getValue()) { + builder.append(value).append(","); + } + builder.setLength(builder.length() - 1); // Get rid of trailing comma + builder.append("],"); + } + builder.setLength(builder.length() - 1); // Get rid of trailing comma + return builder.toString(); + } + + private String bodyToString(InputStream body) throws IOException { + StringBuilder builder = new StringBuilder(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); + String line = bufferedReader.readLine(); + while (line != null) { + builder.append(line).append(System.lineSeparator()); + line = bufferedReader.readLine(); + } + bufferedReader.close(); + return builder.toString(); + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/CustomInstantDeserializer.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/CustomInstantDeserializer.java new file mode 100644 index 0000000000..6957818fb4 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/CustomInstantDeserializer.java @@ -0,0 +1,233 @@ +package com.baeldung.petstore.client.invoker; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonTokenId; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils; +import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase; +import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction; +import com.fasterxml.jackson.datatype.threetenbp.function.Function; + +import java.io.IOException; +import java.math.BigDecimal; + +import org.threeten.bp.DateTimeException; +import org.threeten.bp.DateTimeUtils; +import org.threeten.bp.Instant; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.ZonedDateTime; +import org.threeten.bp.format.DateTimeFormatter; +import org.threeten.bp.temporal.Temporal; +import org.threeten.bp.temporal.TemporalAccessor; + +/** + * Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s. + * Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format. + * + * @author Nick Williams + */ +public class CustomInstantDeserializer + extends ThreeTenDateTimeDeserializerBase { + private static final long serialVersionUID = 1L; + + public static final CustomInstantDeserializer INSTANT = new CustomInstantDeserializer( + Instant.class, DateTimeFormatter.ISO_INSTANT, + new Function() { + @Override + public Instant apply(TemporalAccessor temporalAccessor) { + return Instant.from(temporalAccessor); + } + }, + new Function() { + @Override + public Instant apply(FromIntegerArguments a) { + return Instant.ofEpochMilli(a.value); + } + }, + new Function() { + @Override + public Instant apply(FromDecimalArguments a) { + return Instant.ofEpochSecond(a.integer, a.fraction); + } + }, + null + ); + + public static final CustomInstantDeserializer OFFSET_DATE_TIME = new CustomInstantDeserializer( + OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, + new Function() { + @Override + public OffsetDateTime apply(TemporalAccessor temporalAccessor) { + return OffsetDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromIntegerArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromDecimalArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public OffsetDateTime apply(OffsetDateTime d, ZoneId z) { + return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())); + } + } + ); + + public static final CustomInstantDeserializer ZONED_DATE_TIME = new CustomInstantDeserializer( + ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, + new Function() { + @Override + public ZonedDateTime apply(TemporalAccessor temporalAccessor) { + return ZonedDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromIntegerArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromDecimalArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) { + return zonedDateTime.withZoneSameInstant(zoneId); + } + } + ); + + protected final Function fromMilliseconds; + + protected final Function fromNanoseconds; + + protected final Function parsedToValue; + + protected final BiFunction adjust; + + protected CustomInstantDeserializer(Class supportedType, + DateTimeFormatter parser, + Function parsedToValue, + Function fromMilliseconds, + Function fromNanoseconds, + BiFunction adjust) { + super(supportedType, parser); + this.parsedToValue = parsedToValue; + this.fromMilliseconds = fromMilliseconds; + this.fromNanoseconds = fromNanoseconds; + this.adjust = adjust == null ? new BiFunction() { + @Override + public T apply(T t, ZoneId zoneId) { + return t; + } + } : adjust; + } + + @SuppressWarnings("unchecked") + protected CustomInstantDeserializer(CustomInstantDeserializer base, DateTimeFormatter f) { + super((Class) base.handledType(), f); + parsedToValue = base.parsedToValue; + fromMilliseconds = base.fromMilliseconds; + fromNanoseconds = base.fromNanoseconds; + adjust = base.adjust; + } + + @Override + protected JsonDeserializer withDateFormat(DateTimeFormatter dtf) { + if (dtf == _formatter) { + return this; + } + return new CustomInstantDeserializer(this, dtf); + } + + @Override + public T deserialize(JsonParser parser, DeserializationContext context) throws IOException { + //NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only + //string values have to be adjusted to the configured TZ. + switch (parser.getCurrentTokenId()) { + case JsonTokenId.ID_NUMBER_FLOAT: { + BigDecimal value = parser.getDecimalValue(); + long seconds = value.longValue(); + int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds); + return fromNanoseconds.apply(new FromDecimalArguments( + seconds, nanoseconds, getZone(context))); + } + + case JsonTokenId.ID_NUMBER_INT: { + long timestamp = parser.getLongValue(); + if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { + return this.fromNanoseconds.apply(new FromDecimalArguments( + timestamp, 0, this.getZone(context) + )); + } + return this.fromMilliseconds.apply(new FromIntegerArguments( + timestamp, this.getZone(context) + )); + } + + case JsonTokenId.ID_STRING: { + String string = parser.getText().trim(); + if (string.length() == 0) { + return null; + } + if (string.endsWith("+0000")) { + string = string.substring(0, string.length() - 5) + "Z"; + } + T value; + try { + TemporalAccessor acc = _formatter.parse(string); + value = parsedToValue.apply(acc); + if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) { + return adjust.apply(value, this.getZone(context)); + } + } catch (DateTimeException e) { + throw _peelDTE(e); + } + return value; + } + } + throw context.mappingException("Expected type float, integer, or string."); + } + + private ZoneId getZone(DeserializationContext context) { + // Instants are always in UTC, so don't waste compute cycles + return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone()); + } + + private static class FromIntegerArguments { + public final long value; + public final ZoneId zoneId; + + private FromIntegerArguments(long value, ZoneId zoneId) { + this.value = value; + this.zoneId = zoneId; + } + } + + private static class FromDecimalArguments { + public final long integer; + public final int fraction; + public final ZoneId zoneId; + + private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) { + this.integer = integer; + this.fraction = fraction; + this.zoneId = zoneId; + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java new file mode 100644 index 0000000000..46083815a6 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/RFC3339DateFormat.java @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.baeldung.petstore.client.invoker; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java new file mode 100644 index 0000000000..b494b52050 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java @@ -0,0 +1,62 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location.equals("query")) { + queryParams.add(paramName, value); + } else if (location.equals("header")) { + headerParams.add(paramName, value); + } else if (location.equals("cookie")) { + cookieParams.add(paramName, value); + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java new file mode 100644 index 0000000000..8d55110d1b --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java @@ -0,0 +1,14 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +public interface Authentication { + /** + * Apply authentication settings to header and / or query parameters. + * @param queryParams The query parameters for the request + * @param headerParams The header parameters for the request + * @param cookieParams The cookie parameters for the request + */ + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams); +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java new file mode 100644 index 0000000000..4c1dad6e7c --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java @@ -0,0 +1,38 @@ +package com.baeldung.petstore.client.invoker.auth; + +import java.nio.charset.StandardCharsets; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.Base64Utils; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBearerAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBearerAuth.java new file mode 100644 index 0000000000..46ab6cabce --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBearerAuth.java @@ -0,0 +1,34 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private String bearerToken; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + public String getBearerToken() { + return bearerToken; + } + + public void setBearerToken(String bearerToken) { + this.bearerToken = bearerToken; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (bearerToken == null) { + return; + } + headerParams.add(HttpHeaders.AUTHORIZATION, (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java new file mode 100644 index 0000000000..b9e0f986ac --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java @@ -0,0 +1,24 @@ +package com.baeldung.petstore.client.invoker.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (accessToken != null) { + headerParams.add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); + } + } +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java new file mode 100644 index 0000000000..235e0b7f55 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +package com.baeldung.petstore.client.invoker.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java new file mode 100644 index 0000000000..2bb7ebe9f6 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Category.java @@ -0,0 +1,131 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Category + */ +@JsonPropertyOrder({ + Category.JSON_PROPERTY_ID, + Category.JSON_PROPERTY_NAME +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Category { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + + public Category id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Category name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java new file mode 100644 index 0000000000..107e08b8b9 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/ModelApiResponse.java @@ -0,0 +1,162 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * ModelApiResponse + */ +@JsonPropertyOrder({ + ModelApiResponse.JSON_PROPERTY_CODE, + ModelApiResponse.JSON_PROPERTY_TYPE, + ModelApiResponse.JSON_PROPERTY_MESSAGE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class ModelApiResponse { + public static final String JSON_PROPERTY_CODE = "code"; + private Integer code; + + public static final String JSON_PROPERTY_TYPE = "type"; + private String type; + + public static final String JSON_PROPERTY_MESSAGE = "message"; + private String message; + + + public ModelApiResponse code(Integer code) { + + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_CODE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Integer getCode() { + return code; + } + + + public void setCode(Integer code) { + this.code = code; + } + + + public ModelApiResponse type(String type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getType() { + return type; + } + + + public void setType(String type) { + this.type = type; + } + + + public ModelApiResponse message(String message) { + + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_MESSAGE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getMessage() { + return message; + } + + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java new file mode 100644 index 0000000000..b041595785 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Order.java @@ -0,0 +1,296 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.Objects; + +import org.threeten.bp.OffsetDateTime; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Order + */ +@JsonPropertyOrder({ + Order.JSON_PROPERTY_ID, + Order.JSON_PROPERTY_PET_ID, + Order.JSON_PROPERTY_QUANTITY, + Order.JSON_PROPERTY_SHIP_DATE, + Order.JSON_PROPERTY_STATUS, + Order.JSON_PROPERTY_COMPLETE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Order { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_PET_ID = "petId"; + private Long petId; + + public static final String JSON_PROPERTY_QUANTITY = "quantity"; + private Integer quantity; + + public static final String JSON_PROPERTY_SHIP_DATE = "shipDate"; + private OffsetDateTime shipDate; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_STATUS = "status"; + private StatusEnum status; + + public static final String JSON_PROPERTY_COMPLETE = "complete"; + private Boolean complete; + + + public Order id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Order petId(Long petId) { + + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PET_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getPetId() { + return petId; + } + + + public void setPetId(Long petId) { + this.petId = petId; + } + + + public Order quantity(Integer quantity) { + + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_QUANTITY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Integer getQuantity() { + return quantity; + } + + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + public Order shipDate(OffsetDateTime shipDate) { + + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_SHIP_DATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public OffsetDateTime getShipDate() { + return shipDate; + } + + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + + public Order status(StatusEnum status) { + + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "Order Status") + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public StatusEnum getStatus() { + return status; + } + + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + public Order complete(Boolean complete) { + + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_COMPLETE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Boolean getComplete() { + return complete; + } + + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java new file mode 100644 index 0000000000..3709cd5371 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Pet.java @@ -0,0 +1,310 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.baeldung.petstore.client.model.Category; +import com.baeldung.petstore.client.model.Tag; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Pet + */ +@JsonPropertyOrder({ + Pet.JSON_PROPERTY_ID, + Pet.JSON_PROPERTY_CATEGORY, + Pet.JSON_PROPERTY_NAME, + Pet.JSON_PROPERTY_PHOTO_URLS, + Pet.JSON_PROPERTY_TAGS, + Pet.JSON_PROPERTY_STATUS +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Pet { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_CATEGORY = "category"; + private Category category; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public static final String JSON_PROPERTY_PHOTO_URLS = "photoUrls"; + private List photoUrls = new ArrayList<>(); + + public static final String JSON_PROPERTY_TAGS = "tags"; + private List tags = null; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_STATUS = "status"; + private StatusEnum status; + + + public Pet id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Pet category(Category category) { + + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_CATEGORY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Category getCategory() { + return category; + } + + + public void setCategory(Category category) { + this.category = category; + } + + + public Pet name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + public Pet photoUrls(List photoUrls) { + + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty(JSON_PROPERTY_PHOTO_URLS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getPhotoUrls() { + return photoUrls; + } + + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + public Pet tags(List tags) { + + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_TAGS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getTags() { + return tags; + } + + + public void setTags(List tags) { + this.tags = tags; + } + + + public Pet status(StatusEnum status) { + + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "pet status in the store") + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public StatusEnum getStatus() { + return status; + } + + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java new file mode 100644 index 0000000000..7ee50c69b0 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/Tag.java @@ -0,0 +1,131 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * Tag + */ +@JsonPropertyOrder({ + Tag.JSON_PROPERTY_ID, + Tag.JSON_PROPERTY_NAME +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class Tag { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + + public Tag id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Tag name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/User.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/User.java new file mode 100644 index 0000000000..ba12953ed3 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/main/java/com/baeldung/petstore/client/model/User.java @@ -0,0 +1,317 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Objects; + +import io.swagger.annotations.ApiModelProperty; + +/** + * User + */ +@JsonPropertyOrder({ + User.JSON_PROPERTY_ID, + User.JSON_PROPERTY_USERNAME, + User.JSON_PROPERTY_FIRST_NAME, + User.JSON_PROPERTY_LAST_NAME, + User.JSON_PROPERTY_EMAIL, + User.JSON_PROPERTY_PASSWORD, + User.JSON_PROPERTY_PHONE, + User.JSON_PROPERTY_USER_STATUS +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]") +public class User { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_USERNAME = "username"; + private String username; + + public static final String JSON_PROPERTY_FIRST_NAME = "firstName"; + private String firstName; + + public static final String JSON_PROPERTY_LAST_NAME = "lastName"; + private String lastName; + + public static final String JSON_PROPERTY_EMAIL = "email"; + private String email; + + public static final String JSON_PROPERTY_PASSWORD = "password"; + private String password; + + public static final String JSON_PROPERTY_PHONE = "phone"; + private String phone; + + public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; + private Integer userStatus; + + + public User id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public User username(String username) { + + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_USERNAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getUsername() { + return username; + } + + + public void setUsername(String username) { + this.username = username; + } + + + public User firstName(String firstName) { + + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_FIRST_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getFirstName() { + return firstName; + } + + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + public User lastName(String lastName) { + + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_LAST_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getLastName() { + return lastName; + } + + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + public User email(String email) { + + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_EMAIL) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getEmail() { + return email; + } + + + public void setEmail(String email) { + this.email = email; + } + + + public User password(String password) { + + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PASSWORD) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getPassword() { + return password; + } + + + public void setPassword(String password) { + this.password = password; + } + + + public User phone(String phone) { + + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PHONE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getPhone() { + return phone; + } + + + public void setPhone(String phone) { + this.phone = phone; + } + + + public User userStatus(Integer userStatus) { + + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "User Status") + @JsonProperty(JSON_PROPERTY_USER_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Integer getUserStatus() { + return userStatus; + } + + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java new file mode 100644 index 0000000000..8854e8e3d4 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java @@ -0,0 +1,167 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.ModelApiResponse; +import com.baeldung.petstore.client.model.Pet; + +import java.io.File; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * API tests for PetApi + */ +@Ignore +public class PetApiTest { + + private final PetApi api = new PetApi(); + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() { + Pet body = null; + api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() { + Long petId = null; + String apiKey = null; + api.deletePet(petId, apiKey); + + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() { + List status = null; + List response = api.findPetsByStatus(status); + + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() { + List tags = null; + List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() { + Long petId = null; + Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() { + Pet body = null; + api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() { + Long petId = null; + String name = null; + String status = null; + api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() { + Long petId = null; + String additionalMetadata = null; + File file = null; + ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + + // TODO: test validations + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java new file mode 100644 index 0000000000..444429bd42 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java @@ -0,0 +1,95 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.Order; + +import java.util.Map; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * API tests for StoreApi + */ +@Ignore +public class StoreApiTest { + + private final StoreApi api = new StoreApi(); + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() { + Long orderId = null; + api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() { + Map response = api.getInventory(); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() { + Long orderId = null; + Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() { + Order body = null; + Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java new file mode 100644 index 0000000000..c73b47ecb2 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java @@ -0,0 +1,161 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.api; + +import com.baeldung.petstore.client.model.User; + +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * API tests for UserApi + */ +@Ignore +public class UserApiTest { + + private final UserApi api = new UserApi(); + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() { + User body = null; + api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() { + List body = null; + api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() { + List body = null; + api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() { + String username = null; + api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() { + String username = null; + User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() { + String username = null; + String password = null; + String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() { + api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() { + String username = null; + User body = null; + api.updateUser(username, body); + + // TODO: test validations + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/CategoryTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/CategoryTest.java new file mode 100644 index 0000000000..7be1b285c3 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/CategoryTest.java @@ -0,0 +1,49 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/ModelApiResponseTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/ModelApiResponseTest.java new file mode 100644 index 0000000000..55f742f862 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/ModelApiResponseTest.java @@ -0,0 +1,57 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/OrderTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/OrderTest.java new file mode 100644 index 0000000000..edbacea028 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/OrderTest.java @@ -0,0 +1,81 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/PetTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/PetTest.java new file mode 100644 index 0000000000..78951acaba --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/PetTest.java @@ -0,0 +1,81 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/TagTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/TagTest.java new file mode 100644 index 0000000000..16efed2570 --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/TagTest.java @@ -0,0 +1,49 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/UserTest.java b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/UserTest.java new file mode 100644 index 0000000000..d84cfb21ca --- /dev/null +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/src/test/java/com/baeldung/petstore/client/model/UserTest.java @@ -0,0 +1,97 @@ +/* + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.3 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.baeldung.petstore.client.model; + +import org.junit.Test; + + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + +} 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/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java rename to spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/com/baeldung/SpringContextTest.java index 79b2b7fa88..54949598aa 100644 --- 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/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java new file mode 100644 index 0000000000..19f0101cf2 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.thymeleaf.mvcdata; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@Configuration +public class BeanConfig { + @Bean + public EmailData emailData() { + return new EmailData(); + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java new file mode 100644 index 0000000000..1bfe3f3428 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java @@ -0,0 +1,63 @@ +package com.baeldung.thymeleaf.mvcdata; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpSession; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestParam; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@Controller +public class EmailController { + private EmailData emailData = new EmailData(); + private ServletContext servletContext; + + public EmailController(ServletContext servletContext) { + this.servletContext = servletContext; + } + + @GetMapping(value = "/email/modelattributes") + public String emailModel(Model model) { + model.addAttribute("emaildata", emailData); + return "mvcdata/email-model-attributes"; + } + + @ModelAttribute("emailModelAttribute") + EmailData emailModelAttribute() { + return emailData; + } + + @GetMapping(value = "/email/requestparameters") + public String emailRequestParameters( + @RequestParam(value = "emailsubject") String emailSubject, + @RequestParam(value = "emailcontent") String emailContent, + @RequestParam(value = "emailaddress") String emailAddress1, + @RequestParam(value = "emailaddress") String emailAddress2, + @RequestParam(value = "emaillocale") String emailLocale) { + return "mvcdata/email-request-parameters"; + } + + @GetMapping("/email/sessionattributes") + public String emailSessionAttributes(HttpSession httpSession) { + httpSession.setAttribute("emaildata", emailData); + return "mvcdata/email-session-attributes"; + } + + @GetMapping("/email/servletcontext") + public String emailServletContext() { + servletContext.setAttribute("emailsubject", emailData.getEmailSubject()); + servletContext.setAttribute("emailcontent", emailData.getEmailBody()); + servletContext.setAttribute("emailaddress", emailData.getEmailAddress1()); + servletContext.setAttribute("emaillocale", emailData.getEmailLocale()); + return "mvcdata/email-servlet-context"; + } + + @GetMapping("/email/beandata") + public String emailBeanData() { + return "mvcdata/email-bean-data"; + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java new file mode 100644 index 0000000000..9dc25bdaa7 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java @@ -0,0 +1,48 @@ +package com.baeldung.thymeleaf.mvcdata.repository; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class EmailData implements Serializable { + private String emailSubject; + private String emailBody; + private String emailLocale; + private String emailAddress1; + private String emailAddress2; + + public EmailData() { + this.emailSubject = "You have received a new message"; + this.emailBody = "Good morning !"; + this.emailLocale = "en-US"; + this.emailAddress1 = "jhon.doe@example.com"; + this.emailAddress2 = "mark.jakob@example.com"; + } + + public String getEmailSubject() { + return this.emailSubject; + } + + public String getEmailBody() { + return this.emailBody; + } + + public String getEmailLocale() { + return this.emailLocale; + } + + public String getEmailAddress1() { + return this.emailAddress1; + } + + public String getEmailAddress2() { + return this.emailAddress2; + } + + public List getEmailAddresses() { + List emailAddresses = new ArrayList<>(); + emailAddresses.add(getEmailAddress1()); + emailAddresses.add(getEmailAddress2()); + return emailAddresses; + } +} diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html new file mode 100644 index 0000000000..59073b51c6 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html @@ -0,0 +1,14 @@ + + + +

Subject

+

Subject

+

Content

+

Body

+

Email address

+

Email address

+

Language

+

Language

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html new file mode 100644 index 0000000000..caf136383a --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html @@ -0,0 +1,16 @@ + + + +

Subject

+

Subject

+

Content

+

+

Email addresses

+

+ +

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html new file mode 100644 index 0000000000..8bcd3e1c62 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html @@ -0,0 +1,20 @@ + + + +

Subject

+

Subject

+

Content

+

+

Email addresses

+

+ +

+

Email address 1

+

+

Email address 2

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html new file mode 100644 index 0000000000..b07573047e --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html @@ -0,0 +1,14 @@ + + + +

Subject

+

+

Content

+

+

Email address

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html new file mode 100644 index 0000000000..9227171fc6 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html @@ -0,0 +1,14 @@ + + + +

Subject

+

+

Content

+

+

Email address

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java b/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java new file mode 100644 index 0000000000..5e1190e174 --- /dev/null +++ b/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.thymeleaf.mvcdata; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc(printOnlyOnFailure = false) +public class EmailControllerUnitTest { + + EmailData emailData = new EmailData(); + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenCallModelAttributes_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/modelattributes")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("You have received a new message"))); + } + + @Test + public void whenCallRequestParameters_thenReturnEmailData() throws Exception { + MultiValueMap params = new LinkedMultiValueMap<>(); + params.add("emailsubject", emailData.getEmailSubject()); + params.add("emailcontent", emailData.getEmailBody()); + params.add("emailaddress", emailData.getEmailAddress1()); + params.add("emailaddress", emailData.getEmailAddress2()); + params.add("emaillocale", emailData.getEmailLocale()); + mockMvc.perform(MockMvcRequestBuilders.get("/email/requestparameters") + .params(params)) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("en-US"))); + } + + @Test + public void whenCallSessionAttributes_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/sessionattributes")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("Good morning !"))); + } + + @Test + public void whenCallServletContext_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/servletcontext")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("jhon.doe@example.com"))); + } + + @Test + public void whenCallBeanData_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/beandata")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("jhon.doe@example.com"))); + } + +} diff --git a/spring-thymeleaf-3/README.md b/spring-thymeleaf-3/README.md new file mode 100644 index 0000000000..a8e234b067 --- /dev/null +++ b/spring-thymeleaf-3/README.md @@ -0,0 +1,6 @@ +## Spring Thymeleaf 3 + +This module contains articles about Spring with Thymeleaf + +## Relevant Articles: +- [Add CSS and JS to Thymeleaf](https://www.baeldung.com/spring-thymeleaf-css-js) diff --git a/spring-thymeleaf-3/pom.xml b/spring-thymeleaf-3/pom.xml new file mode 100644 index 0000000000..7677e50d79 --- /dev/null +++ b/spring-thymeleaf-3/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + spring-thymeleaf-3 + spring-thymeleaf-3 + 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.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.thymeleaf.cssandjs.CssAndJsApplication + JAR + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + ${tomcat7-maven-plugin.version} + + + tomcat-run + + exec-war-only + + package + + / + false + webapp.jar + utf-8 + + + + + + spring-thymeleaf-3 + + + + 1.8 + 1.8 + 2.2 + + + diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java new file mode 100644 index 0000000000..2ccca82497 --- /dev/null +++ b/spring-thymeleaf-3/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-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java new file mode 100644 index 0000000000..fc6c142b8b --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf.cssandjs; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CssAndJsApplication { + public static void main(String[] args) { + SpringApplication.run(CssAndJsApplication.class, args); + } +} diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java new file mode 100644 index 0000000000..b56a7b468e --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java @@ -0,0 +1,15 @@ +package com.baeldung.thymeleaf.cssandjs; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class CssAndJsController { + + @GetMapping("/styled-page") + public String getStyledPage(Model model) { + model.addAttribute("name", "Baeldung Reader"); + return "cssandjs/styledPage"; + } +} diff --git a/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js b/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js new file mode 100644 index 0000000000..e192e6358e --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js @@ -0,0 +1,7 @@ +function showAlert() { + alert("The button was clicked!"); +} + +function showName(name) { + alert("Here's the name: " + name); +} \ No newline at end of file diff --git a/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css b/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css new file mode 100644 index 0000000000..1f57b4616a --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css @@ -0,0 +1,18 @@ +h2 { + font-family: sans-serif; + font-size: 1.5em; + text-transform: uppercase; +} + +strong { + font-weight: 700; + background-color: yellow; +} + +p { + font-family: sans-serif; +} + +label { + font-weight: 600; +} \ No newline at end of file diff --git a/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html b/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html new file mode 100644 index 0000000000..12e4fc9227 --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html @@ -0,0 +1,20 @@ + + + + + Add CSS and JS to Thymeleaf + + + + + +

Carefully Styled Heading

+

+ This is text on which we want to apply very special styling. +

+

+ + + \ No newline at end of file diff --git a/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..b7cfa140f0 --- /dev/null +++ b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java @@ -0,0 +1,13 @@ +package com.baeldung.thymeleaf; + +import org.junit.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class ApplicationIntegrationTest { + + @Test + public void contextLoads() { + + } +} diff --git a/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java new file mode 100644 index 0000000000..365608bd2a --- /dev/null +++ b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.thymeleaf.cssandjs; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.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.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = CssAndJsApplication.class) +public class CssAndJsControllerIntegrationTest { + @Autowired + private WebApplicationContext context; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); + } + + @Test + public void whenCalledGetStyledPage_thenReturnContent() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/styled-page")) + .andExpect(status().isOk()) + .andExpect(view().name("cssandjs/styledPage")) + .andExpect(content().string(containsString("Carefully Styled Heading"))); + } +} diff --git a/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java b/spring-vertx/src/test/java/com/baeldung/SpringContextTest.java similarity index 95% rename from spring-vertx/src/test/java/org/baeldung/SpringContextTest.java rename to spring-vertx/src/test/java/com/baeldung/SpringContextTest.java index 4ce94ec16a..386d83b47b 100644 --- a/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-vertx/src/test/java/com/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/terraform/best-practices/README.md b/terraform/best-practices/README.md new file mode 100644 index 0000000000..fd488b1afb --- /dev/null +++ b/terraform/best-practices/README.md @@ -0,0 +1,10 @@ +# Terraform Sample Code + +This folder contains Terraform project samples that illustrates topics covered in the +"Best practices when using Terraform" article. Setup instructions are available in each sample's folder. + +List of available samples: + + * k8s-basic: "Hello world" project that just connects to a Kubernetes cluster and create a new namespace. + * ec2-basic: "Hello world" project that creates a single EC2 instance + * k8s-modules: A more elaborate sample that creates a simple set of services in a Kubernetes cluster diff --git a/terraform/best-practices/ec2-simple/.gitignore b/terraform/best-practices/ec2-simple/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/ec2-simple/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/ec2-simple/SETUP.md b/terraform/best-practices/ec2-simple/SETUP.md new file mode 100644 index 0000000000..3f906b6933 --- /dev/null +++ b/terraform/best-practices/ec2-simple/SETUP.md @@ -0,0 +1,23 @@ +# EC2 Basic Sample + +This Terraform sample project creates a single EC2 instance in the configured region. + +IMPORTANT NOTICE: In order to run this sample you must have an active AWS Account. As you probably know, creating resources on AWS +may result in additional charges in your bill. We recommend creating a test account to run this test as you can then use AWS's free tier +to play around. When finished, ALWAYS REMEMBER TO DESTROY YOUR RESOURCES !!! + +# Setup instructions + +1. Make sure you have a working AWS environment. Use a simple command such as _aws ec2 describe-instances_ and check its output. + If you get a list of existing EC2 instances, you're good to go. Otherwise, please refer to AWS documentation in order to setup your CLI. +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _aws ec2 describe-instances_. The output should list the newly creates EC2 instance +6. Run _terraform destroy_ to remove the previously creates namespace. + diff --git a/terraform/best-practices/ec2-simple/main.tf b/terraform/best-practices/ec2-simple/main.tf new file mode 100644 index 0000000000..57fb9d1757 --- /dev/null +++ b/terraform/best-practices/ec2-simple/main.tf @@ -0,0 +1,33 @@ +# +# Resource definitions +# + +data "aws_ami" "apache" { + filter { + name = "name" + values = [var.ami_name] + } + + filter { + name = "virtualization-type" + values = ["hvm"] + } + + owners = [var.ami_owner] + + most_recent = true +} + +resource "aws_instance" "web" { + ami = data.aws_ami.apache.id + instance_type = "t2.micro" + subnet_id = aws_subnet.frontend.id +} +resource "aws_subnet" "frontend" { + vpc_id = aws_vpc.apps.id + cidr_block = "10.0.1.0/24" +} + +resource "aws_vpc" "apps" { + cidr_block = "10.0.0.0/16" +} diff --git a/terraform/best-practices/ec2-simple/providers.tf b/terraform/best-practices/ec2-simple/providers.tf new file mode 100644 index 0000000000..fa5826b067 --- /dev/null +++ b/terraform/best-practices/ec2-simple/providers.tf @@ -0,0 +1,6 @@ +# +# Providers definitions +# +provider "aws" { + version = "~> 2.53" +} \ No newline at end of file diff --git a/terraform/best-practices/ec2-simple/variables.tf b/terraform/best-practices/ec2-simple/variables.tf new file mode 100644 index 0000000000..2a7fddcd33 --- /dev/null +++ b/terraform/best-practices/ec2-simple/variables.tf @@ -0,0 +1,15 @@ +# +# Variables +# + +variable "ami_name" { + type = string + description = "AMI name to use for our EC2 instance. Defaults to Ubuntu 18.04 (Bionic)" + default = "ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-*" +} + +variable "ami_owner" { + type = string + description = "AMI Owner ID to use for our EC2 instance. Defaults to 099720109477 (Canonical)" + default = "099720109477" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/.gitignore b/terraform/best-practices/k8s-basic/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/k8s-basic/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/k8s-basic/SETUP.md b/terraform/best-practices/k8s-basic/SETUP.md new file mode 100644 index 0000000000..35e690d88e --- /dev/null +++ b/terraform/best-practices/k8s-basic/SETUP.md @@ -0,0 +1,14 @@ +# Setup instructions + +1. Make sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. + If you get a list of nodes that contains at least one _ready_ module, you're good to go +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _kubectl get namespaces_. The output should now have a new "hello-terraform" namespace. +6. Run _terraform destroy_ to remove the previously creates namespace. diff --git a/terraform/best-practices/k8s-basic/main.tf b/terraform/best-practices/k8s-basic/main.tf new file mode 100644 index 0000000000..5eb3749930 --- /dev/null +++ b/terraform/best-practices/k8s-basic/main.tf @@ -0,0 +1,12 @@ +# +# Resource definitions +# + +resource "kubernetes_namespace" "hello" { + metadata { + labels = { + terraform = "true" + } + name = var.namespace_name + } +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/providers.tf b/terraform/best-practices/k8s-basic/providers.tf new file mode 100644 index 0000000000..385f857a11 --- /dev/null +++ b/terraform/best-practices/k8s-basic/providers.tf @@ -0,0 +1,6 @@ +# +# Providers definitions +# +provider "kubernetes" { + version = "~> 1.11" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/variables.tf b/terraform/best-practices/k8s-basic/variables.tf new file mode 100644 index 0000000000..b9217079bf --- /dev/null +++ b/terraform/best-practices/k8s-basic/variables.tf @@ -0,0 +1,9 @@ +# +# Variables +# + +variable "namespace_name" { + type = string + description = "Name to use for the created namespace" + default = "hello-terraform" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/.gitignore b/terraform/best-practices/k8s-modules/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/k8s-modules/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/k8s-modules/SETUP.md b/terraform/best-practices/k8s-modules/SETUP.md new file mode 100644 index 0000000000..f00247a293 --- /dev/null +++ b/terraform/best-practices/k8s-modules/SETUP.md @@ -0,0 +1,20 @@ +# Kubernetes multimodule sample + +This sample deploys two services behind a Kubernetes ingress. + +# Setup instructions + +1. Make sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. + If you get a list of nodes that contains at least one _ready_ module, you're good to go +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _kubectl get services_. The output should now have a few services. +6. Run _terraform destroy_ to remove the previously creates namespace. + + diff --git a/terraform/best-practices/k8s-modules/main.tf b/terraform/best-practices/k8s-modules/main.tf new file mode 100644 index 0000000000..86426b33db --- /dev/null +++ b/terraform/best-practices/k8s-modules/main.tf @@ -0,0 +1,27 @@ +/* + * Top-level definitions + */ + +//================================================================== Ingress + +module "ingress_www_petshop_com_br" { + source = "./modules/ingress/www.petshop.com.br" + ingress_host = "www.petshop.com.br" +} + +//================================================================== Deployments + +module "SvcCustomer" { + source = "./modules/SvcCustomer" +} + +module "SvcFeedback" { + source = "./modules/SvcFeedback" +} + + + + + + + diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf new file mode 100644 index 0000000000..1ca0c91545 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf @@ -0,0 +1,68 @@ +/* + * SvcCustomer deployment resources + */ + +resource "kubernetes_deployment" "SvcCustomer" { + + metadata { + name = "svccustomer" + labels = { + app = "SvcCustomer" + } + } + + spec { + replicas = 1 + + selector { + match_labels = { + app = "SvcCustomer" + } + } + + template { + metadata { + labels = { + app = "SvcCustomer" + } + } + + spec { + image_pull_secrets { + name = "docker-config" + } + + + container { + image = "inanimate/echo-server" + name = "svccustomer-httpd" + env { + name = "PORT" + value = "80" + } + } + } + } + } +} + +resource "kubernetes_service" "SvcCustomer" { + metadata { + name = "svccustomer" + } + + spec { + + selector = { + app = "SvcCustomer" + } + + session_affinity = "ClientIP" + port { + port = 80 + } + + //type = "LoadBalancer" + } + } + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf new file mode 100644 index 0000000000..8a37fdf375 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf @@ -0,0 +1,3 @@ +/* + * SvcCustomer output values + */ diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf new file mode 100644 index 0000000000..3dfcfcd264 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf @@ -0,0 +1,5 @@ +/* + * SvcCustomer deployment variables + */ + + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf new file mode 100644 index 0000000000..0f84c9163e --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf @@ -0,0 +1,69 @@ +/* + * SvcFeedback deployment resources + */ + +resource "kubernetes_deployment" "SvcFeedback" { + + metadata { + name = "svcfeedback" + labels = { + app = "SvcFeedback" + } + } + + spec { + replicas = 1 + + selector { + match_labels = { + app = "SvcFeedback" + } + } + + template { + metadata { + labels = { + app = "SvcFeedback" + } + } + + spec { + image_pull_secrets { + name = "docker-config" + } + + + container { + image = "inanimate/echo-server" + name = "svcfeedback-httpd" + env { + name = "PORT" + value = "80" + } + } + + } + } + } +} + +resource "kubernetes_service" "SvcFeedback" { + metadata { + name = "svcfeedback" + } + + spec { + + selector = { + app = "SvcFeedback" + } + + session_affinity = "ClientIP" + port { + port = 80 + } + + //type = "LoadBalancer" + } + } + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf new file mode 100644 index 0000000000..e08c17d4b4 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf @@ -0,0 +1,3 @@ +/* + * SvcFeedback output values + */ diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf new file mode 100644 index 0000000000..d8076d41a4 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf @@ -0,0 +1,5 @@ +/* + * SvcFeedback deployment variables + */ + + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf new file mode 100644 index 0000000000..0dbda48981 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf @@ -0,0 +1,41 @@ +/* + * Kubernetes Ingress module + */ +locals { + iname = var.ingress_name == "" ? join("-",["ingress",sha1(uuid())]) : var.ingress_name +} + +resource "kubernetes_ingress" "ingress" { + metadata { + name = local.iname + annotations = map( + "nginx.ingress.kubernetes.io/rewrite-target","/" + ) + } + spec { + rule { + http { + path { + backend { + service_name = "svccustomer" + service_port = 80 + } + path = "/customers" + } + path { + backend { + service_name = "svcfeedback" + service_port = 80 + } + path = "/feedback" + } + } + } +/* + tls { + secret_name = "tls-secret" + } +*/ + } +} + diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf new file mode 100644 index 0000000000..e604417b05 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf @@ -0,0 +1,5 @@ +/* + * Output variables + */ + + diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf new file mode 100644 index 0000000000..9b06128ec5 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf @@ -0,0 +1,20 @@ +/* + * Kubernetes Ingress module + */ + + +variable "ingress_name" { + type = string + description = "Ingress name. Defaults to a random name." + default = "" +} + +variable "ingress_host" { + type = string + description = "Ingress hostname" + default = "www.petshop.com.br" +} + + + + diff --git a/terraform/best-practices/k8s-modules/provider.tf b/terraform/best-practices/k8s-modules/provider.tf new file mode 100644 index 0000000000..bb90d66ecf --- /dev/null +++ b/terraform/best-practices/k8s-modules/provider.tf @@ -0,0 +1,13 @@ +# +# Provider configurations +# This file will *NOT* be overwriten upon regeneration, so it's safe +# to add your own customizations +# + +provider "kubernetes" { + version = "~> 1.10" +} + +provider "random" { + version = "~> 2.2" +} \ No newline at end of file diff --git a/terraform/hello-terraform/.gitignore b/terraform/hello-terraform/.gitignore new file mode 100644 index 0000000000..452502c50f --- /dev/null +++ b/terraform/hello-terraform/.gitignore @@ -0,0 +1,6 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform +hello.txt + diff --git a/terraform/hello-terraform/main.tf b/terraform/hello-terraform/main.tf new file mode 100644 index 0000000000..d6a726fa36 --- /dev/null +++ b/terraform/hello-terraform/main.tf @@ -0,0 +1,7 @@ +provider "local" { + version = "~> 1.4" +} +resource "local_file" "hello" { + content = "Hello, Terraform" + filename = "hello.txt" +} diff --git a/testing-modules/junit5-annotations/pom.xml b/testing-modules/junit5-annotations/pom.xml index d0fba4d21b..9e51d0ab55 100644 --- a/testing-modules/junit5-annotations/pom.xml +++ b/testing-modules/junit5-annotations/pom.xml @@ -46,12 +46,19 @@ ${junit.platform.version} test + + org.assertj + assertj-core + ${assertj-core.version} + test + - 5.6.0 + 5.6.2 1.6.0 2.8.2 + 3.11.1 diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java new file mode 100644 index 0000000000..f19adb13c8 --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java @@ -0,0 +1,5 @@ +package com.baeldung.junit5.templates; + +public interface UserIdGenerator { + String generate(String firstName, String lastName); +} diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java new file mode 100644 index 0000000000..b39b07bc4b --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java @@ -0,0 +1,15 @@ +package com.baeldung.junit5.templates; + +public class UserIdGeneratorImpl implements UserIdGenerator { + private boolean isFeatureEnabled; + + public UserIdGeneratorImpl(boolean isFeatureEnabled) { + this.isFeatureEnabled = isFeatureEnabled; + } + + public String generate(String firstName, String lastName) { + String initialAndLastName = firstName.substring(0, 1) + .concat(lastName); + return isFeatureEnabled ? "bael".concat(initialAndLastName) : initialAndLastName; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java new file mode 100644 index 0000000000..cd8b7b677d --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java @@ -0,0 +1,27 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.ExtensionContext; + +import java.io.IOException; +import java.util.Properties; + +public class DisabledOnQAEnvironmentExtension implements ExecutionCondition { + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + Properties properties = new Properties(); + try { + properties.load(DisabledOnQAEnvironmentExtension.class.getClassLoader() + .getResourceAsStream("application.properties")); + if ("qa".equalsIgnoreCase(properties.getProperty("env"))) { + String reason = String.format("The test '%s' is disabled on QA environment", context.getDisplayName()); + System.out.println(reason); + return ConditionEvaluationResult.disabled(reason); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + return ConditionEvaluationResult.enabled("Test enabled"); + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java new file mode 100644 index 0000000000..76321be101 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java @@ -0,0 +1,26 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +public class GenericTypedParameterResolver implements ParameterResolver { + T data; + + public GenericTypedParameterResolver(T data) { + this.data = data; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + return parameterContext.getParameter() + .getType() + .isInstance(data); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + return data; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java new file mode 100644 index 0000000000..a2306154a6 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UserIdGeneratorImplUnitTest { + @TestTemplate + @ExtendWith(UserIdGeneratorTestInvocationContextProvider.class) + public void whenUserIdRequested_thenUserIdIsReturnedInCorrectFormat(UserIdGeneratorTestCase testCase) { + UserIdGenerator userIdGenerator = new UserIdGeneratorImpl(testCase.isFeatureEnabled()); + + String actualUserId = userIdGenerator.generate(testCase.getFirstName(), testCase.getLastName()); + + assertThat(actualUserId).isEqualTo(testCase.getExpectedUserId()); + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java new file mode 100644 index 0000000000..dd41dd5a27 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java @@ -0,0 +1,37 @@ +package com.baeldung.junit5.templates; + +public class UserIdGeneratorTestCase { + private String displayName; + private boolean isFeatureEnabled; + private String firstName; + private String lastName; + private String expectedUserId; + + public UserIdGeneratorTestCase(String displayName, boolean isFeatureEnabled, String firstName, String lastName, String expectedUserId) { + this.displayName = displayName; + this.isFeatureEnabled = isFeatureEnabled; + this.firstName = firstName; + this.lastName = lastName; + this.expectedUserId = expectedUserId; + } + + public String getDisplayName() { + return displayName; + } + + public boolean isFeatureEnabled() { + return isFeatureEnabled; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public String getExpectedUserId() { + return expectedUserId; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java new file mode 100644 index 0000000000..277ec03f05 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java @@ -0,0 +1,87 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.*; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class UserIdGeneratorTestInvocationContextProvider implements TestTemplateInvocationContextProvider { + + @Override + public boolean supportsTestTemplate(ExtensionContext extensionContext) { + return true; + } + + @Override + public Stream provideTestTemplateInvocationContexts(ExtensionContext extensionContext) { + boolean featureDisabled = false; + boolean featureEnabled = true; + return Stream.of( + featureDisabledContext( + new UserIdGeneratorTestCase( + "Given feature switch disabled When user name is John Smith Then generated userid is JSmith", + featureDisabled, "John", "Smith", "JSmith")), + featureEnabledContext( + new UserIdGeneratorTestCase( + "Given feature switch enabled When user name is John Smith Then generated userid is baelJSmith", + featureEnabled, "John", "Smith", "baelJSmith")) + ); + } + + private TestTemplateInvocationContext featureDisabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) { + return new TestTemplateInvocationContext() { + @Override + public String getDisplayName(int invocationIndex) { + return userIdGeneratorTestCase.getDisplayName(); + } + + @Override + public List getAdditionalExtensions() { + return asList( + new GenericTypedParameterResolver(userIdGeneratorTestCase), + new BeforeTestExecutionCallback() { + @Override + public void beforeTestExecution(ExtensionContext extensionContext) { + System.out.println("BeforeTestExecutionCallback:Disabled context"); + } + }, + new AfterTestExecutionCallback() { + @Override + public void afterTestExecution(ExtensionContext extensionContext) { + System.out.println("AfterTestExecutionCallback:Disabled context"); + } + }); + } + }; + } + + private TestTemplateInvocationContext featureEnabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) { + return new TestTemplateInvocationContext() { + @Override + public String getDisplayName(int invocationIndex) { + return userIdGeneratorTestCase.getDisplayName(); + } + + @Override + public List getAdditionalExtensions() { + return asList( + new GenericTypedParameterResolver(userIdGeneratorTestCase), + new DisabledOnQAEnvironmentExtension(), + new BeforeEachCallback() { + @Override + public void beforeEach(ExtensionContext extensionContext) { + System.out.println("BeforeEachCallback:Enabled context"); + } + }, + new AfterEachCallback() { + @Override + public void afterEach(ExtensionContext extensionContext) { + System.out.println("AfterEachCallback:Enabled context"); + } + }); + } + }; + } +} diff --git a/testing-modules/junit5-annotations/src/test/resources/application.properties b/testing-modules/junit5-annotations/src/test/resources/application.properties new file mode 100644 index 0000000000..bbfa14d866 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/resources/application.properties @@ -0,0 +1 @@ +env=qa \ No newline at end of file diff --git a/testing-modules/junit5-migration/README.md b/testing-modules/junit5-migration/README.md index 84e540b466..5cc9db8bd3 100644 --- a/testing-modules/junit5-migration/README.md +++ b/testing-modules/junit5-migration/README.md @@ -5,6 +5,6 @@ This module contains articles about migrating to JUnit 5. The code for the JUnit 4 - JUnit 5 E-book is in `com.baeldung.junit4` and `com.baeldung.junit5`. ### Relevant Articles: -- [JUnit 5 Migration](https://www.baeldung.com/junit-5-migration) + - [A Quick JUnit vs TestNG Comparison](https://www.baeldung.com/junit-vs-testng) - [Assertions in JUnit 4 and JUnit 5](https://www.baeldung.com/junit-assertions) diff --git a/testing-modules/mockito-2/README.md b/testing-modules/mockito-2/README.md index d7069949e4..6c9ddee01d 100644 --- a/testing-modules/mockito-2/README.md +++ b/testing-modules/mockito-2/README.md @@ -3,6 +3,5 @@ - [Mockito’s Java 8 Features](https://www.baeldung.com/mockito-2-java-8) - [Lazy Verification with Mockito 2](https://www.baeldung.com/mockito-2-lazy-verification) - [Mockito Strict Stubbing and The UnnecessaryStubbingException](https://www.baeldung.com/mockito-unnecessary-stubbing-exception) -- [Quick Guide to BDDMockito](https://www.baeldung.com/bdd-mockito) -- [Mockito – Using Spies](https://www.baeldung.com/mockito-spy) - [Mockito and Fluent APIs](https://www.baeldung.com/mockito-fluent-apis) +- [Mocking the ObjectMapper readValue() Method](https://www.baeldung.com/mockito-mock-jackson-read-value) diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 76608a3039..340af89c82 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -14,8 +14,23 @@ ../../ + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + + + 2.21.0 + 2.10.3 diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/Book.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/Book.java new file mode 100644 index 0000000000..fa021f8cba --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/Book.java @@ -0,0 +1,58 @@ +package com.baeldung.mockito.additionalanswers; + +public class Book { + + private Long bookId; + + private String title; + + private String author; + + private int numberOfPages; + + public Book(String title, String author, int numberOfPages) { + this.title = title; + this.author = author; + this.numberOfPages = numberOfPages; + } + + public Book(Long bookId, String title, String author, int numberOfPages) { + this.bookId = bookId; + this.title = title; + this.author = author; + this.numberOfPages = numberOfPages; + } + + public Long getBookId() { + return bookId; + } + + public void setBookId(Long bookId) { + this.bookId = bookId; + } + + 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 int getNumberOfPages() { + return numberOfPages; + } + + public void setNumberOfPages(int numberOfPages) { + this.numberOfPages = numberOfPages; + } +} + diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java new file mode 100644 index 0000000000..677ee502b4 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java @@ -0,0 +1,24 @@ +package com.baeldung.mockito.additionalanswers; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class BookRepository { + public Book getByBookId(Long bookId) { + return new Book(bookId, "To Kill a Mocking Bird", "Harper Lee", 256); + } + + public Book save(Book book) { + return new Book(book.getBookId(), book.getTitle(), book.getAuthor(), book.getNumberOfPages()); + } + + public Book selectRandomBook(Book bookOne, Book bookTwo, Book bookThree) { + List selection = new ArrayList<>(); + selection.add(bookOne); + selection.add(bookTwo); + selection.add(bookThree); + Random random = new Random(); + return selection.get(random.nextInt(selection.size())); + } +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java new file mode 100644 index 0000000000..4499a6524b --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java @@ -0,0 +1,22 @@ +package com.baeldung.mockito.additionalanswers; + +public class BookService { + private final BookRepository bookRepository; + + public BookService(BookRepository bookRepository) { + this.bookRepository = bookRepository; + } + + public Book getByBookId(Long id) { + return bookRepository.getByBookId(id); + } + + public Book save(Book book) { + return bookRepository.save(book); + } + + public Book selectRandomBook(Book book1, Book book2, Book book3) { + return bookRepository.selectRandomBook(book1, book2, book3); + } +} + diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/Flower.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/Flower.java new file mode 100644 index 0000000000..bc366a39f9 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/Flower.java @@ -0,0 +1,32 @@ +package com.baeldung.mockito.objectmapper; + +public class Flower { + + private String name; + private Integer petals; + + public Flower(String name, Integer petals) { + this.name = name; + this.petals = petals; + } + + public Flower() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getPetals() { + return petals; + } + + public void setPetals(Integer petals) { + this.petals = petals; + } + +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidator.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidator.java new file mode 100644 index 0000000000..91bad66e6d --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidator.java @@ -0,0 +1,17 @@ +package com.baeldung.mockito.objectmapper; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class FlowerJsonStringValidator { + private ObjectMapper objectMapper; + + public FlowerJsonStringValidator(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + public boolean flowerHasPetals(String jsonFlowerAsString) throws JsonProcessingException { + Flower flower = objectMapper.readValue(jsonFlowerAsString, Flower.class); + return flower.getPetals() > 0; + } +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java new file mode 100644 index 0000000000..ee32bcf70c --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.mockito.additionalanswers; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.AdditionalAnswers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; + +@RunWith(MockitoJUnitRunner.class) +public class BookServiceUnitTest { + @InjectMocks + private BookService bookService; + + @Mock + private BookRepository bookRepository; + + @Test + public void givenSaveMethodMocked_whenSaveInvoked_ThenReturnFirstArgument_UnitTest() { + Book book = new Book("To Kill a Mocking Bird", "Harper Lee", 256); + Mockito.when(bookRepository.save(any(Book.class))).then(AdditionalAnswers.returnsFirstArg()); + + Book savedBook = bookService.save(book); + + assertEquals(savedBook, book); + } + + @Test + public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnSecondArgument_UnitTest() { + Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456); + Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); + Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); + + Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsSecondArg()); + + Book secondBook = bookService.selectRandomBook(book1, book2, book3); + + assertEquals(secondBook, book2); + } + + @Test + public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnLastArgument_UnitTest() { + Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456); + Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); + Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); + + Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsLastArg()); + + Book lastBook = bookService.selectRandomBook(book1, book2, book3); + assertEquals(lastBook, book3); + } + + @Test + public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnArgumentAtIndex_UnitTest() { + Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456); + Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); + Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); + + Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsArgAt(1)); + + Book bookOnIndex = bookService.selectRandomBook(book1, book2, book3); + + assertEquals(bookOnIndex, book2); + } +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidatorUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidatorUnitTest.java new file mode 100644 index 0000000000..31c3f0d01d --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/objectmapper/FlowerJsonStringValidatorUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.mockito.objectmapper; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class FlowerJsonStringValidatorUnitTest { + + @Mock + private ObjectMapper objectMapper; + + private FlowerJsonStringValidator flowerJsonStringValidator; + + @BeforeEach + public void setUp() { + flowerJsonStringValidator = new FlowerJsonStringValidator(objectMapper); + } + + @Test + public void whenCallingHasPetalsWithPetals_thenReturnsTrue() throws JsonProcessingException { + Flower rose = new Flower("testFlower", 100); + + when(objectMapper.readValue(anyString(), eq(Flower.class))).thenReturn(rose); + + assertTrue(flowerJsonStringValidator.flowerHasPetals("this can be a very long json flower")); + + verify(objectMapper, times(1)).readValue(anyString(), eq(Flower.class)); + } + + @Test + public void whenCallingHasPetalsWithZeroPetal_thenReturnsFalse() throws JsonProcessingException { + Flower rose = new Flower("testFlowerWithoutPetal", 0); + + when(objectMapper.readValue(anyString(), eq(Flower.class))).thenReturn(rose); + + assertFalse(flowerJsonStringValidator.flowerHasPetals("this can be a very long json flower")); + + verify(objectMapper, times(1)).readValue(anyString(), eq(Flower.class)); + } +} diff --git a/testing-modules/mockito/README.md b/testing-modules/mockito/README.md index 7cef9ee8f6..5f307c2f0b 100644 --- a/testing-modules/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -8,8 +8,6 @@ - [Mockito When/Then Cookbook](https://www.baeldung.com/mockito-behavior) - [Getting Started with Mockito @Mock, @Spy, @Captor and @InjectMocks](https://www.baeldung.com/mockito-annotations) - [Mockito’s Mock Methods](https://www.baeldung.com/mockito-mock-methods) -- [Introduction to PowerMock](https://www.baeldung.com/intro-to-powermock) -- [Mocking of Private Methods Using PowerMock](https://www.baeldung.com/powermock-private-method) - [Mocking Exception Throwing using Mockito](https://www.baeldung.com/mockito-exceptions) - [Mocking Void Methods with Mockito](https://www.baeldung.com/mockito-void-methods) - [Mock Final Classes and Methods with Mockito](https://www.baeldung.com/mockito-final) diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index aae3981c66..ea5ef4c322 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -44,19 +44,6 @@ - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - test - org.springframework.boot spring-boot-starter diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java index 731183bae2..27e3258efb 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java @@ -75,7 +75,53 @@ public class MockitoAnnotationUnitTest { Mockito.doReturn(100).when(spiedList).size(); assertEquals(100, spiedList.size()); } + + @Test + public void whenSpyingOnList_thenCorrect() { + List list = new ArrayList(); + List spyList = Mockito.spy(list); + + spyList.add("one"); + spyList.add("two"); + + Mockito.verify(spyList).add("one"); + Mockito.verify(spyList).add("two"); + + assertEquals(2, spyList.size()); + } + @Test + public void whenUsingTheSpyAnnotation_thenObjectIsSpied() { + spiedList.add("one"); + spiedList.add("two"); + + Mockito.verify(spiedList).add("one"); + Mockito.verify(spiedList).add("two"); + + assertEquals(2, spiedList.size()); + } + + @Test + public void whenStubASpy_thenStubbed() { + List list = new ArrayList(); + List spyList = Mockito.spy(list); + + assertEquals(0, spyList.size()); + + Mockito.doReturn(100).when(spyList).size(); + assertEquals(100, spyList.size()); + } + + @Test + public void whenCreateSpy_thenCreate() { + List spyList = Mockito.spy(new ArrayList<>()); + + spyList.add("one"); + Mockito.verify(spyList).add("one"); + + assertEquals(1, spyList.size()); + } + @Test public void whenNotUseCaptorAnnotation_thenCorrect() { final List mockList = Mockito.mock(List.class); diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java b/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java index 799e7721e0..1aafa28a6a 100644 --- a/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java +++ b/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java @@ -15,5 +15,5 @@ public interface ExpectationsCollaborator { void methodForArgThat(Object o); String methodReturnsString(); int methodReturnsInt(); - Object methodForDelegate(int i); + int methodForDelegate(int i); } diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java index 8b0c3ab4ec..1ff90111d1 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java @@ -1,21 +1,21 @@ package com.baeldung.jmockit; -import com.baeldung.jmockit.ExpectationsCollaborator; -import com.baeldung.jmockit.Model; -import mockit.Delegate; -import mockit.Expectations; -import mockit.Mocked; -import mockit.Verifications; -import mockit.integration.junit4.JMockit; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Test; import org.junit.runner.RunWith; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; +import mockit.Delegate; +import mockit.Expectations; +import mockit.Mocked; +import mockit.Verifications; +import mockit.integration.junit4.JMockit; @RunWith(JMockit.class) @SuppressWarnings("unchecked") @@ -112,17 +112,16 @@ public class ExpectationsIntegrationTest { result = "foo"; result = new Exception(); result = "bar"; - mock.methodReturnsInt(); - result = new int[]{1, 2, 3}; - mock.methodReturnsString(); returns("foo", "bar"); mock.methodReturnsInt(); + result = new int[]{1, 2, 3}; result = 1; }}; assertEquals("Should return foo", "foo", mock.methodReturnsString()); try { mock.methodReturnsString(); + fail("Shouldn't reach here"); } catch (Exception e) { // NOOP } @@ -134,13 +133,14 @@ public class ExpectationsIntegrationTest { assertEquals("Should return bar", "bar", mock.methodReturnsString()); assertEquals("Should return 1", 1, mock.methodReturnsInt()); } - + @Test public void testDelegate(@Mocked ExpectationsCollaborator mock) { new Expectations() {{ mock.methodForDelegate(anyInt); - result = new Delegate() { - public int delegate(int i) throws Exception { + + result = new Delegate() { + int delegate(int i) throws Exception { if (i < 3) { return 5; } else { @@ -153,6 +153,7 @@ public class ExpectationsIntegrationTest { assertEquals("Should return 5", 5, mock.methodForDelegate(1)); try { mock.methodForDelegate(3); + fail("Shouldn't reach here"); } catch (Exception e) { } } diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index f4a8368581..951909b36f 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -40,6 +40,7 @@ xmlunit-2 junit-4 testing-libraries + powermock diff --git a/testing-modules/powermock/README.md b/testing-modules/powermock/README.md new file mode 100644 index 0000000000..df9fb0088c --- /dev/null +++ b/testing-modules/powermock/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Introduction to PowerMock](https://www.baeldung.com/intro-to-powermock) +- [Mocking of Private Methods Using PowerMock](https://www.baeldung.com/powermock-private-method) diff --git a/testing-modules/powermock/pom.xml b/testing-modules/powermock/pom.xml new file mode 100644 index 0000000000..21b2e98af0 --- /dev/null +++ b/testing-modules/powermock/pom.xml @@ -0,0 +1,33 @@ + + + + testing-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + powermock + + + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.version} + test + + + + + 2.21.0 + 2.0.2 + + \ No newline at end of file diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java similarity index 100% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorUnitTest.java diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java similarity index 98% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java rename to testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java index 4943b0486a..1b2bb99896 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java +++ b/testing-modules/powermock/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoUnitTest.java @@ -68,7 +68,7 @@ public class PowerMockitoUnitTest { when(mock.finalMethod()).thenReturn("I am a final mock method."); returnValue = mock.finalMethod(); - verify(mock,times(3)).finalMethod(); + verify(mock).finalMethod(); assertEquals("I am a final mock method.", returnValue); when(mock, "privateMethod").thenReturn("I am a private mock method."); diff --git a/twitter4j/pom.xml b/twitter4j/pom.xml index 6d98e2fe58..274b5c75c3 100644 --- a/twitter4j/pom.xml +++ b/twitter4j/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - Twitter4J - Twitter4J + twitter4J + twitter4J jar diff --git a/vavr-2/README.md b/vavr-2/README.md new file mode 100644 index 0000000000..71814a08fd --- /dev/null +++ b/vavr-2/README.md @@ -0,0 +1,8 @@ +## Vavr + +This module contains articles about Vavr. + +### Relevant Articles: +- [Introduction to Vavr’s Either](https://www.baeldung.com/vavr-either) +- [Interoperability Between Java and Vavr](https://www.baeldung.com/java-vavr) +- [[<-- prev]](/vavr) diff --git a/vavr-2/pom.xml b/vavr-2/pom.xml new file mode 100644 index 0000000000..d20dd9afef --- /dev/null +++ b/vavr-2/pom.xml @@ -0,0 +1,27 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + vavr-2 + vavr-2 + jar + + + + io.vavr + vavr-test + ${vavr.version} + + + + + 0.9.1 + + \ No newline at end of file diff --git a/vavr/src/main/java/com/baeldung/vavr/either/EitherDemo.java b/vavr-2/src/main/java/com/baeldung/vavr/either/EitherDemo.java similarity index 100% rename from vavr/src/main/java/com/baeldung/vavr/either/EitherDemo.java rename to vavr-2/src/main/java/com/baeldung/vavr/either/EitherDemo.java diff --git a/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java b/vavr-2/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java similarity index 100% rename from vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java rename to vavr-2/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java diff --git a/vavr/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java b/vavr-2/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java similarity index 100% rename from vavr/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java rename to vavr-2/src/test/java/com/baeldung/vavr/interoperability/CollectionsInteroperabilityUnitTest.java diff --git a/vavr/README.md b/vavr/README.md index 2b8bb25356..e04e02069f 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -13,5 +13,4 @@ This module contains articles about Vavr. - [Guide to Collections API in Vavr](https://www.baeldung.com/vavr-collections) - [Collection Factory Methods for Vavr](https://www.baeldung.com/vavr-collection-factory-methods) - [Introduction to Future in Vavr](https://www.baeldung.com/vavr-future) -- [Introduction to Vavr’s Either](https://www.baeldung.com/vavr-either) -- [Interoperability Between Java and Vavr](https://www.baeldung.com/java-vavr) +- [[next -->]](/vavr-2)