diff --git a/JGit/pom.xml b/JGit/pom.xml new file mode 100644 index 0000000000..93c49edb92 --- /dev/null +++ b/JGit/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + com.baeldung + JGitSnippets + 1.0-SNAPSHOT + jar + http://maven.apache.org + + UTF-8 + 1.8 + 1.8 + + + + jgit-repository + https://repo.eclipse.org/content/groups/releases/ + + + + + + + org.eclipse.jgit + org.eclipse.jgit + 4.5.0.201609210915-r + + + org.eclipse.jgit + org.eclipse.jgit.archive + 4.5.0.201609210915-r + + + commons-io + commons-io + 2.5 + + + org.slf4j + slf4j-simple + 1.7.21 + + + junit + junit + 4.12 + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + + + + + \ No newline at end of file diff --git a/JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java b/JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java new file mode 100644 index 0000000000..1702efc315 --- /dev/null +++ b/JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java @@ -0,0 +1,30 @@ +package com.baeldung.jgit; + +import java.io.File; +import java.io.IOException; +import org.apache.commons.io.FileUtils; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; + +/** + * Simple snippet which shows how to create a new repository + * + * + */ +public class CreateNewRepository { + + public static void main(String[] args) throws IOException, IllegalStateException, GitAPIException { + // prepare a new folder + File localPath = File.createTempFile("TestGitRepository", ""); + if(!localPath.delete()) { + throw new IOException("Could not delete temporary file " + localPath); + } + + // create the directory + try (Git git = Git.init().setDirectory(localPath).call()) { + System.out.println("Having repository: " + git.getRepository().getDirectory()); + } + + FileUtils.deleteDirectory(localPath); + } +} diff --git a/JGit/src/main/java/com/baeldung/jgit/OpenRepository.java b/JGit/src/main/java/com/baeldung/jgit/OpenRepository.java new file mode 100644 index 0000000000..671df2a844 --- /dev/null +++ b/JGit/src/main/java/com/baeldung/jgit/OpenRepository.java @@ -0,0 +1,65 @@ +package com.baeldung.jgit; + +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; +import java.io.File; +import java.io.IOException; + +/** + * Simple snippet which shows how to open an existing repository + * + * + */ +public class OpenRepository { + + public static void main(String[] args) throws IOException, GitAPIException { + // first create a test-repository, the return is including the .get directory here! + File repoDir = createSampleGitRepo(); + + // now open the resulting repository with a FileRepositoryBuilder + FileRepositoryBuilder builder = new FileRepositoryBuilder(); + try (Repository repository = builder.setGitDir(repoDir) + .readEnvironment() // scan environment GIT_* variables + .findGitDir() // scan up the file system tree + .build()) { + System.out.println("Having repository: " + repository.getDirectory()); + + // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree) + Ref head = repository.exactRef("refs/heads/master"); + System.out.println("Ref of refs/heads/master: " + head); + } + } + + private static File createSampleGitRepo() throws IOException, GitAPIException { + try (Repository repository = Helper.createNewRepository()) { + System.out.println("Temporary repository at " + repository.getDirectory()); + + // create the file + File myfile = new File(repository.getDirectory().getParent(), "testfile"); + if(!myfile.createNewFile()) { + throw new IOException("Could not create file " + myfile); + } + + // run the add-call + try (Git git = new Git(repository)) { + git.add() + .addFilepattern("testfile") + .call(); + + + // and then commit the changes + git.commit() + .setMessage("Added testfile") + .call(); + } + + System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); + + return repository.getDirectory(); + } + } +} diff --git a/JGit/src/main/java/com/baeldung/jgit/helper/Helper.java b/JGit/src/main/java/com/baeldung/jgit/helper/Helper.java new file mode 100644 index 0000000000..39d7b767d2 --- /dev/null +++ b/JGit/src/main/java/com/baeldung/jgit/helper/Helper.java @@ -0,0 +1,33 @@ + +package com.baeldung.jgit.helper; + +import java.io.File; +import java.io.IOException; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; + +public class Helper { + + public static Repository openJGitRepository() throws IOException { + FileRepositoryBuilder builder = new FileRepositoryBuilder(); + return builder + .readEnvironment() // scan environment GIT_* variables + .findGitDir() // scan up the file system tree + .build(); + } + + public static Repository createNewRepository() throws IOException { + // prepare a new folder + File localPath = File.createTempFile("TestGitRepository", ""); + if(!localPath.delete()) { + throw new IOException("Could not delete temporary file " + localPath); + } + + // create the directory + Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git")); + repository.create(); + + return repository; + } + +} diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java b/JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java new file mode 100644 index 0000000000..314366f08c --- /dev/null +++ b/JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java @@ -0,0 +1,36 @@ +package com.baeldung.jgit.porcelain; + +import java.io.File; +import java.io.IOException; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; + +/** + * Simple snippet which shows how to add a file to the index + * + * + */ +public class AddFile { + + public static void main(String[] args) throws IOException, GitAPIException { + // prepare a new test-repository + try (Repository repository = Helper.createNewRepository()) { + try (Git git = new Git(repository)) { + // create the file + File myfile = new File(repository.getDirectory().getParent(), "testfile"); + if(!myfile.createNewFile()) { + throw new IOException("Could not create file " + myfile); + } + + // run the add-call + git.add() + .addFilepattern("testfile") + .call(); + + System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); + } + } + } +} diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java b/JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java new file mode 100644 index 0000000000..4c0956ebf8 --- /dev/null +++ b/JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java @@ -0,0 +1,51 @@ +package com.baeldung.jgit.porcelain; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; + +/** + * Simple snippet which shows how to commit all files + * + * + */ +public class CommitAll { + + public static void main(String[] args) throws IOException, GitAPIException { + // prepare a new test-repository + try (Repository repository = Helper.createNewRepository()) { + try (Git git = new Git(repository)) { + // create the file + File myfile = new File(repository.getDirectory().getParent(), "testfile"); + if(!myfile.createNewFile()) { + throw new IOException("Could not create file " + myfile); + } + + // Stage all files in the repo including new files + git.add().addFilepattern(".").call(); + + // and then commit the changes. + git.commit() + .setMessage("Commit all changes including additions") + .call(); + + try(PrintWriter writer = new PrintWriter(myfile)) { + writer.append("Hello, world!"); + } + + // Stage all changed files, omitting new files, and commit with one command + git.commit() + .setAll(true) + .setMessage("Commit changes to all files") + .call(); + + + System.out.println("Committed all changes to repository at " + repository.getDirectory()); + } + } + } +} diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java b/JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java new file mode 100644 index 0000000000..0f735daf8c --- /dev/null +++ b/JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java @@ -0,0 +1,56 @@ +package com.baeldung.jgit.porcelain; + +import java.io.IOException; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.ObjectId; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.revwalk.RevWalk; + +/** + * Simple snippet which shows how to create a tag + * + * + */ +public class CreateAndDeleteTag { + + public static void main(String[] args) throws IOException, GitAPIException { + // prepare test-repository + try (Repository repository = Helper.openJGitRepository()) { + try (Git git = new Git(repository)) { + // remove the tag before creating it + git.tagDelete().setTags("tag_for_testing").call(); + + // set it on the current HEAD + Ref tag = git.tag().setName("tag_for_testing").call(); + System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); + + // remove the tag again + git.tagDelete().setTags("tag_for_testing").call(); + + // read some other commit and set the tag on it + ObjectId id = repository.resolve("HEAD^"); + try (RevWalk walk = new RevWalk(repository)) { + RevCommit commit = walk.parseCommit(id); + tag = git.tag().setObjectId(commit).setName("tag_for_testing").call(); + System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); + + // remove the tag again + git.tagDelete().setTags("tag_for_testing").call(); + + // create an annotated tag + tag = git.tag().setName("tag_for_testing").setAnnotated(true).call(); + System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); + + // remove the tag again + git.tagDelete().setTags("tag_for_testing").call(); + + walk.dispose(); + } + } + } + } +} diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java new file mode 100644 index 0000000000..cb476b9d9e --- /dev/null +++ b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java @@ -0,0 +1,74 @@ +package com.baeldung.jgit.porcelain; + +import java.io.IOException; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevCommit; + +/** + * Simple snippet which shows how to get the commit-ids for a file to provide log information. + * + * + */ +public class Log { + + @SuppressWarnings("unused") + public static void main(String[] args) throws IOException, GitAPIException { + try (Repository repository = Helper.openJGitRepository()) { + try (Git git = new Git(repository)) { + Iterable logs = git.log() + .call(); + int count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits overall on current branch"); + + logs = git.log() + .add(repository.resolve("remotes/origin/testbranch")) + .call(); + count = 0; + for (RevCommit rev : logs) { + System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits overall on test-branch"); + + logs = git.log() + .all() + .call(); + count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits overall in repository"); + + logs = git.log() + // for all log.all() + .addPath("README.md") + .call(); + count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits on README.md"); + + logs = git.log() + // for all log.all() + .addPath("pom.xml") + .call(); + count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits on pom.xml"); + } + } + } +} diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java b/JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java new file mode 100644 index 0000000000..acad4e395f --- /dev/null +++ b/JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java @@ -0,0 +1,31 @@ +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.lib.ObjectLoader; +import org.eclipse.jgit.lib.ObjectReader; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevWalk; +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 JGitBugTest { + @Test + public void testRevWalkDisposeClosesReader() throws IOException { + try (Repository repo = Helper.openJGitRepository()) { + try (ObjectReader reader = repo.newObjectReader()) { + try (RevWalk walk = new RevWalk(reader)) { + walk.dispose(); + + Ref head = repo.exactRef("refs/heads/master"); + System.out.println("Found head: " + head); + + ObjectLoader loader = reader.open(head.getObjectId()); + assertNotNull(loader); + } + } + } + } +} diff --git a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainTest.java b/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainTest.java new file mode 100644 index 0000000000..ce3a41e657 --- /dev/null +++ b/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainTest.java @@ -0,0 +1,17 @@ +package com.baeldung.jgit.porcelain; + +import org.junit.Test; + +public class PorcelainTest { + @Test + public void runSamples() throws Exception { + // simply call all the samples to see any severe problems with the samples + AddFile.main(null); + + CommitAll.main(null); + + CreateAndDeleteTag.main(null); + + Log.main(null); + } +} diff --git a/algorithms/pom.xml b/algorithms/pom.xml new file mode 100644 index 0000000000..0c85a19534 --- /dev/null +++ b/algorithms/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + com.baeldung + algorithms + 0.0.1-SNAPSHOT + + + 4.12 + 3.6.0 + 1.5.0 + + + + + junit + junit + ${junit.version} + test + + + + + install + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + + \ No newline at end of file diff --git a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java b/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java new file mode 100644 index 0000000000..b82eedbc3f --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java @@ -0,0 +1,59 @@ +package com.baeldung.algorithms.dijkstra; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Map.Entry; +import java.util.Set; + +public class Dijkstra { + + public static Graph calculateShortestPathFromSource(Graph graph, Node source) { + + source.setDistance(0); + + Set settledNodes = new HashSet<>(); + Set unsettledNodes = new HashSet<>(); + unsettledNodes.add(source); + + while (unsettledNodes.size() != 0) { + Node currentNode = getLowestDistanceNode(unsettledNodes); + unsettledNodes.remove(currentNode); + for (Entry adjacencyPair : currentNode + .getAdjacentNodes() + .entrySet()) { + Node adjacentNode = adjacencyPair.getKey(); + Integer edgeWeigh = adjacencyPair.getValue(); + + if (!settledNodes.contains(adjacentNode)) { + CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode); + unsettledNodes.add(adjacentNode); + } + } + settledNodes.add(currentNode); + } + return graph; + } + + private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) { + Integer sourceDistance = sourceNode.getDistance(); + if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) { + evaluationNode.setDistance(sourceDistance + edgeWeigh); + LinkedList shortestPath = new LinkedList<>(sourceNode.getShortestPath()); + shortestPath.add(sourceNode); + evaluationNode.setShortestPath(shortestPath); + } + } + + private static Node getLowestDistanceNode(Set unsettledNodes) { + Node lowestDistanceNode = null; + int lowestDistance = Integer.MAX_VALUE; + for (Node node : unsettledNodes) { + int nodeDistance = node.getDistance(); + if (nodeDistance < lowestDistance) { + lowestDistance = nodeDistance; + lowestDistanceNode = node; + } + } + return lowestDistanceNode; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java b/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java new file mode 100644 index 0000000000..f24d6ae60e --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java @@ -0,0 +1,21 @@ +package com.baeldung.algorithms.dijkstra; + +import java.util.HashSet; +import java.util.Set; + +public class Graph { + + private Set nodes = new HashSet<>(); + + public void addNode(Node nodeA) { + nodes.add(nodeA); + } + + public Set getNodes() { + return nodes; + } + + public void setNodes(Set nodes) { + this.nodes = nodes; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Node.java new file mode 100644 index 0000000000..b00127a259 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Node.java @@ -0,0 +1,58 @@ +package com.baeldung.algorithms.dijkstra; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public class Node { + + private String name; + + private LinkedList shortestPath = new LinkedList<>(); + + private Integer distance = Integer.MAX_VALUE; + + private Map adjacentNodes = new HashMap<>(); + + public Node(String name) { + this.name = name; + } + + public void addDestination(Node destination, int distance) { + adjacentNodes.put(destination, distance); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map getAdjacentNodes() { + return adjacentNodes; + } + + public void setAdjacentNodes(Map adjacentNodes) { + this.adjacentNodes = adjacentNodes; + } + + public Integer getDistance() { + return distance; + } + + public void setDistance(Integer distance) { + this.distance = distance; + } + + public List getShortestPath() { + return shortestPath; + } + + public void setShortestPath(LinkedList shortestPath) { + this.shortestPath = shortestPath; + } + +} diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java b/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java new file mode 100644 index 0000000000..86ee62c827 --- /dev/null +++ b/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java @@ -0,0 +1,85 @@ +package algorithms; + +import com.baeldung.algorithms.dijkstra.Dijkstra; +import com.baeldung.algorithms.dijkstra.Graph; +import com.baeldung.algorithms.dijkstra.Node; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class DijkstraAlgorithmTest { + + @Test + public void whenSPPSolved_thenCorrect() { + + Node nodeA = new Node("A"); + Node nodeB = new Node("B"); + Node nodeC = new Node("C"); + Node nodeD = new Node("D"); + Node nodeE = new Node("E"); + Node nodeF = new Node("F"); + + nodeA.addDestination(nodeB, 10); + nodeA.addDestination(nodeC, 15); + + nodeB.addDestination(nodeD, 12); + nodeB.addDestination(nodeF, 15); + + nodeC.addDestination(nodeE, 10); + + nodeD.addDestination(nodeE, 2); + nodeD.addDestination(nodeF, 1); + + nodeF.addDestination(nodeE, 5); + + Graph graph = new Graph(); + + graph.addNode(nodeA); + graph.addNode(nodeB); + graph.addNode(nodeC); + graph.addNode(nodeD); + graph.addNode(nodeE); + graph.addNode(nodeF); + + graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA); + + List shortestPathForNodeB = Arrays.asList(nodeA); + List shortestPathForNodeC = Arrays.asList(nodeA); + List shortestPathForNodeD = Arrays.asList(nodeA, nodeB); + List shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD); + List shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD); + + for (Node node : graph.getNodes()) { + switch (node.getName()) { + case "B": + assertTrue(node + .getShortestPath() + .equals(shortestPathForNodeB)); + break; + case "C": + assertTrue(node + .getShortestPath() + .equals(shortestPathForNodeC)); + break; + case "D": + assertTrue(node + .getShortestPath() + .equals(shortestPathForNodeD)); + break; + case "E": + assertTrue(node + .getShortestPath() + .equals(shortestPathForNodeE)); + break; + case "F": + assertTrue(node + .getShortestPath() + .equals(shortestPathForNodeF)); + break; + } + } + } +} diff --git a/annotations/pom.xml b/annotations/pom.xml index f691674cf1..0ddc17f8a7 100644 --- a/annotations/pom.xml +++ b/annotations/pom.xml @@ -1,7 +1,6 @@ - + parent-modules com.baeldung diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml index e2cd7d344a..6849452908 100644 --- a/apache-cxf/pom.xml +++ b/apache-cxf/pom.xml @@ -5,20 +5,20 @@ apache-cxf 0.0.1-SNAPSHOT pom - + cxf-introduction cxf-spring cxf-jaxrs-implementation cxf-aegis - + 4.12 3.6.0 1.5.0 - + junit @@ -27,7 +27,7 @@ test - + install diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml index 4dd61d8f4e..6f89497a7d 100644 --- a/apache-fop/pom.xml +++ b/apache-fop/pom.xml @@ -1,154 +1,155 @@ - - 4.0.0 - com.baeldung - apache-fop - 0.1-SNAPSHOT + + 4.0.0 + com.baeldung + apache-fop + 0.1-SNAPSHOT - apache-fop + apache-fop - + - + - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + - + - - junit - junit - ${junit.version} - test - + + junit + junit + ${junit.version} + test + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - + + org.mockito + mockito-core + ${mockito.version} + test + - + - - org.apache.xmlgraphics - fop - ${fop.version} - - - org.apache.avalon.framework - avalon-framework-api - - - org.apache.avalon.framework - avalon-framework-impl - - - + + org.apache.xmlgraphics + fop + ${fop.version} + + + org.apache.avalon.framework + avalon-framework-api + + + org.apache.avalon.framework + avalon-framework-impl + + + - - avalon-framework - avalon-framework-api - ${avalon-framework.version} - - - avalon-framework - avalon-framework-impl - ${avalon-framework.version} - + + avalon-framework + avalon-framework-api + ${avalon-framework.version} + + + avalon-framework + avalon-framework-impl + ${avalon-framework.version} + - - org.dbdoclet - dbdoclet - ${dbdoclet.version} - + + org.dbdoclet + dbdoclet + ${dbdoclet.version} + - - org.dbdoclet - herold - 6.1.0 - system - ${basedir}/src/test/resources/jars/herold.jar - - - - net.sf.jtidy - jtidy - ${jtidy.version} - + + org.dbdoclet + herold + 6.1.0 + system + ${basedir}/src/test/resources/jars/herold.jar + - + + net.sf.jtidy + jtidy + ${jtidy.version} + - - apache-fop - - - src/main/resources - true - - + - + + apache-fop + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.7 - 1.7 - - + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.7 + 1.7 + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + **/*IntegrationTest.java **/*LiveTest.java - - - + + + - + - + @@ -170,7 +171,7 @@ **/*IntegrationTest.java - **/*LiveTest.java + **/*LiveTest.java @@ -185,25 +186,25 @@ - - - 1.1 - 4.3 - 8.0.2 - r938 - - 1.7.21 - 1.1.7 - - 1.3 - 4.12 - 1.10.19 + + 1.1 + 4.3 + 8.0.2 + r938 + + 1.7.21 + 1.1.7 - - 3.6.0 - 2.19.1 + + 1.3 + 4.12 + 1.10.19 - + + 3.6.0 + 2.19.1 + + \ No newline at end of file diff --git a/apache-poi/README.md b/apache-poi/README.md new file mode 100644 index 0000000000..cef6810c97 --- /dev/null +++ b/apache-poi/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi) diff --git a/aspectj/README.md b/aspectj/README.md new file mode 100644 index 0000000000..71724e76b6 --- /dev/null +++ b/aspectj/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Intro to AspectJ](http://www.baeldung.com/aspectj) +- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging) diff --git a/aspectj/pom.xml b/aspectj/pom.xml index 2fca4031fb..90b527c14f 100644 --- a/aspectj/pom.xml +++ b/aspectj/pom.xml @@ -12,39 +12,69 @@ aspectjrt ${aspectj.version} - + org.aspectj aspectjweaver ${aspectj.version} - + org.slf4j slf4j-api ${org.slf4j.version} - + ch.qos.logback logback-classic ${logback.version} - + ch.qos.logback logback-core ${logback.version} - + junit junit ${junit.version} - + + + org.springframework + spring-context + 4.3.4.RELEASE + + + org.springframework + spring-beans + 4.3.4.RELEASE + + + org.springframework + spring-core + 4.3.4.RELEASE + + + cglib + cglib + 3.2.4 + + + org.springframework + spring-aop + 4.3.4.RELEASE + + + log4j + log4j + 1.2.17 + @@ -65,9 +95,9 @@ ${source.version} ${source.version} - + - + org.codehaus.mojo aspectj-maven-plugin @@ -81,41 +111,22 @@ ignore ${project.build.sourceEncoding} - - + + compile - test-compile + test-compile - - - + + diff --git a/aspectj/src/main/java/com/baeldung/performancemonitor/AopConfiguration.java b/aspectj/src/main/java/com/baeldung/performancemonitor/AopConfiguration.java new file mode 100644 index 0000000000..5e2ef90c0f --- /dev/null +++ b/aspectj/src/main/java/com/baeldung/performancemonitor/AopConfiguration.java @@ -0,0 +1,59 @@ +package com.baeldung.performancemonitor; + +import java.time.LocalDate; +import java.time.Month; + +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.aop.Advisor; +import org.springframework.aop.aspectj.AspectJExpressionPointcut; +import org.springframework.aop.interceptor.PerformanceMonitorInterceptor; +import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +@Configuration +@EnableAspectJAutoProxy +public class AopConfiguration { + + @Pointcut("execution(public String com.baeldung.performancemonitor.PersonService.getFullName(..))") + public void monitor() { } + + @Pointcut("execution(public int com.baeldung.performancemonitor.PersonService.getAge(..))") + public void myMonitor() { } + + @Bean + public PerformanceMonitorInterceptor performanceMonitorInterceptor() { + return new PerformanceMonitorInterceptor(true); + } + + @Bean + public Advisor performanceMonitorAdvisor() { + AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.monitor()"); + return new DefaultPointcutAdvisor(pointcut, performanceMonitorInterceptor()); + } + + @Bean + public Person person(){ + return new Person("John","Smith", LocalDate.of(1980, Month.JANUARY, 12)); + } + + @Bean + public PersonService personService(){ + return new PersonService(); + } + + @Bean + public MyPerformanceMonitorInterceptor myPerformanceMonitorInterceptor() { + return new MyPerformanceMonitorInterceptor(true); + } + + @Bean + public Advisor myPerformanceMonitorAdvisor() { + AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.myMonitor()"); + return new DefaultPointcutAdvisor(pointcut, myPerformanceMonitorInterceptor()); + } + +} diff --git a/aspectj/src/main/java/com/baeldung/performancemonitor/MyPerformanceMonitorInterceptor.java b/aspectj/src/main/java/com/baeldung/performancemonitor/MyPerformanceMonitorInterceptor.java new file mode 100644 index 0000000000..e995e52182 --- /dev/null +++ b/aspectj/src/main/java/com/baeldung/performancemonitor/MyPerformanceMonitorInterceptor.java @@ -0,0 +1,39 @@ +package com.baeldung.performancemonitor; + +import java.util.Date; + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; +import org.springframework.aop.interceptor.AbstractMonitoringInterceptor; + +public class MyPerformanceMonitorInterceptor extends AbstractMonitoringInterceptor { + + public MyPerformanceMonitorInterceptor() { + } + + public MyPerformanceMonitorInterceptor(boolean useDynamicLogger) { + setUseDynamicLogger(useDynamicLogger); + } + + @Override + protected Object invokeUnderTrace(MethodInvocation invocation, Log log) throws Throwable { + + String name = createInvocationTraceName(invocation); + long start = System.currentTimeMillis(); + log.info("Method "+name+" execution started at:"+new Date()); + try { + return invocation.proceed(); + } + finally { + long end = System.currentTimeMillis(); + long time = end - start; + log.info("Method "+name+" execution lasted:"+time+" ms"); + log.info("Method "+name+" execution ended at:"+new Date()); + + if (time > 10){ + log.warn("Method execution longer than 10 ms!"); + } + + } + } +} diff --git a/aspectj/src/main/java/com/baeldung/performancemonitor/PerfomanceApp.java b/aspectj/src/main/java/com/baeldung/performancemonitor/PerfomanceApp.java new file mode 100644 index 0000000000..00268c978e --- /dev/null +++ b/aspectj/src/main/java/com/baeldung/performancemonitor/PerfomanceApp.java @@ -0,0 +1,16 @@ +package com.baeldung.performancemonitor; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class PerfomanceApp { + public static void main(String[] args) { + + ApplicationContext context = new AnnotationConfigApplicationContext(AopConfiguration.class); + Person person = (Person) context.getBean("person"); + PersonService personService = (PersonService) context.getBean("personService"); + + System.out.println("Name is:"+personService.getFullName(person)); + System.out.println("Age is:"+personService.getAge(person)); + } +} diff --git a/aspectj/src/main/java/com/baeldung/performancemonitor/Person.java b/aspectj/src/main/java/com/baeldung/performancemonitor/Person.java new file mode 100644 index 0000000000..f16f28fdef --- /dev/null +++ b/aspectj/src/main/java/com/baeldung/performancemonitor/Person.java @@ -0,0 +1,42 @@ +package com.baeldung.performancemonitor; + +import java.time.LocalDate; + +public class Person { + private String lastName; + private String firstName; + private LocalDate dateOfBirth; + + public Person() { + } + + public Person(String firstName, String lastName, LocalDate dateOfBirth) { + this.firstName = firstName; + this.lastName = lastName; + this.dateOfBirth = dateOfBirth; + } + + public LocalDate getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(LocalDate dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } +} diff --git a/aspectj/src/main/java/com/baeldung/performancemonitor/PersonService.java b/aspectj/src/main/java/com/baeldung/performancemonitor/PersonService.java new file mode 100644 index 0000000000..f5bfdddc12 --- /dev/null +++ b/aspectj/src/main/java/com/baeldung/performancemonitor/PersonService.java @@ -0,0 +1,17 @@ +package com.baeldung.performancemonitor; + +import java.time.LocalDate; +import java.time.Period; + +public class PersonService { + + public String getFullName(Person person){ + return person.getLastName()+" "+person.getFirstName(); + } + + public int getAge(Person person){ + Period p = Period.between(person.getDateOfBirth(), LocalDate.now()); + return p.getYears(); + } + +} diff --git a/aspectj/src/main/resources/log4j.properties b/aspectj/src/main/resources/log4j.properties new file mode 100644 index 0000000000..9e2afcd5b0 --- /dev/null +++ b/aspectj/src/main/resources/log4j.properties @@ -0,0 +1,10 @@ +log4j.rootLogger=TRACE, stdout + +# Redirect log messages to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n + +log4j.logger.org.springframework.aop.interceptor.PerformanceMonitorInterceptor=TRACE, stdout +log4j.logger.com.baeldung.performancemonitor.MyPerformanceMonitorInterceptor=INFO, stdout \ No newline at end of file diff --git a/assertj/pom.xml b/assertj/pom.xml index 0b3bcbacdb..032f33c89d 100644 --- a/assertj/pom.xml +++ b/assertj/pom.xml @@ -54,8 +54,8 @@ 3.1.0 4.12 3.6.1 - + 3.6.0 - + \ No newline at end of file diff --git a/autovalue/pom.xml b/autovalue/pom.xml index 57c4662e5c..32616dc8bc 100644 --- a/autovalue/pom.xml +++ b/autovalue/pom.xml @@ -41,5 +41,5 @@ 4.12 3.6.0 - + diff --git a/aws/.gitignore b/aws/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/aws/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/aws-lambda/pom.xml b/aws/pom.xml similarity index 94% rename from aws-lambda/pom.xml rename to aws/pom.xml index c02d9d59dd..f3ae672a2f 100644 --- a/aws-lambda/pom.xml +++ b/aws/pom.xml @@ -2,10 +2,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - aws-lambda + aws 0.1.0-SNAPSHOT jar - aws-lambda + aws diff --git a/aws-lambda/src/main/java/com/baeldung/LambdaMethodHandler.java b/aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java similarity index 89% rename from aws-lambda/src/main/java/com/baeldung/LambdaMethodHandler.java rename to aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java index 6cce694912..dc21476290 100644 --- a/aws-lambda/src/main/java/com/baeldung/LambdaMethodHandler.java +++ b/aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.lambda; import com.amazonaws.services.lambda.runtime.Context; diff --git a/aws-lambda/src/main/java/com/baeldung/LambdaRequestHandler.java b/aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java similarity index 92% rename from aws-lambda/src/main/java/com/baeldung/LambdaRequestHandler.java rename to aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java index 37f114db25..85385555d2 100644 --- a/aws-lambda/src/main/java/com/baeldung/LambdaRequestHandler.java +++ b/aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.lambda; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; diff --git a/aws-lambda/src/main/java/com/baeldung/LambdaRequestStreamHandler.java b/aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java similarity index 87% rename from aws-lambda/src/main/java/com/baeldung/LambdaRequestStreamHandler.java rename to aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java index aba65628ad..6e8a33c42d 100644 --- a/aws-lambda/src/main/java/com/baeldung/LambdaRequestStreamHandler.java +++ b/aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java @@ -1,7 +1,6 @@ -package com.baeldung; +package com.baeldung.lambda; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.RequestStreamHandler; import org.apache.commons.io.IOUtils; diff --git a/cdi/pom.xml b/cdi/pom.xml index 231390ea5c..e5aaeb2c7b 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -45,7 +45,7 @@ - + @@ -61,7 +61,7 @@ - + integration @@ -101,7 +101,7 @@ 1.8.9 2.4.1.Final 4.12 - 2.19.1 + 2.19.1 \ No newline at end of file diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml index bf9325c935..decba19c53 100644 --- a/core-java-9/pom.xml +++ b/core-java-9/pom.xml @@ -1,91 +1,88 @@ - - 4.0.0 - com.baeldung - core-java9 - 0.2-SNAPSHOT + + 4.0.0 + com.baeldung + core-java9 + 0.2-SNAPSHOT - core-java9 + core-java9 - - - apache.snapshots - http://repository.apache.org/snapshots/ - - + + + apache.snapshots + http://repository.apache.org/snapshots/ + + - + - - org.slf4j - slf4j-api - ${org.slf4j.version} - + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + junit + junit + ${junit.version} + test + - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.mockito + mockito-core + ${mockito.version} + test + - - junit - junit - ${junit.version} - test - + - - org.mockito - mockito-core - ${mockito.version} - test - + + core-java-9 - + - - core-java-9 + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.9 + 1.9 + true + + - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.9 - 1.9 - true - - + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - + - + + + 1.7.21 - + + 3.6-jigsaw-SNAPSHOT + 2.19.1 - - - 1.7.21 - - - 3.6-jigsaw-SNAPSHOT - 2.19.1 - - - 1.3 - 4.12 - 1.10.19 - + + 1.3 + 4.12 + 1.10.19 + diff --git a/core-java/README.md b/core-java/README.md index 3abe1ba808..16cac81526 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -46,3 +46,10 @@ - [Grep in Java](http://www.baeldung.com/grep-in-java) - [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections) - [Simulated Annealing for Travelling Salesman Problem](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman) +- [Slope One Algorithm: Collaborative Filtering Recommendation Systems](http://www.baeldung.com/java-collaborative-filtering-recommendations) +- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library) +- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java) +- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding) +- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size) +- [The Basics of Java Generics](http://www.baeldung.com/java-generics) +- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman) diff --git a/core-java/src/main/java/com/baeldung/scripting/Nashorn.java b/core-java/src/main/java/com/baeldung/scripting/Nashorn.java deleted file mode 100644 index ba9b778de5..0000000000 --- a/core-java/src/main/java/com/baeldung/scripting/Nashorn.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.scripting; - -import javax.script.Bindings; -import javax.script.Invocable; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; - -public class Nashorn { - public static void main(String[] args) throws ScriptException, NoSuchMethodException { - ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); - - Object result = engine.eval( - "var greeting='hello world';" + - "print(greeting);" + - "greeting"); - - System.out.println(result); - - Bindings bindings = engine.createBindings(); - bindings.put("count", 3); - bindings.put("name", "baeldung"); - - String script = "var greeting='Hello ';" + - "for(var i=count;i>0;i--) { " + - "greeting+=name + ' '" + - "}" + - "greeting"; - - Object bindingsResult = engine.eval(script, bindings); - System.out.println(bindingsResult); - - engine.eval("function composeGreeting(name) {" + - "return 'Hello ' + name" + - "}"); - Invocable invocable = (Invocable) engine; - - Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung"); - System.out.println(funcResult); - - Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" + - "var map = new HashMap();" + - "map.put('hello', 'world');" + - "map"); - - System.out.println(map); - } -} diff --git a/core-java/src/main/resources/js/bind.js b/core-java/src/main/resources/js/bind.js new file mode 100644 index 0000000000..652e646d0d --- /dev/null +++ b/core-java/src/main/resources/js/bind.js @@ -0,0 +1,15 @@ +var first = { + name: "Whiskey", + age: 5 +}; + +var second = { + volume: 100 +}; + +Object.bindProperties(first, second); + +print(first.volume); + +second.volume = 1000; +print(first.volume); diff --git a/core-java/src/main/resources/js/locations.js b/core-java/src/main/resources/js/locations.js new file mode 100644 index 0000000000..abfc944639 --- /dev/null +++ b/core-java/src/main/resources/js/locations.js @@ -0,0 +1 @@ +print(__FILE__, __LINE__, __DIR__); diff --git a/core-java/src/main/resources/js/math_module.js b/core-java/src/main/resources/js/math_module.js new file mode 100644 index 0000000000..267a100f36 --- /dev/null +++ b/core-java/src/main/resources/js/math_module.js @@ -0,0 +1,19 @@ +var math = { + increment: function (num) { + return ++num; + }, + + failFunc: function () { + try { + throw "BOOM"; + } catch (e if typeof e === 'string') { + print("String thrown: " + e); + } + catch (e) { + print("this shouldn't happen!"); + } + } +}; + + +math; diff --git a/core-java/src/main/resources/js/no_such.js b/core-java/src/main/resources/js/no_such.js new file mode 100644 index 0000000000..43b50c5cad --- /dev/null +++ b/core-java/src/main/resources/js/no_such.js @@ -0,0 +1,11 @@ +var demo = { + __noSuchProperty__: function (propName) { + print("Accessed non-existing property: " + propName); + }, + + __noSuchMethod__: function (methodName) { + print("Invoked non-existing method: " + methodName); + } +}; + +demo; diff --git a/core-java/src/main/resources/js/script.js b/core-java/src/main/resources/js/script.js new file mode 100644 index 0000000000..6f701ed59d --- /dev/null +++ b/core-java/src/main/resources/js/script.js @@ -0,0 +1 @@ +function increment(num) ++num; diff --git a/core-java/src/main/resources/js/trim.js b/core-java/src/main/resources/js/trim.js new file mode 100644 index 0000000000..81be009978 --- /dev/null +++ b/core-java/src/main/resources/js/trim.js @@ -0,0 +1,2 @@ +print(" hello world".trimLeft()); +print("hello world ".trimRight()); diff --git a/core-java/src/main/resources/js/typed_arrays.js b/core-java/src/main/resources/js/typed_arrays.js new file mode 100644 index 0000000000..6899b29373 --- /dev/null +++ b/core-java/src/main/resources/js/typed_arrays.js @@ -0,0 +1,9 @@ +function arrays(arr) { + + var javaIntArray = Java.to(arr, "int[]"); + print(javaIntArray[0]); + print(javaIntArray[1]); + print(javaIntArray[2]); +} + +arrays([100, "1654", true]); diff --git a/core-java/src/test/java/com/baeldung/java/map/README.md b/core-java/src/test/java/com/baeldung/java/map/README.md new file mode 100644 index 0000000000..0bba153763 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/map/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap) diff --git a/core-java/src/test/java/com/baeldung/java/nio2/README.md b/core-java/src/test/java/com/baeldung/java/nio2/README.md index 65584f93b8..569be82d27 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/README.md +++ b/core-java/src/test/java/com/baeldung/java/nio2/README.md @@ -1,3 +1,11 @@ ### Relevant Articles: - [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api) - [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path) +- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel) +- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng) +- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel) +- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor) +- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute) +- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) +- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice) +- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels) diff --git a/core-java/src/test/java/com/baeldung/java8/optional/README.md b/core-java/src/test/java/com/baeldung/java8/optional/README.md new file mode 100644 index 0000000000..129131ae45 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/optional/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional) diff --git a/core-java/src/test/java/com/baeldung/scripting/NashornTest.java b/core-java/src/test/java/com/baeldung/scripting/NashornTest.java new file mode 100644 index 0000000000..f50db3ad7c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/scripting/NashornTest.java @@ -0,0 +1,111 @@ +package com.baeldung.scripting; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import javax.script.*; +import java.io.InputStreamReader; +import java.util.List; +import java.util.Map; + +public class NashornTest { + + private ScriptEngine engine; + + @Before + public void setUp() { + engine = new ScriptEngineManager().getEngineByName("nashorn"); + } + + @Test + public void trim() throws ScriptException { + engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/trim.js"))); + } + + @Test + public void locations() throws ScriptException { + engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/locations.js"))); + } + + @Test + public void bindProperties() throws ScriptException { + engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/bind.js"))); + } + + @Test + public void magicMethods() throws ScriptException { + engine.eval("var demo = load('classpath:js/no_such.js');" + "var tmp = demo.doesNotExist;" + "var none = demo.callNonExistingMethod()"); + } + + @Test + public void typedArrays() throws ScriptException { + engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/typed_arrays.js"))); + } + + @Test + public void basicUsage() throws ScriptException { + Object result = engine.eval("var greeting='hello world';" + "print(greeting);" + "greeting"); + + Assert.assertEquals("hello world", result); + } + + @Test + public void jsonObjectExample() throws ScriptException { + Object obj = engine.eval("Java.asJSONCompatible({ number: 42, greet: 'hello', primes: [2,3,5,7,11,13] })"); + Map map = (Map) obj; + + Assert.assertEquals("hello", map.get("greet")); + Assert.assertTrue(List.class.isAssignableFrom(map + .get("primes") + .getClass())); + } + + @Test + public void tryCatchGuard() throws ScriptException { + engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.failFunc();"); + } + + @Test + public void extensionsExamples() throws ScriptException { + String script = "var list = [1, 2, 3, 4, 5];" + "var result = '';" + "for each (var i in list) {" + "result+=i+'-';" + "};" + "print(result);"; + engine.eval(script); + } + + @Test + public void bindingsExamples() throws ScriptException { + Bindings bindings = engine.createBindings(); + bindings.put("count", 3); + bindings.put("name", "baeldung"); + + String script = "var greeting='Hello ';" + "for(var i=count;i>0;i--) { " + "greeting+=name + ' '" + "}" + "greeting"; + + Object bindingsResult = engine.eval(script, bindings); + Assert.assertEquals("Hello baeldung baeldung baeldung ", bindingsResult); + } + + @Test + public void jvmBoundaryExamples() throws ScriptException, NoSuchMethodException { + engine.eval("function composeGreeting(name) {" + "return 'Hello ' + name" + "}"); + + Invocable invocable = (Invocable) engine; + + Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung"); + Assert.assertEquals("Hello baeldung", funcResult); + + Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" + "var map = new HashMap();" + "map.put('hello', 'world');" + "map"); + + Assert.assertTrue(Map.class.isAssignableFrom(map.getClass())); + } + + @Test + public void loadExamples() throws ScriptException { + Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)"); + + Assert.assertEquals(6.0, loadResult); + + Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);"); + + Assert.assertEquals(6.0, math); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/collections/README.md b/core-java/src/test/java/org/baeldung/java/collections/README.md new file mode 100644 index 0000000000..50748cbf81 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/collections/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java index 1a6ac5f8ce..6d6d4d9c9b 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java @@ -1,38 +1,26 @@ package org.baeldung.java.io; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; -import java.io.StringWriter; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.StandardCopyOption; -import java.util.Scanner; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.common.base.Charsets; import com.google.common.io.ByteSource; import com.google.common.io.ByteStreams; import com.google.common.io.CharStreams; import com.google.common.io.Files; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.StandardCopyOption; +import java.util.Scanner; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; @SuppressWarnings("unused") public class JavaInputStreamToXUnitTest { @@ -163,7 +151,7 @@ public class JavaInputStreamToXUnitTest { // tests - InputStream to File @Test - public final void givenUsingPlainJava_whenConvertingAnFullInputStreamToAFile_thenCorrect() throws IOException { + public final void whenConvertingToFile_thenCorrect() throws IOException { final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); final byte[] buffer = new byte[initialStream.available()]; initialStream.read(buffer); @@ -177,7 +165,7 @@ public class JavaInputStreamToXUnitTest { } @Test - public final void givenUsingPlainJava_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException { + public final void whenConvertingInProgressToFile_thenCorrect() throws IOException { final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); final File targetFile = new File("src/main/resources/targetFile.tmp"); final OutputStream outStream = new FileOutputStream(targetFile); @@ -193,7 +181,7 @@ public class JavaInputStreamToXUnitTest { } @Test - public final void givenUsingPlainJava8_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException { + public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException { final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); final File targetFile = new File("src/main/resources/targetFile.tmp"); @@ -203,7 +191,7 @@ public class JavaInputStreamToXUnitTest { } @Test - public final void givenUsingGuava_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException { + public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException { final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); final byte[] buffer = new byte[initialStream.available()]; initialStream.read(buffer); @@ -215,7 +203,7 @@ public class JavaInputStreamToXUnitTest { } @Test - public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException { + public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException { final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt")); final File targetFile = new File("src/main/resources/targetFile.tmp"); diff --git a/couchbase-sdk/pom.xml b/couchbase-sdk/pom.xml index 6462cfb57a..301fd81c51 100644 --- a/couchbase-sdk/pom.xml +++ b/couchbase-sdk/pom.xml @@ -1,91 +1,91 @@ - 4.0.0 - com.baeldung - couchbase-sdk - 0.1-SNAPSHOT - jar - couchbase-sdk - Couchbase SDK Tutorials + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + couchbase-sdk + 0.1-SNAPSHOT + jar + couchbase-sdk + Couchbase SDK Tutorials - - - - com.couchbase.client - java-client - ${couchbase.client.version} - + + + + com.couchbase.client + java-client + ${couchbase.client.version} + - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-context-support - ${spring-framework.version} - + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-context-support + ${spring-framework.version} + - - - org.slf4j - slf4j-api - ${org.slf4j.version} - compile - - - ch.qos.logback - logback-classic - ${logback.version} - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - + + + org.slf4j + slf4j-api + ${org.slf4j.version} + compile + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + - - - org.springframework - spring-test - ${spring-framework.version} - test - - - junit - junit - ${junit.version} - test - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - test - - + + + org.springframework + spring-test + ${spring-framework.version} + test + + + junit + junit + ${junit.version} + test + - - - - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + test + + + + + + + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} @@ -96,20 +96,20 @@ - - + + - - 1.8 - UTF-8 - 2.3.6 - 4.3.4.RELEASE - 1.1.7 - 1.7.21 - 4.12 - 3.5 - 3.6.0 + + 1.8 + UTF-8 + 2.3.6 + 4.3.4.RELEASE + 1.1.7 + 1.7.21 + 4.12 + 3.5 + 3.6.0 2.19.1 - + diff --git a/deltaspike/pom.xml b/deltaspike/pom.xml index b4a7657e97..141b5b0da6 100644 --- a/deltaspike/pom.xml +++ b/deltaspike/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung deltaspike @@ -19,21 +19,19 @@ - - - UTF-8 + + + + UTF-8 1.7.21 3.7.4 1.7.2 - + 1.0.2.Final - + 8.2.2.Final @@ -50,14 +48,11 @@ - + org.wildfly.bom jboss-javaee-7.0-with-tools @@ -77,43 +72,37 @@ - + - + javax.enterprise cdi-api provided - + org.jboss.spec.javax.annotation jboss-annotations-api_1.2_spec provided - + org.jboss.resteasy jaxrs-api provided - + org.hibernate.javax.persistence hibernate-jpa-2.1-api provided - + org.jboss.spec.javax.ejb jboss-ejb-api_3.2_spec @@ -135,8 +124,7 @@ - + org.jboss.spec.javax.faces jboss-jsf-api_2.2_spec @@ -145,16 +133,14 @@ - + org.hibernate hibernate-jpamodelgen provided - + org.hibernate hibernate-validator-annotation-processor @@ -169,8 +155,7 @@ - + org.jboss.arquillian.junit arquillian-junit-container @@ -225,8 +210,7 @@ - + ${project.artifactId} @@ -265,10 +249,8 @@ - - + + default true @@ -288,10 +270,8 @@ - - + + arq-wildfly-managed diff --git a/dozer/pom.xml b/dozer/pom.xml index 363285f619..56d5e889c3 100644 --- a/dozer/pom.xml +++ b/dozer/pom.xml @@ -1,11 +1,11 @@ 4.0.0 - + com.baeldung dozer 1.0 - + dozer @@ -54,7 +54,7 @@ - + 1.7.21 3.5 @@ -62,5 +62,5 @@ 4.12 3.6.0 - + diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml index 2580a1e869..ba5763a3e7 100755 --- a/ejb/ejb-client/pom.xml +++ b/ejb/ejb-client/pom.xml @@ -1,16 +1,21 @@ - 4.0.0 - ejb-client - ejb-client - - - com.baeldung.ejb - ejb - 1.0-SNAPSHOT - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + + ejb-client + EJB3 Client Maven + EJB3 Client Maven + + + 4.12 + 2.19 + + org.wildfly @@ -45,10 +50,4 @@ - - - 4.12 - 2.19.1 - - \ No newline at end of file diff --git a/ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java b/ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java index 1a8165cee6..fa92873a73 100755 --- a/ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java +++ b/ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java @@ -1,16 +1,18 @@ package com.baeldung.ejb.setup.test; -import static org.junit.Assert.*; -import org.junit.Test; import com.baeldung.ejb.client.EJBClient; import com.baeldung.ejb.tutorial.HelloWorldBean; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; public class EJBSetupTest { @Test - public void testEJBClient() { + public void EJBClientTest() { EJBClient ejbClient = new EJBClient(); HelloWorldBean bean = new HelloWorldBean(); assertEquals(bean.getHelloWorld(), ejbClient.getEJBRemoteMessage()); } + } diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml index 601ad69447..beb182ff8b 100755 --- a/ejb/ejb-remote/pom.xml +++ b/ejb/ejb-remote/pom.xml @@ -1,45 +1,95 @@ - 4.0.0 - - com.baeldung.ejb - ejb - 1.0-SNAPSHOT - - ejb-remote - ejb + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - - - - javax - javaee-api - ${javaee-api.version} - provided - - + + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + - - - - org.wildfly.plugins - wildfly-maven-plugin - ${wildfly-maven-plugin.version} - - 127.0.0.1 - 9990 - testUser - admin1234! - ${build.finalName}.jar - - - - - - - + ejb-remote + ejb + + + + javax + javaee-api + ${javaee-api.version} + provided + + + + + + + + wildfly-standalone + + true + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + + + + wildfly10x + + http://download.jboss.org/wildfly/10.1.0.Final/wildfly-10.1.0.Final.zip + + + + + + 127.0.0.1 + 9990 + testUser:admin1234! + + + + + + + + + + + + wildfly-runtime + + false + + + + + org.wildfly.plugins + wildfly-maven-plugin + 1.1.0.Alpha5 + + 127.0.0.1 + 9990 + testUser + admin1234! + ${build.finalName}.jar + + + + + + + + + 7.0 - 1.1.0.Beta1 + 1.6.1 - \ No newline at end of file + + + + diff --git a/ejb/pom.xml b/ejb/pom.xml index 7676165b8b..bfcc972417 100755 --- a/ejb/pom.xml +++ b/ejb/pom.xml @@ -1,89 +1,82 @@ - 4.0.0 - com.baeldung.ejb - ejb - 1.0-SNAPSHOT - pom - ejb - EJB Tutorial + 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.ejb + ejb + 1.0-SNAPSHOT + pom + ejb + EJB Tutorial - - - jboss-public-repository-group - JBoss Public Maven Repository Group - http://repository.jboss.org/nexus/content/groups/public/ - default - - true - never - - - true - never - - - + + + jboss-public-repository-group + JBoss Public Maven Repository Group + http://repository.jboss.org/nexus/content/groups/public/ + default + + true + never + + + true + never + + + - - - - com.baeldung.ejb - ejb-remote - 1.0-SNAPSHOT - ejb - + + + + com.baeldung.ejb + ejb-remote + 1.0-SNAPSHOT + ejb + - - javax - javaee-api - ${javaee-api.version} - provided - + + javax + javaee-api + 7.0 + provided + - - org.wildfly - wildfly-ejb-client-bom - ${wildfly.version} - pom - import - - - + + org.wildfly + wildfly-ejb-client-bom + 10.1.0.Final + pom + import + + + - - - - - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - + + + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + - - maven-ejb-plugin - ${maven-ejb-plugin.version} - - 3.2 - - - - - + + maven-ejb-plugin + 2.4 + + 3.2 + + + + + - - ejb-remote - ejb-client - - - - 7.0 - 10.1.0.Final - 3.6.0 - 2.5.1 - + + ejb-remote + ejb-client + \ No newline at end of file diff --git a/enterprise-patterns/pom.xml b/enterprise-patterns/pom.xml index 763227e45b..1c895095dc 100644 --- a/enterprise-patterns/pom.xml +++ b/enterprise-patterns/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung.enterprise.patterns @@ -32,7 +31,7 @@ - + 3.6.0 diff --git a/feign/pom.xml b/feign/pom.xml index 721fa76682..160f37ec2c 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.feign diff --git a/gradle/build.gradle b/gradle/build.gradle new file mode 100644 index 0000000000..fc561987f7 --- /dev/null +++ b/gradle/build.gradle @@ -0,0 +1,25 @@ +apply plugin: 'java' +apply plugin: 'maven' + +repositories{ + mavenCentral() +} + +dependencies{ + compile 'org.springframework:spring-context:4.3.5.RELEASE' +} + +task hello { + println "this Baeldung's tutorial is ${awesomeness}" +} + +uploadArchives { + repositories { + mavenDeployer { + repository(url: 'http://yourmavenrepo/repository') { + authentication(userName: 'user', password: 'password'); + } + + } + } +} diff --git a/gradle/gradle.properties b/gradle/gradle.properties new file mode 100644 index 0000000000..41701e5a19 --- /dev/null +++ b/gradle/gradle.properties @@ -0,0 +1,3 @@ +awesomeness=awesome +group=com.baeldung.tutorial +version=1.0.1 diff --git a/gradle/gradle/wrapper/gradle-wrapper.jar b/gradle/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..3391a4cdf6 Binary files /dev/null and b/gradle/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/gradle/wrapper/gradle-wrapper.properties b/gradle/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..b601d97764 --- /dev/null +++ b/gradle/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Dec 31 15:46:08 BRT 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip diff --git a/gradle/gradlew b/gradle/gradlew new file mode 100644 index 0000000000..9d82f78915 --- /dev/null +++ b/gradle/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# 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 +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# 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 + +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" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradle/gradlew.bat b/gradle/gradlew.bat new file mode 100644 index 0000000000..8a0b282aa6 --- /dev/null +++ b/gradle/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@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= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@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 Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/gradle/src/main/java/Main.java b/gradle/src/main/java/Main.java new file mode 100644 index 0000000000..10edd1840b --- /dev/null +++ b/gradle/src/main/java/Main.java @@ -0,0 +1,5 @@ +public class Main{ + public static void main(String[] args){ + System.out.println("Baeldung Rocks"); + } +} diff --git a/guava/pom.xml b/guava/pom.xml index a7b4e79e34..0a50fad2c3 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -92,7 +92,7 @@ - 19.0 + 21.0 3.5 4.1 diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMultiMapTest.java b/guava/src/test/java/org/baeldung/guava/GuavaMultiMapTest.java new file mode 100644 index 0000000000..5e80dd2f87 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaMultiMapTest.java @@ -0,0 +1,63 @@ +package org.baeldung.guava; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimap; +import org.junit.Test; + +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + + +public class GuavaMultiMapTest { + + @Test + public void givenMap_whenAddTwoValuesForSameKey_shouldOverridePreviousKey() { + //given + String key = "a-key"; + Map map = new LinkedHashMap<>(); + + //when + map.put(key, "firstValue"); + map.put(key, "secondValue"); + + //then + assertEquals(1, map.size()); + } + + @Test + public void givenMultiMap_whenAddTwoValuesForSameKey_shouldHaveTwoEntriesInMap() { + //given + String key = "a-key"; + Multimap map = ArrayListMultimap.create(); + + //when + map.put(key, "firstValue"); + map.put(key, "secondValue"); + + //then + assertEquals(2, map.size()); + } + + @Test + public void givenMapOfListValues_whenAddTwoValuesForSameKey_shouldHaveTwoElementsInList() { + //given + String key = "a-key"; + Map> map = new LinkedHashMap<>(); + + //when + List values = map.get(key); + if(values == null){ + values = new LinkedList<>(); + values.add("firstValue"); + values.add("secondValue"); + } + map.put(key, values); + + //then + assertEquals(1, map.size()); + } +} \ No newline at end of file diff --git a/guava/src/test/java/org/baeldung/guava/GuavaStringTest.java b/guava/src/test/java/org/baeldung/guava/GuavaStringTest.java index be230a9b0e..cedbe60d91 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaStringTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaStringTest.java @@ -8,10 +8,9 @@ import static org.junit.Assert.assertTrue; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; +import com.google.common.collect.*; import org.junit.Test; import com.google.common.base.CharMatcher; @@ -19,9 +18,6 @@ import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Splitter; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; public class GuavaStringTest { diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java index 6fad126537..954236a56f 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -28,13 +28,14 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; -@Ignore("Server is not available") public class HttpClientMultipartLiveTest { - private static final String SERVER = "http://echo.200please.com"; + // No longer available + // private static final String SERVER = "http://echo.200please.com"; + + private static final String SERVER = "http://posttestserver.com/post.php"; private static final String TEXTFILENAME = "temp.txt"; private static final String IMAGEFILENAME = "image.jpg"; private static final String ZIPFILENAME = "zipFile.zip"; @@ -46,7 +47,8 @@ public class HttpClientMultipartLiveTest { @Before public final void before() { - client = HttpClientBuilder.create().build(); + client = HttpClientBuilder.create() + .build(); post = new HttpPost(SERVER); } @@ -80,7 +82,9 @@ public class HttpClientMultipartLiveTest { @Test public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { - final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME); + final URL url = Thread.currentThread() + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); @@ -97,11 +101,12 @@ public class HttpClientMultipartLiveTest { post.setEntity(entity); response = client.execute(post); - final int statusCode = response.getStatusLine().getStatusCode(); + final int statusCode = response.getStatusLine() + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(responseString.contains("Content-Type: multipart/form-data;")); + // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); System.out.println(responseString); System.out.println("POST Content Type: " + contentTypeInHeader); @@ -109,7 +114,9 @@ public class HttpClientMultipartLiveTest { @Test public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException { - final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME); + final URL url = Thread.currentThread() + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -119,11 +126,12 @@ public class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); response = client.execute(post); - final int statusCode = response.getStatusLine().getStatusCode(); + final int statusCode = response.getStatusLine() + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(responseString.contains("Content-Type: multipart/form-data;")); + // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); System.out.println(responseString); System.out.println("POST Content Type: " + contentTypeInHeader); @@ -131,8 +139,12 @@ public class HttpClientMultipartLiveTest { @Test public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { - final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + ZIPFILENAME); - final URL url2 = Thread.currentThread().getContextClassLoader().getResource("uploads/" + IMAGEFILENAME); + final URL url = Thread.currentThread() + .getContextClassLoader() + .getResource("uploads/" + ZIPFILENAME); + final URL url2 = Thread.currentThread() + .getContextClassLoader() + .getResource("uploads/" + IMAGEFILENAME); final InputStream inputStream = new FileInputStream(url.getPath()); final File file = new File(url2.getPath()); final String message = "This is a multipart post"; @@ -144,11 +156,12 @@ public class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); response = client.execute(post); - final int statusCode = response.getStatusLine().getStatusCode(); + final int statusCode = response.getStatusLine() + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(responseString.contains("Content-Type: multipart/form-data;")); + // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); System.out.println(responseString); System.out.println("POST Content Type: " + contentTypeInHeader); @@ -166,11 +179,12 @@ public class HttpClientMultipartLiveTest { final HttpEntity entity = builder.build(); post.setEntity(entity); response = client.execute(post); - final int statusCode = response.getStatusLine().getStatusCode(); + final int statusCode = response.getStatusLine() + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - assertTrue(responseString.contains("Content-Type: multipart/form-data;")); + // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); System.out.println(responseString); System.out.println("POST Content Type: " + contentTypeInHeader); @@ -179,7 +193,8 @@ public class HttpClientMultipartLiveTest { // UTIL final String getContent() throws IOException { - rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); + rd = new BufferedReader(new InputStreamReader(response.getEntity() + .getContent())); String body = ""; String content = ""; while ((body = rd.readLine()) != null) { @@ -189,7 +204,9 @@ public class HttpClientMultipartLiveTest { } final String getContentTypeHeader() throws IOException { - return post.getEntity().getContentType().toString(); + return post.getEntity() + .getContentType() + .toString(); } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index 278cdb3556..5dfecb85aa 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,11 +1,24 @@ package org.baeldung.httpclient; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; + import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.*; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder; @@ -15,14 +28,6 @@ import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.junit.Test; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLException; -import java.io.IOException; -import java.security.GeneralSecurityException; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - /** * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build @@ -35,13 +40,15 @@ public class HttpsClientSslLiveTest { // tests - @Test(expected = SSLException.class) + @Test(expected = SSLHandshakeException.class) public final void whenHttpsUrlIsConsumed_thenException() throws IOException { - final CloseableHttpClient httpClient = HttpClientBuilder.create().build(); + final CloseableHttpClient httpClient = HttpClientBuilder.create() + .build(); final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); } @SuppressWarnings("deprecation") @@ -57,7 +64,8 @@ public class HttpsClientSslLiveTest { final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); httpClient.close(); } @@ -65,44 +73,62 @@ public class HttpsClientSslLiveTest { @Test public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; - final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); + final SSLContext sslContext = SSLContexts.custom() + .loadTrustMaterial(null, acceptingTrustStrategy) + .build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - final CloseableHttpClient httpClient = HttpClients.custom().setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLSocketFactory(sslsf).build(); + final CloseableHttpClient httpClient = HttpClients.custom() + .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) + .setSSLSocketFactory(sslsf) + .build(); final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); httpClient.close(); } @Test public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { - final SSLContextBuilder builder = new SSLContextBuilder(); - builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); - final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); - final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); + final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .build(); + final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier(); + + final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); + final CloseableHttpClient httpClient = HttpClients.custom() + .setSSLHostnameVerifier(hostnameVerifier) + .setSSLSocketFactory(sslsf) + .build(); // new final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); + httpClient.close(); + } @Test public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception { - SSLContext sslContext = new SSLContextBuilder() - .loadTrustMaterial(null, (certificate, authType) -> true).build(); + final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true) + .build(); - final CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + final CloseableHttpClient client = HttpClients.custom() + .setSSLContext(sslContext) + .setSSLHostnameVerifier(new NoopHostnameVerifier()) + .build(); final HttpGet httpGet = new HttpGet(HOST_WITH_SSL); httpGet.setHeader("Accept", "application/xml"); final HttpResponse response = client.execute(httpGet); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); } } diff --git a/image-processing/README.md b/image-processing/README.md new file mode 100644 index 0000000000..48604bdb1f --- /dev/null +++ b/image-processing/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Working with Images in Java](http://www.baeldung.com/java-images) diff --git a/jackson/README.md b/jackson/README.md index f48a7dc8ab..67a03589a8 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -24,3 +24,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [XML Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-xml-serialization-and-deserialization) - [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations) - [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance) +- [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat) diff --git a/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java b/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java new file mode 100644 index 0000000000..8026eedc44 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java @@ -0,0 +1,54 @@ +package com.baeldung.jackson.enums; + +import com.baeldung.jackson.serialization.DistanceSerializer; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +/** + * Use @JsonFormat to handle representation of Enum as JSON (available since Jackson 2.1.2) + * Use @JsonSerialize to configure a custom Jackson serializer + */ +// @JsonFormat(shape = JsonFormat.Shape.OBJECT) +@JsonSerialize(using = DistanceSerializer.class) +public enum Distance { + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private final double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + /** + * Use @JsonValue to control marshalling output for an enum + */ + // @JsonValue + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + /** + * Usage example: Distance.MILE.convertFromMeters(1205.5); + */ + public double convertFromMeters(double distanceInMeters) { + return distanceInMeters / meters; + + } + + /** + * Usage example: Distance.MILE.convertToMeters(0.5); + */ + public double convertToMeters(double distanceInMeters) { + return distanceInMeters * meters; + } + +} \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/DistanceSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/DistanceSerializer.java new file mode 100644 index 0000000000..ca013ff921 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/DistanceSerializer.java @@ -0,0 +1,33 @@ +package com.baeldung.jackson.serialization; + +import java.io.IOException; + +import com.baeldung.jackson.enums.Distance; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; + +public class DistanceSerializer extends StdSerializer { + + private static final long serialVersionUID = 1376504304439963619L; + + public DistanceSerializer() { + super(Distance.class); + } + + public DistanceSerializer(Class t) { + super(t); + } + + public void serialize(Distance distance, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException { + generator.writeStartObject(); + generator.writeFieldName("name"); + generator.writeNumber(distance.name()); + generator.writeFieldName("unit"); + generator.writeString(distance.getUnit()); + generator.writeFieldName("meters"); + generator.writeNumber(distance.getMeters()); + generator.writeEndObject(); + } +} diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/DistanceEnumSimple.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/DistanceEnumSimple.java new file mode 100644 index 0000000000..1118fb349a --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/DistanceEnumSimple.java @@ -0,0 +1,26 @@ +package com.baeldung.jackson.dtos.withEnum; + +public enum DistanceEnumSimple { + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private final double meters; + + private DistanceEnumSimple(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + +} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/DistanceEnumWithJsonFormat.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/DistanceEnumWithJsonFormat.java new file mode 100644 index 0000000000..7dc6bb559b --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/DistanceEnumWithJsonFormat.java @@ -0,0 +1,29 @@ +package com.baeldung.jackson.dtos.withEnum; + +import com.fasterxml.jackson.annotation.JsonFormat; + +@JsonFormat(shape = JsonFormat.Shape.OBJECT) +public enum DistanceEnumWithJsonFormat { + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private final double meters; + + private DistanceEnumWithJsonFormat(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + +} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/DistanceEnumWithValue.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/DistanceEnumWithValue.java new file mode 100644 index 0000000000..69c476d8a5 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/DistanceEnumWithValue.java @@ -0,0 +1,29 @@ +package com.baeldung.jackson.dtos.withEnum; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DistanceEnumWithValue { + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private final double meters; + + private DistanceEnumWithValue(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + @JsonValue + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + +} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/MyDtoWithEnumCustom.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/MyDtoWithEnumCustom.java index 676e22686e..bf9b7db395 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/MyDtoWithEnumCustom.java +++ b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/MyDtoWithEnumCustom.java @@ -1,17 +1,19 @@ package com.baeldung.jackson.dtos.withEnum; +import com.baeldung.jackson.enums.Distance; + public class MyDtoWithEnumCustom { private String stringValue; private int intValue; private boolean booleanValue; - private TypeEnumWithCustomSerializer type; + private Distance type; public MyDtoWithEnumCustom() { super(); } - public MyDtoWithEnumCustom(final String stringValue, final int intValue, final boolean booleanValue, final TypeEnumWithCustomSerializer type) { + public MyDtoWithEnumCustom(final String stringValue, final int intValue, final boolean booleanValue, final Distance type) { super(); this.stringValue = stringValue; @@ -46,11 +48,11 @@ public class MyDtoWithEnumCustom { this.booleanValue = booleanValue; } - public TypeEnumWithCustomSerializer getType() { + public Distance getType() { return type; } - public void setType(final TypeEnumWithCustomSerializer type) { + public void setType(final Distance type) { this.type = type; } diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/MyDtoWithEnum.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/MyDtoWithEnumJsonFormat.java similarity index 62% rename from jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/MyDtoWithEnum.java rename to jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/MyDtoWithEnumJsonFormat.java index 258eb6febd..8e2f1b835f 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/MyDtoWithEnum.java +++ b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/MyDtoWithEnumJsonFormat.java @@ -1,23 +1,23 @@ package com.baeldung.jackson.dtos.withEnum; -public class MyDtoWithEnum { +public class MyDtoWithEnumJsonFormat { private String stringValue; private int intValue; private boolean booleanValue; - private TypeEnum type; + private DistanceEnumWithJsonFormat distanceType; - public MyDtoWithEnum() { + public MyDtoWithEnumJsonFormat() { super(); } - public MyDtoWithEnum(final String stringValue, final int intValue, final boolean booleanValue, final TypeEnum type) { + public MyDtoWithEnumJsonFormat(final String stringValue, final int intValue, final boolean booleanValue, final DistanceEnumWithJsonFormat type) { super(); this.stringValue = stringValue; this.intValue = intValue; this.booleanValue = booleanValue; - this.type = type; + this.distanceType = type; } // API @@ -46,12 +46,12 @@ public class MyDtoWithEnum { this.booleanValue = booleanValue; } - public TypeEnum getType() { - return type; + public DistanceEnumWithJsonFormat getDistanceType() { + return distanceType; } - public void setType(final TypeEnum type) { - this.type = type; + public void setDistanceType(final DistanceEnumWithJsonFormat type) { + this.distanceType = type; } } diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnum.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnum.java deleted file mode 100644 index e0c9718330..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnum.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.jackson.dtos.withEnum; - -import com.fasterxml.jackson.annotation.JsonFormat; - -@JsonFormat(shape = JsonFormat.Shape.OBJECT) -public enum TypeEnum { - TYPE1(1, "Type A"), TYPE2(2, "Type 2"); - - private Integer id; - private String name; - - private TypeEnum(final Integer id, final String name) { - this.id = id; - this.name = name; - } - - // API - - public Integer getId() { - return id; - } - - public void setId(final Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - -} diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnumSimple.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnumSimple.java deleted file mode 100644 index 477db67069..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnumSimple.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.jackson.dtos.withEnum; - -public enum TypeEnumSimple { - TYPE1(1, "Type A"), TYPE2(2, "Type 2"); - - private Integer id; - private String name; - - private TypeEnumSimple(final Integer id, final String name) { - this.id = id; - this.name = name; - } - - // API - - public Integer getId() { - return id; - } - - public void setId(final Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - -} diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnumWithCustomSerializer.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnumWithCustomSerializer.java deleted file mode 100644 index e7c2859dd1..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnumWithCustomSerializer.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.jackson.dtos.withEnum; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonSerialize(using = TypeSerializer.class) -public enum TypeEnumWithCustomSerializer { - TYPE1(1, "Type A"), TYPE2(2, "Type 2"); - - private Integer id; - private String name; - - private TypeEnumWithCustomSerializer(final Integer id, final String name) { - this.id = id; - this.name = name; - } - - // API - - public Integer getId() { - return id; - } - - public void setId(final Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - -} diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnumWithValue.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnumWithValue.java deleted file mode 100644 index c5ddf222ff..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeEnumWithValue.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.jackson.dtos.withEnum; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum TypeEnumWithValue { - TYPE1(1, "Type A"), TYPE2(2, "Type 2"); - - private Integer id; - - private String name; - - private TypeEnumWithValue(final Integer id, final String name) { - this.id = id; - this.name = name; - } - - // API - - public Integer getId() { - return id; - } - - public void setId(final Integer id) { - this.id = id; - } - - @JsonValue - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - -} diff --git a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeSerializer.java b/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeSerializer.java deleted file mode 100644 index fc5011137c..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/dtos/withEnum/TypeSerializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.jackson.dtos.withEnum; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class TypeSerializer extends StdSerializer { - - private static final long serialVersionUID = -7650668914169390772L; - - public TypeSerializer() { - this(null); - } - - public TypeSerializer(final Class t) { - super(t); - } - - @Override - public void serialize(final TypeEnumWithCustomSerializer value, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { - generator.writeStartObject(); - generator.writeFieldName("id"); - generator.writeNumber(value.getId()); - generator.writeFieldName("name"); - generator.writeString(value.getName()); - generator.writeEndObject(); - } - -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationTest.java b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationTest.java new file mode 100644 index 0000000000..af61e55bb4 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.jackson.enums; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JacksonEnumSerializationTest { + + @Test + public final void givenEnum_whenSerializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + final String dtoAsString = new ObjectMapper().writeValueAsString(Distance.MILE); + + assertThat(dtoAsString, containsString("1609.34")); + } + +} diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationTest.java index d854d89b5f..9351b929d3 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationTest.java @@ -34,11 +34,10 @@ import com.baeldung.jackson.bidirection.UserWithRef; import com.baeldung.jackson.date.EventWithFormat; import com.baeldung.jackson.date.EventWithSerializer; import com.baeldung.jackson.dtos.MyMixInForIgnoreType; -import com.baeldung.jackson.dtos.withEnum.TypeEnumWithValue; +import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue; import com.baeldung.jackson.exception.UserWithRoot; import com.baeldung.jackson.jsonview.Item; import com.baeldung.jackson.jsonview.Views; -import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.MapperFeature; @@ -101,10 +100,10 @@ public class JacksonAnnotationTest { } @Test - public void whenSerializingUsingJsonValue_thenCorrect() throws JsonParseException, IOException { - final String enumAsString = new ObjectMapper().writeValueAsString(TypeEnumWithValue.TYPE1); + public void whenSerializingUsingJsonValue_thenCorrect() throws IOException { + final String enumAsString = new ObjectMapper().writeValueAsString(DistanceEnumWithValue.MILE); - assertThat(enumAsString, is("\"Type A\"")); + assertThat(enumAsString, is("1609.34")); } @Test @@ -122,7 +121,7 @@ public class JacksonAnnotationTest { // ========================= Deserializing annotations ============================ @Test - public void whenDeserializingUsingJsonCreator_thenCorrect() throws JsonProcessingException, IOException { + public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { final String json = "{\"id\":1,\"theName\":\"My bean\"}"; final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class).readValue(json); @@ -130,7 +129,7 @@ public class JacksonAnnotationTest { } @Test - public void whenDeserializingUsingJsonInject_thenCorrect() throws JsonProcessingException, IOException { + public void whenDeserializingUsingJsonInject_thenCorrect() throws IOException { final String json = "{\"name\":\"My bean\"}"; final InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1); @@ -140,7 +139,7 @@ public class JacksonAnnotationTest { } @Test - public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws JsonProcessingException, IOException { + public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException { final String json = "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\"}"; final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class).readValue(json); @@ -149,7 +148,7 @@ public class JacksonAnnotationTest { } @Test - public void whenDeserializingUsingJsonSetter_thenCorrect() throws JsonProcessingException, IOException { + public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException { final String json = "{\"id\":1,\"name\":\"My bean\"}"; final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(json); @@ -157,7 +156,7 @@ public class JacksonAnnotationTest { } @Test - public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws JsonProcessingException, IOException { + public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOException { final String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014 02:30:00\"}"; final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); @@ -169,7 +168,7 @@ public class JacksonAnnotationTest { // ========================= Inclusion annotations ============================ @Test - public void whenSerializingUsingJsonIgnoreProperties_thenCorrect() throws JsonProcessingException, IOException { + public void whenSerializingUsingJsonIgnoreProperties_thenCorrect() throws JsonProcessingException { final BeanWithIgnore bean = new BeanWithIgnore(1, "My bean"); final String result = new ObjectMapper().writeValueAsString(bean); @@ -178,7 +177,7 @@ public class JacksonAnnotationTest { } @Test - public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException, IOException { + public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException { final BeanWithIgnore bean = new BeanWithIgnore(1, "My bean"); final String result = new ObjectMapper().writeValueAsString(bean); @@ -199,7 +198,7 @@ public class JacksonAnnotationTest { } @Test - public void whenSerializingUsingJsonInclude_thenCorrect() throws JsonProcessingException, IOException { + public void whenSerializingUsingJsonInclude_thenCorrect() throws JsonProcessingException { final MyBean bean = new MyBean(1, null); final String result = new ObjectMapper().writeValueAsString(bean); @@ -208,7 +207,7 @@ public class JacksonAnnotationTest { } @Test - public void whenSerializingUsingJsonAutoDetect_thenCorrect() throws JsonProcessingException, IOException { + public void whenSerializingUsingJsonAutoDetect_thenCorrect() throws JsonProcessingException { final PrivateBean bean = new PrivateBean(1, "My bean"); final String result = new ObjectMapper().writeValueAsString(bean); @@ -219,7 +218,7 @@ public class JacksonAnnotationTest { // ========================= Polymorphic annotations ============================ @Test - public void whenSerializingPolymorphic_thenCorrect() throws JsonProcessingException, IOException { + public void whenSerializingPolymorphic_thenCorrect() throws JsonProcessingException { final Zoo.Dog dog = new Zoo.Dog("lacy"); final Zoo zoo = new Zoo(dog); @@ -230,7 +229,7 @@ public class JacksonAnnotationTest { } @Test - public void whenDeserializingPolymorphic_thenCorrect() throws JsonProcessingException, IOException { + public void whenDeserializingPolymorphic_thenCorrect() throws IOException { final String json = "{\"animal\":{\"name\":\"lacy\",\"type\":\"cat\"}}"; final Zoo zoo = new ObjectMapper().readerFor(Zoo.class).readValue(json); @@ -276,7 +275,7 @@ public class JacksonAnnotationTest { } @Test - public void whenSerializingUsingJsonView_thenCorrect() throws JsonProcessingException { + public void whenSerializingUsingJsonView_thenCorrect() throws JsonProcessingException, JsonProcessingException { final Item item = new Item(2, "book", "John"); final String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(item); @@ -352,7 +351,7 @@ public class JacksonAnnotationTest { } @Test - public void whenDisablingAllAnnotations_thenAllDisabled() throws JsonProcessingException, IOException { + public void whenDisablingAllAnnotations_thenAllDisabled() throws JsonProcessingException { final MyBean bean = new MyBean(1, null); final ObjectMapper mapper = new ObjectMapper(); diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationEnumsUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationEnumsUnitTest.java index 78c6316aa6..0f57d26d8b 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationEnumsUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationEnumsUnitTest.java @@ -6,14 +6,14 @@ import static org.junit.Assert.assertThat; import java.io.IOException; -import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnum; -import com.baeldung.jackson.dtos.withEnum.TypeEnum; -import com.baeldung.jackson.dtos.withEnum.TypeEnumSimple; -import com.baeldung.jackson.dtos.withEnum.TypeEnumWithValue; -import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumCustom; -import com.baeldung.jackson.dtos.withEnum.TypeEnumWithCustomSerializer; import org.junit.Test; +import com.baeldung.jackson.dtos.withEnum.DistanceEnumSimple; +import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithJsonFormat; +import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue; +import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumCustom; +import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumJsonFormat; +import com.baeldung.jackson.enums.Distance; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -24,10 +24,9 @@ public class JacksonSerializationEnumsUnitTest { @Test public final void whenSerializingASimpleEnum_thenCorrect() throws JsonParseException, IOException { final ObjectMapper mapper = new ObjectMapper(); - final String enumAsString = mapper.writeValueAsString(TypeEnumSimple.TYPE1); - System.out.println(enumAsString); + final String enumAsString = mapper.writeValueAsString(DistanceEnumSimple.MILE); - assertThat(enumAsString, containsString("TYPE1")); + assertThat(enumAsString, containsString("MILE")); } // tests - enum with main value @@ -35,10 +34,9 @@ public class JacksonSerializationEnumsUnitTest { @Test public final void whenSerializingAEnumWithValue_thenCorrect() throws JsonParseException, IOException { final ObjectMapper mapper = new ObjectMapper(); - final String enumAsString = mapper.writeValueAsString(TypeEnumWithValue.TYPE1); - System.out.println(enumAsString); + final String enumAsString = mapper.writeValueAsString(DistanceEnumWithValue.MILE); - assertThat(enumAsString, is("\"Type A\"")); + assertThat(enumAsString, is("1609.34")); } // tests - enum @@ -46,28 +44,25 @@ public class JacksonSerializationEnumsUnitTest { @Test public final void whenSerializingAnEnum_thenCorrect() throws JsonParseException, IOException { final ObjectMapper mapper = new ObjectMapper(); - final String enumAsString = mapper.writeValueAsString(TypeEnum.TYPE1); + final String enumAsString = mapper.writeValueAsString(DistanceEnumWithJsonFormat.MILE); - System.out.println(enumAsString); - assertThat(enumAsString, containsString("\"name\":\"Type A\"")); + assertThat(enumAsString, containsString("\"meters\":1609.34")); } @Test public final void whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException { final ObjectMapper mapper = new ObjectMapper(); - final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnum("a", 1, true, TypeEnum.TYPE1)); + final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumJsonFormat("a", 1, true, DistanceEnumWithJsonFormat.MILE)); - System.out.println(enumAsString); - assertThat(enumAsString, containsString("\"name\":\"Type A\"")); + assertThat(enumAsString, containsString("\"meters\":1609.34")); } @Test public final void whenSerializingArrayOfEnums_thenCorrect() throws JsonParseException, IOException { final ObjectMapper mapper = new ObjectMapper(); - final String json = mapper.writeValueAsString(new TypeEnum[] { TypeEnum.TYPE1, TypeEnum.TYPE2 }); + final String json = mapper.writeValueAsString(new DistanceEnumWithJsonFormat[] { DistanceEnumWithJsonFormat.MILE, DistanceEnumWithJsonFormat.KILOMETER }); - System.out.println(json); - assertThat(json, containsString("\"name\":\"Type A\"")); + assertThat(json, containsString("\"meters\":1609.34")); } // tests - enum with custom serializer @@ -75,10 +70,9 @@ public class JacksonSerializationEnumsUnitTest { @Test public final void givenCustomSerializer_whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException { final ObjectMapper mapper = new ObjectMapper(); - final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumCustom("a", 1, true, TypeEnumWithCustomSerializer.TYPE1)); + final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumCustom("a", 1, true, Distance.MILE)); - System.out.println(enumAsString); - assertThat(enumAsString, containsString("\"name\":\"Type A\"")); + assertThat(enumAsString, containsString("\"meters\":1609.34")); } } diff --git a/java-mongodb/.gitignore b/java-mongodb/.gitignore new file mode 100644 index 0000000000..79ba317cb5 --- /dev/null +++ b/java-mongodb/.gitignore @@ -0,0 +1,5 @@ +.classpath +.project +.settings +target +build \ No newline at end of file diff --git a/java-mongodb/pom.xml b/java-mongodb/pom.xml new file mode 100644 index 0000000000..66b4bbdc99 --- /dev/null +++ b/java-mongodb/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.baeldung + java-mongodb + 1.0-SNAPSHOT + + + 1.8 + 1.8 + 4.12 + 3.4.1 + 1.11 + + + + + + junit + junit + ${junit.version} + test + + + + de.flapdoodle.embedmongo + de.flapdoodle.embedmongo + ${flapdoodle.version} + test + + + + + org.mongodb + mongo-java-driver + ${mongo.version} + + + + + \ No newline at end of file diff --git a/java-mongodb/src/main/java/com/baeldung/MongoExample.java b/java-mongodb/src/main/java/com/baeldung/MongoExample.java new file mode 100644 index 0000000000..fbef17a15f --- /dev/null +++ b/java-mongodb/src/main/java/com/baeldung/MongoExample.java @@ -0,0 +1,53 @@ +package com.baeldung; + +import com.mongodb.BasicDBObject; +import com.mongodb.DB; +import com.mongodb.DBCollection; +import com.mongodb.DBCursor; +import com.mongodb.MongoClient; + +public class MongoExample { + public static void main( String[] args ) { + + MongoClient mongoClient = new MongoClient("localhost", 27017); + + DB database = mongoClient.getDB("myMongoDb"); + + // print existing databases + mongoClient.getDatabaseNames().forEach(System.out::println); + + database.createCollection("customers", null); + + // print all collections in customers database + database.getCollectionNames().forEach(System.out::println); + + // create data + DBCollection collection = database.getCollection("customers"); + BasicDBObject document = new BasicDBObject(); + document.put("name", "Shubham"); + document.put("company", "Baeldung"); + collection.insert(document); + + // update data + BasicDBObject query = new BasicDBObject(); + query.put("name", "Shubham"); + BasicDBObject newDocument = new BasicDBObject(); + newDocument.put("name", "John"); + BasicDBObject updateObject = new BasicDBObject(); + updateObject.put("$set", newDocument); + collection.update(query, updateObject); + + // read data + BasicDBObject searchQuery = new BasicDBObject(); + searchQuery.put("name", "John"); + DBCursor cursor = collection.find(searchQuery); + while (cursor.hasNext()) { + System.out.println(cursor.next()); + } + + // delete data + BasicDBObject deleteQuery = new BasicDBObject(); + deleteQuery.put("name", "John"); + collection.remove(deleteQuery); + } +} diff --git a/java-mongodb/src/test/java/com/baeldung/AppTest.java b/java-mongodb/src/test/java/com/baeldung/AppTest.java new file mode 100644 index 0000000000..5dd6bb66a9 --- /dev/null +++ b/java-mongodb/src/test/java/com/baeldung/AppTest.java @@ -0,0 +1,72 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import com.mongodb.BasicDBObject; +import com.mongodb.DB; +import com.mongodb.DBCollection; +import com.mongodb.DBCursor; +import com.mongodb.Mongo; +import de.flapdoodle.embedmongo.MongoDBRuntime; +import de.flapdoodle.embedmongo.MongodExecutable; +import de.flapdoodle.embedmongo.MongodProcess; +import de.flapdoodle.embedmongo.config.MongodConfig; +import de.flapdoodle.embedmongo.distribution.Version; +import de.flapdoodle.embedmongo.runtime.Network; + +public class AppTest { + + private static final String DB_NAME = "myMongoDb"; + private MongodExecutable mongodExe; + private MongodProcess mongod; + private Mongo mongo; + private DB db; + private DBCollection collection; + + @Before + public void setup() throws Exception { + + // Creating Mongodbruntime instance + MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance(); + + // Creating MongodbExecutable + mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345, + Network.localhostIsIPv6())); + + // Starting Mongodb + mongod = mongodExe.start(); + mongo = new Mongo("localhost", 12345); + + // Creating DB + db = mongo.getDB(DB_NAME); + + // Creating collection Object and adding values + collection = db.getCollection("customers"); + } + + @After + public void teardown() throws Exception { + mongod.stop(); + mongodExe.cleanup(); + } + + @Test + public void testAddressPersistance() { + + BasicDBObject contact = new BasicDBObject(); + contact.put("name", "John"); + contact.put("company", "Baeldung"); + + // Inserting document + collection.insert(contact); + DBCursor cursorDoc = collection.find(); + BasicDBObject contact1 = new BasicDBObject(); + while (cursorDoc.hasNext()) { + contact1 = (BasicDBObject) cursorDoc.next(); + System.out.println(contact1); + } + assertEquals(contact1.get("name"), "John"); + } +} \ No newline at end of file diff --git a/javaslang/README.md b/javaslang/README.md new file mode 100644 index 0000000000..334ac02f60 --- /dev/null +++ b/javaslang/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Javaslang](http://www.baeldung.com/javaslang) diff --git a/jaxb/README.md b/jaxb/README.md new file mode 100644 index 0000000000..4b603fca00 --- /dev/null +++ b/jaxb/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Guide to JAXB](http://www.baeldung.com/jaxb) diff --git a/jsoup/README.md b/jsoup/README.md new file mode 100644 index 0000000000..8728cc7c4e --- /dev/null +++ b/jsoup/README.md @@ -0,0 +1,10 @@ +========= + +## jsoup Example Project + +### Relevant Articles: +- [Parsing HTML in Java with Jsoup](http://www.baeldung.com/java-with-jsoup) + +### Build the Project + +mvn clean install diff --git a/jsoup/pom.xml b/jsoup/pom.xml index 989f30422c..25551cb3d6 100644 --- a/jsoup/pom.xml +++ b/jsoup/pom.xml @@ -15,15 +15,16 @@ ${jsoup.version} - commons-io - commons-io - ${commons.io.version} + junit + junit + 4.12 + test 1.8 1.8 - 2.5 - 1.10.1 + + 1.10.2
diff --git a/jsoup/src/main/java/com/baeldung/jsoup/JsoupExample.java b/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserTest.java similarity index 59% rename from jsoup/src/main/java/com/baeldung/jsoup/JsoupExample.java rename to jsoup/src/test/java/com/baeldung/jsoup/JsoupParserTest.java index 10431a621d..ba6d7358bc 100644 --- a/jsoup/src/main/java/com/baeldung/jsoup/JsoupExample.java +++ b/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserTest.java @@ -1,47 +1,52 @@ package com.baeldung.jsoup; -import java.io.File; -import java.io.IOException; -import org.apache.commons.io.FileUtils; import org.jsoup.HttpStatusException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; +import org.junit.Before; +import org.junit.Test; -public class JsoupExample { +import java.io.IOException; - public static void main(String[] args) throws IOException { - scrapeSpringBlog(); +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class JsoupParserTest { + + Document doc; + + @Before + public void setUp() throws IOException { + doc = Jsoup.connect("https://spring.io/blog").get(); } - static void scrapeSpringBlog() throws IOException { - String blogUrl = "https://spring.io/blog"; - Document doc = Jsoup.connect(blogUrl).get(); - + @Test + public void loadDocument404() throws IOException { try { - Document doc404 = Jsoup.connect("https://spring.io/will-not-be-found").get(); + doc = Jsoup.connect("https://spring.io/will-not-be-found").get(); } catch (HttpStatusException ex) { - System.out.println(ex.getMessage()); + assertEquals(404, ex.getStatusCode()); } + } - Document docCustomConn = Jsoup.connect(blogUrl).userAgent("Mozilla").get(); - docCustomConn = Jsoup.connect(blogUrl).timeout(5000).get(); - docCustomConn = Jsoup.connect(blogUrl).cookie("cookiename", "val234").get(); - // docCustomConn = Jsoup.connect(blogUrl).data("datakey", "datavalue").post(); - docCustomConn = Jsoup.connect(blogUrl).header("headersecurity", "xyz123").get(); - - docCustomConn = Jsoup.connect(blogUrl) + @Test + public void loadDocumentCustomized() throws IOException { + doc = Jsoup.connect("https://spring.io/blog") .userAgent("Mozilla") .timeout(5000) .cookie("cookiename", "val234") .cookie("anothercookie", "ilovejsoup") + .referrer("http://google.com") .header("headersecurity", "xyz123") .get(); + } + @Test + public void examplesSelectors() { Elements links = doc.select("a"); - Elements sections = doc.select("section"); Elements logo = doc.select(".spring-logo--container"); Elements pagination = doc.select("#pagination_control"); Elements divsDescendant = doc.select("header div"); @@ -50,6 +55,15 @@ public class JsoupExample { Element pag = doc.getElementById("pagination_control"); Elements desktopOnly = doc.getElementsByClass("desktopOnly"); + Elements sections = doc.select("section"); + Element firstSection = sections.first(); + Elements sectionParagraphs = firstSection.select(".paragraph"); + } + + @Test + public void examplesTraversing() { + Elements sections = doc.select("section"); + Element firstSection = sections.first(); Element lastSection = sections.last(); Element secondSection = sections.get(2); @@ -58,10 +72,11 @@ public class JsoupExample { Elements children = firstSection.children(); Elements siblings = firstSection.siblingElements(); - sections.stream().forEach(el -> System.out.println("section: " + el)); - - Elements sectionParagraphs = firstSection.select(".paragraph"); + sections.forEach(el -> System.out.println("section: " + el)); + } + @Test + public void examplesExtracting() { Element firstArticle = doc.select("article").first(); Element timeElement = firstArticle.select("time").first(); String dateTimeOfFirstArticle = timeElement.attr("datetime"); @@ -69,21 +84,28 @@ public class JsoupExample { String sectionDivText = sectionDiv.text(); String articleHtml = firstArticle.html(); String outerHtml = firstArticle.outerHtml(); + } + @Test + public void examplesModifying() { + Element firstArticle = doc.select("article").first(); + Element timeElement = firstArticle.select("time").first(); + Element sectionDiv = firstArticle.select("section div").first(); + + String dateTimeOfFirstArticle = timeElement.attr("datetime"); timeElement.attr("datetime", "2016-12-16 15:19:54.3"); sectionDiv.text("foo bar"); firstArticle.select("h2").html("
"); Element link = new Element(Tag.valueOf("a"), "") - .text("Checkout this amazing website!") - .attr("href", "http://baeldung.com") - .attr("target", "_blank"); + .text("Checkout this amazing website!") + .attr("href", "http://baeldung.com") + .attr("target", "_blank"); firstArticle.appendChild(link); doc.select("li.navbar-link").remove(); firstArticle.select("img").remove(); - File indexFile = new File("/tmp", "spring_blog_home.html"); - FileUtils.writeStringToFile(indexFile, doc.html(), doc.charset()); + assertTrue(doc.html().contains("http://baeldung.com")); } } diff --git a/log-mdc/README.md b/log-mdc/README.md index e69507ae4d..be0b2670c3 100644 --- a/log-mdc/README.md +++ b/log-mdc/README.md @@ -1,6 +1,7 @@ ### 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) ### References diff --git a/pom.xml b/pom.xml index 19bec5bf81..6a0514da4d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 com.baeldung parent-modules @@ -15,6 +14,8 @@ + aws + algorithms annotations apache-cxf apache-fop @@ -91,6 +92,7 @@ selenium-junit-testng spring-akka + spring-amqp spring-all spring-apache-camel spring-autowire @@ -115,6 +117,7 @@ spring-hibernate3 spring-hibernate4 spring-integration + spring-jersey spring-jms spring-jooq spring-jpa @@ -158,6 +161,7 @@ spring-security-rest spring-security-x509 spring-session + spring-sleuth spring-social-login spring-spel spring-thymeleaf @@ -172,6 +176,7 @@ xml xmlunit2 xstream - + java-mongodb + - + \ No newline at end of file diff --git a/spring-all/pom.xml b/spring-all/pom.xml index e77bf0b284..deb6bd6f6a 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -38,6 +38,11 @@ org.springframework spring-context + + org.springframework.retry + spring-retry + ${springretry.version} + @@ -166,7 +171,6 @@ ehcache ${ehcache.version} - @@ -275,6 +279,7 @@ 4.3.4.RELEASE 4.2.0.RELEASE + 1.1.5.RELEASE 5.2.5.Final diff --git a/spring-all/src/main/java/org/baeldung/springretry/AppConfig.java b/spring-all/src/main/java/org/baeldung/springretry/AppConfig.java new file mode 100644 index 0000000000..63bb2a53f1 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/springretry/AppConfig.java @@ -0,0 +1,34 @@ +package org.baeldung.springretry; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.retry.annotation.EnableRetry; +import org.springframework.retry.backoff.FixedBackOffPolicy; +import org.springframework.retry.policy.SimpleRetryPolicy; +import org.springframework.retry.support.RetryTemplate; + +@Configuration +@ComponentScan(basePackages = "org.baeldung.springretry") +@EnableRetry +//Uncomment this two lines if we need XML configuration +//@EnableAspectJAutoProxy +//@ImportResource("classpath:/retryadvice.xml") +public class AppConfig { + + @Bean + public RetryTemplate retryTemplate() { + RetryTemplate retryTemplate = new RetryTemplate(); + + FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy(); + fixedBackOffPolicy.setBackOffPeriod(2000l); + retryTemplate.setBackOffPolicy(fixedBackOffPolicy); + + SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); + retryPolicy.setMaxAttempts(2); + retryTemplate.setRetryPolicy(retryPolicy); + + retryTemplate.registerListener(new DefaultListenerSupport()); + return retryTemplate; + } +} diff --git a/spring-all/src/main/java/org/baeldung/springretry/DefaultListenerSupport.java b/spring-all/src/main/java/org/baeldung/springretry/DefaultListenerSupport.java new file mode 100644 index 0000000000..bc251b4c2f --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/springretry/DefaultListenerSupport.java @@ -0,0 +1,31 @@ +package org.baeldung.springretry; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.retry.RetryCallback; +import org.springframework.retry.RetryContext; +import org.springframework.retry.listener.RetryListenerSupport; + +public class DefaultListenerSupport extends RetryListenerSupport { + + private static final Logger logger = LoggerFactory.getLogger(DefaultListenerSupport.class); + + @Override + public void close(RetryContext context, RetryCallback callback, Throwable throwable) { + logger.info("onClose"); + super.close(context, callback, throwable); + } + + @Override + public void onError(RetryContext context, RetryCallback callback, Throwable throwable) { + logger.info("onError"); + super.onError(context, callback, throwable); + } + + @Override + public boolean open(RetryContext context, RetryCallback callback) { + logger.info("onOpen"); + return super.open(context, callback); + } + +} diff --git a/spring-all/src/main/java/org/baeldung/springretry/MyService.java b/spring-all/src/main/java/org/baeldung/springretry/MyService.java new file mode 100644 index 0000000000..2b8cc16eb3 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/springretry/MyService.java @@ -0,0 +1,21 @@ +package org.baeldung.springretry; + +import java.sql.SQLException; + +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; + +public interface MyService { + + @Retryable + void retryService(); + + @Retryable(value = { SQLException.class }, maxAttempts = 2, backoff = @Backoff(delay = 5000)) + void retryServiceWithRecovery(String sql) throws SQLException; + + @Recover + void recover(SQLException e, String sql); + + void templateRetryService(); +} diff --git a/spring-all/src/main/java/org/baeldung/springretry/MyServiceImpl.java b/spring-all/src/main/java/org/baeldung/springretry/MyServiceImpl.java new file mode 100644 index 0000000000..1b698f26c9 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/springretry/MyServiceImpl.java @@ -0,0 +1,39 @@ +package org.baeldung.springretry; + +import java.sql.SQLException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +@Service +public class MyServiceImpl implements MyService { + + private static final Logger logger = LoggerFactory.getLogger(MyServiceImpl.class); + + @Override + public void retryService() { + logger.info("throw RuntimeException in method retryService()"); + throw new RuntimeException(); + } + + @Override + public void retryServiceWithRecovery(String sql) throws SQLException { + if (StringUtils.isEmpty(sql)) { + logger.info("throw SQLException in method retryServiceWithRecovery()"); + throw new SQLException(); + } + } + + @Override + public void recover(SQLException e, String sql) { + logger.info("In recover method"); + } + + @Override + public void templateRetryService() { + logger.info("throw RuntimeException in method templateRetryService()"); + throw new RuntimeException(); + } +} diff --git a/spring-all/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerConfig.java b/spring-all/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerConfig.java new file mode 100644 index 0000000000..342a5fe3e6 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerConfig.java @@ -0,0 +1,41 @@ +package org.baeldung.taskscheduler; + +import java.util.concurrent.TimeUnit; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; +import org.springframework.scheduling.support.CronTrigger; +import org.springframework.scheduling.support.PeriodicTrigger; + +@Configuration +@ComponentScan(basePackages = "org.baeldung.taskscheduler", basePackageClasses = { ThreadPoolTaskSchedulerExamples.class }) +public class ThreadPoolTaskSchedulerConfig { + + @Bean + public ThreadPoolTaskScheduler threadPoolTaskScheduler() { + ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); + threadPoolTaskScheduler.setPoolSize(5); + threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler"); + return threadPoolTaskScheduler; + } + + @Bean + public CronTrigger cronTrigger() { + return new CronTrigger("10 * * * * ?"); + } + + @Bean + public PeriodicTrigger periodicTrigger() { + return new PeriodicTrigger(2000, TimeUnit.MICROSECONDS); + } + + @Bean + public PeriodicTrigger periodicFixedDelayTrigger() { + PeriodicTrigger periodicTrigger = new PeriodicTrigger(2000, TimeUnit.MICROSECONDS); + periodicTrigger.setFixedRate(true); + periodicTrigger.setInitialDelay(1000); + return periodicTrigger; + } +} \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java b/spring-all/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java new file mode 100644 index 0000000000..7505b85516 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerExamples.java @@ -0,0 +1,47 @@ +package org.baeldung.taskscheduler; + +import java.util.Date; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; +import org.springframework.scheduling.support.CronTrigger; +import org.springframework.scheduling.support.PeriodicTrigger; +import org.springframework.stereotype.Component; + +@Component +public class ThreadPoolTaskSchedulerExamples { + @Autowired + private ThreadPoolTaskScheduler taskScheduler; + + @Autowired + private CronTrigger cronTrigger; + + @Autowired + private PeriodicTrigger periodicTrigger; + + @PostConstruct + public void scheduleRunnableWithCronTrigger(){ + taskScheduler.schedule(new RunnableTask("Current Date"), new Date()); + taskScheduler.scheduleWithFixedDelay(new RunnableTask("Fixed 1 second Delay"), 1000); + taskScheduler.scheduleWithFixedDelay(new RunnableTask("Current Date Fixed 1 second Delay"),new Date() , 1000); + taskScheduler.scheduleAtFixedRate(new RunnableTask("Fixed Rate of 2 seconds"),new Date(), 2000); + taskScheduler.scheduleAtFixedRate(new RunnableTask("Fixed Rate of 2 seconds"), 2000); + taskScheduler.schedule(new RunnableTask("Cron Trigger"), cronTrigger); + taskScheduler.schedule(new RunnableTask("Periodic Trigger"), periodicTrigger); + } + + class RunnableTask implements Runnable{ + + private String message; + + public RunnableTask(String message){ + this.message = message; + } + @Override + public void run() { + System.out.println("Runnable Task with "+message+" on thread "+Thread.currentThread().getName()); + } + } +} \ No newline at end of file diff --git a/spring-all/src/main/resources/retryadvice.xml b/spring-all/src/main/resources/retryadvice.xml new file mode 100644 index 0000000000..8de7801a58 --- /dev/null +++ b/spring-all/src/main/resources/retryadvice.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Initial sleep interval value, default 300 ms + + + + + The maximum value of the backoff period in milliseconds. + + + + + The value to increment the exp seed with for each retry attempt. + + + + + \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java b/spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java new file mode 100644 index 0000000000..2f3411957e --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java @@ -0,0 +1,40 @@ +package org.baeldung.springretry; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.retry.support.RetryTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import java.sql.SQLException; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class) +public class SpringRetryTest { + + @Autowired + private MyService myService; + + @Autowired + private RetryTemplate retryTemplate; + + @Test(expected = RuntimeException.class) + public void givenRetryService_whenCallWithException_thenRetry() { + myService.retryService(); + } + + @Test + public void givenRetryServiceWithRecovery_whenCallWithException_thenRetryRecover() throws SQLException { + myService.retryServiceWithRecovery(null); + } + + @Test(expected = RuntimeException.class) + public void givenTemplateRetryService_whenCallWithException_thenRetry() { + retryTemplate.execute(arg0 -> { + myService.templateRetryService(); + return null; + }); + } +} diff --git a/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java b/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java new file mode 100644 index 0000000000..cc247cb384 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java @@ -0,0 +1,16 @@ +package org.baeldung.taskscheduler; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { ThreadPoolTaskSchedulerConfig.class }, loader = AnnotationConfigContextLoader.class) +public class ThreadPoolTaskSchedulerTest { + @Test + public void testThreadPoolTaskSchedulerAnnotation() throws InterruptedException { + Thread.sleep(2550); + } +} \ No newline at end of file diff --git a/spring-amqp/pom.xml b/spring-amqp/pom.xml new file mode 100755 index 0000000000..bb26b2d15d --- /dev/null +++ b/spring-amqp/pom.xml @@ -0,0 +1,41 @@ + + 4.0.0 + + com.baeldung + springamqp + 0.1-SNAPSHOT + jar + + springamqp + Introduction to Spring-AMQP + + + UTF-8 + 3.6.0 + + + + + org.springframework.amqp + spring-rabbit + 1.6.6.RELEASE + + + + + springamqp + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + true + + + + + diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/consumer/Consumer.java b/spring-amqp/src/main/java/com/baeldung/springamqp/consumer/Consumer.java new file mode 100644 index 0000000000..42d7e88cbd --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/consumer/Consumer.java @@ -0,0 +1,7 @@ +package com.baeldung.springamqp.consumer; + +public class Consumer { + public void listen(String foo) { + System.out.println(foo); + } +} \ No newline at end of file diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/producer/Producer.java b/spring-amqp/src/main/java/com/baeldung/springamqp/producer/Producer.java new file mode 100644 index 0000000000..b4067ed795 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/producer/Producer.java @@ -0,0 +1,17 @@ +package com.baeldung.springamqp.producer; + +import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class Producer { + + public static void main(String[] args) throws InterruptedException { + AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); + AmqpTemplate template = ctx.getBean(RabbitTemplate.class); + template.convertAndSend("Hello, world!"); + Thread.sleep(1000); + ctx.destroy(); + } +} \ No newline at end of file diff --git a/spring-amqp/src/main/resources/beans.xml b/spring-amqp/src/main/resources/beans.xml new file mode 100644 index 0000000000..f6a966b0f6 --- /dev/null +++ b/spring-amqp/src/main/resources/beans.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-apache-camel/README.md b/spring-apache-camel/README.md index ab7cf5c575..e72e18b198 100644 --- a/spring-apache-camel/README.md +++ b/spring-apache-camel/README.md @@ -9,6 +9,7 @@ This article will demonstrate how to configure and use Apache Camel with Spring
  • Apache Camel
  • Enterprise Integration Patterns
  • Introduction To Apache Camel
  • +
  • Integration Patterns With Apache Camel
  • Framework Versions:

    diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 19203d2b8d..05173ef318 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -6,3 +6,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) - [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) - [Introduction to WebJars](http://www.baeldung.com/maven-webjars) +- [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) diff --git a/spring-boot/src/main/java/org/baeldung/config/WebConfig.java b/spring-boot/src/main/java/org/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..4ef407823e --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/config/WebConfig.java @@ -0,0 +1,17 @@ +package org.baeldung.config; + +import org.baeldung.web.resolver.HeaderVersionArgumentResolver; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import java.util.List; + +@Configuration +public class WebConfig extends WebMvcConfigurerAdapter { + + @Override + public void addArgumentResolvers(final List argumentResolvers) { + argumentResolvers.add(new HeaderVersionArgumentResolver()); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java b/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java index b6f88e7cd5..7d6293056a 100644 --- a/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java +++ b/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java @@ -1,11 +1,17 @@ package org.baeldung.controller; import org.baeldung.domain.GenericEntity; +import org.baeldung.domain.Modes; +import org.baeldung.web.resolver.Version; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; @@ -35,4 +41,21 @@ public class GenericEntityController { public GenericEntity findById(@PathVariable Long id) { return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get(); } + + @GetMapping("/entity/findbydate/{date}") + public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) { + return entityList.stream().findFirst().get(); + } + + @GetMapping("/entity/findbymode/{mode}") + public GenericEntity findByEnum(@PathVariable("mode") Modes mode) { + return entityList.stream().findFirst().get(); + } + + @GetMapping("/entity/findbyversion") + public ResponseEntity findByVersion(@Version String version) { + return version != null + ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) + : new ResponseEntity(HttpStatus.NOT_FOUND); + } } diff --git a/spring-boot/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java b/spring-boot/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java new file mode 100644 index 0000000000..17c6fd06de --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java @@ -0,0 +1,27 @@ +package org.baeldung.converter; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.convert.converter.ConverterFactory; +import org.springframework.stereotype.Component; + +@Component +public class StringToEnumConverterFactory implements ConverterFactory { + + private static class StringToEnumConverter implements Converter { + + private Class enumType; + + public StringToEnumConverter(Class enumType) { + this.enumType = enumType; + } + + public T convert(String source) { + return (T) Enum.valueOf(this.enumType, source.trim()); + } + } + + @Override + public Converter getConverter(final Class targetType) { + return new StringToEnumConverter(targetType); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java b/spring-boot/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java new file mode 100644 index 0000000000..cbb9e6ddb4 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java @@ -0,0 +1,16 @@ +package org.baeldung.converter; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +@Component +public class StringToLocalDateTimeConverter implements Converter { + + @Override + public LocalDateTime convert(final String source) { + return LocalDateTime.parse(source, DateTimeFormatter.ISO_LOCAL_DATE_TIME); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/domain/Modes.java b/spring-boot/src/main/java/org/baeldung/domain/Modes.java new file mode 100644 index 0000000000..473406ef26 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/domain/Modes.java @@ -0,0 +1,6 @@ +package org.baeldung.domain; + +public enum Modes { + + ALPHA, BETA; +} diff --git a/spring-boot/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java b/spring-boot/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java new file mode 100644 index 0000000000..89a77f38d1 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java @@ -0,0 +1,26 @@ +package org.baeldung.web.resolver; + +import org.springframework.core.MethodParameter; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; + +import javax.servlet.http.HttpServletRequest; + +@Component +public class HeaderVersionArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public boolean supportsParameter(final MethodParameter methodParameter) { + return methodParameter.getParameterAnnotation(Version.class) != null; + } + + @Override + public Object resolveArgument(final MethodParameter methodParameter, final ModelAndViewContainer modelAndViewContainer, final NativeWebRequest nativeWebRequest, final WebDataBinderFactory webDataBinderFactory) throws Exception { + HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest(); + + return request.getHeader("Version"); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/web/resolver/Version.java b/spring-boot/src/main/java/org/baeldung/web/resolver/Version.java new file mode 100644 index 0000000000..2a9e6e60b3 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/web/resolver/Version.java @@ -0,0 +1,11 @@ +package org.baeldung.web.resolver; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface Version { +} diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java index 3c5444942c..8cdcdb2216 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java @@ -1,7 +1,10 @@ package org.baeldung; -import org.baeldung.domain.GenericEntity; -import org.baeldung.repository.GenericEntityRepository; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + +import org.baeldung.domain.Modes; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,11 +21,6 @@ import org.springframework.web.context.WebApplicationContext; import java.nio.charset.Charset; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @@ -42,4 +40,34 @@ public class SpringBootApplicationIntegrationTest { mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); } + + @Test + public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception { + MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); + } + + @Test + public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception { + MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); + } + + @Test + public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception { + MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); + } } diff --git a/spring-core/src/test/java/com/baeldung/applicationcontext/README.md b/spring-core/src/test/java/com/baeldung/applicationcontext/README.md new file mode 100644 index 0000000000..211007e0cf --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/applicationcontext/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) +- [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext) diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 7d7c9cd590..726fcf5f25 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung @@ -160,10 +161,10 @@
    - + UTF-8 - + 4.3.4.RELEASE 1.8.6.RELEASE @@ -177,7 +178,7 @@ 1.7.21 1.1.7 3.6.0 - 2.19.1 + 2.19.1 diff --git a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java similarity index 99% rename from spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java rename to spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java index bb4b268ca7..3853a406fb 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java @@ -33,7 +33,7 @@ import com.mongodb.gridfs.GridFSDBFile; @ContextConfiguration("file:src/main/resources/mongoConfig.xml") @RunWith(SpringJUnit4ClassRunner.class) -public class GridFSIntegrationTest { +public class GridFSLiveTest { private final Logger logger = LoggerFactory.getLogger(getClass()); diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java similarity index 99% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryIntegrationTest.java rename to spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java index cf46c6ed6e..df3ebcb2d2 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java @@ -25,7 +25,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) -public class DocumentQueryIntegrationTest { +public class DocumentQueryLiveTest { @Autowired private MongoTemplate mongoTemplate; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java similarity index 99% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryIntegrationTest.java rename to spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java index 1701b9ac5a..76162c6096 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java @@ -28,7 +28,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) -public class MongoTemplateQueryIntegrationTest { +public class MongoTemplateQueryLiveTest { @Autowired private MongoTemplate mongoTemplate; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java similarity index 94% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryIntegrationTest.java rename to spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java index 8572cc858e..afd7259c6c 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java @@ -7,7 +7,7 @@ import org.junit.Before; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; -public class BaseQueryIntegrationTest { +public class BaseQueryLiveTest { @Autowired protected UserRepository userRepository; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryIntegrationTest.java rename to spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java index ca8d46a97a..03fd38c796 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java @@ -17,7 +17,7 @@ import com.mysema.query.types.Predicate; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) -public class DSLQueryIntegrationTest extends BaseQueryIntegrationTest { +public class DSLQueryLiveTest extends BaseQueryLiveTest { @Test public void givenUsersExist_whenFindingUsersByName_thenUserAreFound() { diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryIntegrationTest.java rename to spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java index ed88429792..9464a4eb52 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java @@ -14,7 +14,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) -public class JSONQueryIntegrationTest extends BaseQueryIntegrationTest { +public class JSONQueryLiveTest extends BaseQueryLiveTest { @Test public void givenUsersExist_whenFindingUsersByName_thenUsersAreFound() { diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsIntegrationTest.java rename to spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java index f7c35c8de2..5705c119b8 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java @@ -14,7 +14,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) -public class QueryMethodsIntegrationTest extends BaseQueryIntegrationTest { +public class QueryMethodsLiveTest extends BaseQueryLiveTest { @Test public void givenUsersExist_whenFindingUsersByName_thenUsersAreFound() { diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java similarity index 99% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java rename to spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java index 53cadc09bc..1543b847ba 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java @@ -24,7 +24,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) -public class UserRepositoryIntegrationTest { +public class UserRepositoryLiveTest { @Autowired private UserRepository userRepository; diff --git a/spring-integration/README.md b/spring-integration/README.md new file mode 100644 index 0000000000..e5b0f601ce --- /dev/null +++ b/spring-integration/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Spring Integration](http://www.baeldung.com/spring-integration) diff --git a/spring-jersey/.gitignore b/spring-jersey/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-jersey/.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-jersey/README.md b/spring-jersey/README.md new file mode 100644 index 0000000000..2767ceb9a7 --- /dev/null +++ b/spring-jersey/README.md @@ -0,0 +1,3 @@ +========= + +## REST API with Jersey & Spring Example Project diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml new file mode 100644 index 0000000000..00d67febec --- /dev/null +++ b/spring-jersey/pom.xml @@ -0,0 +1,210 @@ + + + 4.0.0 + + com.baeldung + jersey-api + 0.1-SNAPSHOT + war + + + 2.25 + 1.7.22 + 1.1.8 + 4.12 + 3.0.0 + 2.19.1 + 1.6.1 + 4.12 + 4.4.5 + 4.5.2 + 3.1.0 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + 8082 + + + + + + + + + + + + + org.glassfish.jersey.core + jersey-server + ${jersey.version} + + + org.glassfish.jersey.containers + jersey-container-servlet + ${jersey.version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey.version} + + + + javax.servlet + javax.servlet-api + ${servlet-api-version} + provided + + + + + org.glassfish.jersey.ext + jersey-spring3 + ${jersey.version} + + + commons-logging + commons-logging + + + + + + org.slf4j + jcl-over-slf4j + ${jcl.slf4j.version} + + + + ch.qos.logback + logback-classic + ${logback.version} + + + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + test + + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + test + + + + + + junit + junit + ${junit.version} + test + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + json + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + false + + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + + + \ No newline at end of file diff --git a/spring-jersey/src/main/java/com/baeldung/server/config/ApplicationInitializer.java b/spring-jersey/src/main/java/com/baeldung/server/config/ApplicationInitializer.java new file mode 100644 index 0000000000..d91d4d5f38 --- /dev/null +++ b/spring-jersey/src/main/java/com/baeldung/server/config/ApplicationInitializer.java @@ -0,0 +1,22 @@ +package com.baeldung.server.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; + +@Order(Ordered.HIGHEST_PRECEDENCE) +public class ApplicationInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + servletContext.addListener(new ContextLoaderListener(context)); + servletContext.setInitParameter("contextConfigLocation", "com.baeldung.server"); + } + +} diff --git a/spring-jersey/src/main/java/com/baeldung/server/config/RestConfig.java b/spring-jersey/src/main/java/com/baeldung/server/config/RestConfig.java new file mode 100644 index 0000000000..34d8948f59 --- /dev/null +++ b/spring-jersey/src/main/java/com/baeldung/server/config/RestConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.server.config; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +import com.baeldung.server.exception.AlreadyExistsExceptionHandler; +import com.baeldung.server.exception.NotFoundExceptionHandler; +import com.baeldung.server.rest.EmployeeResource; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +@ApplicationPath("/resources") +public class RestConfig extends Application { + public Set> getClasses() { + return new HashSet>(Arrays.asList(EmployeeResource.class, NotFoundExceptionHandler.class, AlreadyExistsExceptionHandler.class)); + } +} \ No newline at end of file diff --git a/spring-jersey/src/main/java/com/baeldung/server/exception/AlreadyExistsExceptionHandler.java b/spring-jersey/src/main/java/com/baeldung/server/exception/AlreadyExistsExceptionHandler.java new file mode 100644 index 0000000000..4603372807 --- /dev/null +++ b/spring-jersey/src/main/java/com/baeldung/server/exception/AlreadyExistsExceptionHandler.java @@ -0,0 +1,12 @@ +package com.baeldung.server.exception; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Provider +public class AlreadyExistsExceptionHandler implements ExceptionMapper { + public Response toResponse(EmployeeAlreadyExists ex) { + return Response.status(Response.Status.CONFLICT.getStatusCode()).build(); + } +} diff --git a/spring-jersey/src/main/java/com/baeldung/server/exception/EmployeeAlreadyExists.java b/spring-jersey/src/main/java/com/baeldung/server/exception/EmployeeAlreadyExists.java new file mode 100644 index 0000000000..827e4bf1e7 --- /dev/null +++ b/spring-jersey/src/main/java/com/baeldung/server/exception/EmployeeAlreadyExists.java @@ -0,0 +1,5 @@ +package com.baeldung.server.exception; + +public class EmployeeAlreadyExists extends RuntimeException { + +} diff --git a/spring-jersey/src/main/java/com/baeldung/server/exception/EmployeeNotFound.java b/spring-jersey/src/main/java/com/baeldung/server/exception/EmployeeNotFound.java new file mode 100644 index 0000000000..f205b5dfae --- /dev/null +++ b/spring-jersey/src/main/java/com/baeldung/server/exception/EmployeeNotFound.java @@ -0,0 +1,5 @@ +package com.baeldung.server.exception; + +public class EmployeeNotFound extends RuntimeException { + +} diff --git a/spring-jersey/src/main/java/com/baeldung/server/exception/NotFoundExceptionHandler.java b/spring-jersey/src/main/java/com/baeldung/server/exception/NotFoundExceptionHandler.java new file mode 100644 index 0000000000..5de9b53c30 --- /dev/null +++ b/spring-jersey/src/main/java/com/baeldung/server/exception/NotFoundExceptionHandler.java @@ -0,0 +1,12 @@ +package com.baeldung.server.exception; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Provider +public class NotFoundExceptionHandler implements ExceptionMapper { + public Response toResponse(EmployeeNotFound ex) { + return Response.status(Response.Status.NOT_FOUND).build(); + } +} diff --git a/spring-jersey/src/main/java/com/baeldung/server/model/Employee.java b/spring-jersey/src/main/java/com/baeldung/server/model/Employee.java new file mode 100644 index 0000000000..1801134f68 --- /dev/null +++ b/spring-jersey/src/main/java/com/baeldung/server/model/Employee.java @@ -0,0 +1,34 @@ +package com.baeldung.server.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Employee { + private int id; + private String firstName; + + public Employee() { + + } + + public Employee(int id, String firstName) { + this.id = id; + this.firstName = firstName; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } +} diff --git a/spring-jersey/src/main/java/com/baeldung/server/repository/EmployeeRepository.java b/spring-jersey/src/main/java/com/baeldung/server/repository/EmployeeRepository.java new file mode 100644 index 0000000000..15132cd618 --- /dev/null +++ b/spring-jersey/src/main/java/com/baeldung/server/repository/EmployeeRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.server.repository; + +import java.util.List; + +import com.baeldung.server.model.Employee; + +public interface EmployeeRepository { + + public List getAllEmployees(); + + public Employee getEmployee(int id); + + public void updateEmployee(Employee employee, int id); + + public void deleteEmployee(int id); + + public void addEmployee(Employee employee); +} diff --git a/spring-jersey/src/main/java/com/baeldung/server/repository/EmployeeRepositoryImpl.java b/spring-jersey/src/main/java/com/baeldung/server/repository/EmployeeRepositoryImpl.java new file mode 100644 index 0000000000..8e61e1395b --- /dev/null +++ b/spring-jersey/src/main/java/com/baeldung/server/repository/EmployeeRepositoryImpl.java @@ -0,0 +1,65 @@ +package com.baeldung.server.repository; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.stereotype.Component; + +import com.baeldung.server.exception.EmployeeAlreadyExists; +import com.baeldung.server.exception.EmployeeNotFound; +import com.baeldung.server.model.Employee; + +@Component +public class EmployeeRepositoryImpl implements EmployeeRepository { + private List employeeList; + + public EmployeeRepositoryImpl() { + employeeList = new ArrayList(); + employeeList.add(new Employee(1, "Jane")); + employeeList.add(new Employee(2, "Jack")); + employeeList.add(new Employee(3, "George")); + } + + public List getAllEmployees() { + return employeeList; + } + + public Employee getEmployee(int id) { + for (Employee emp : employeeList) { + if (emp.getId() == id) { + return emp; + } + } + throw new EmployeeNotFound(); + } + + public void updateEmployee(Employee employee, int id) { + for (Employee emp : employeeList) { + if (emp.getId() == id) { + emp.setId(employee.getId()); + emp.setFirstName(employee.getFirstName()); + return; + } + } + throw new EmployeeNotFound(); + } + + public void deleteEmployee(int id) { + for (Employee emp : employeeList) { + if (emp.getId() == id) { + employeeList.remove(emp); + return; + } + } + throw new EmployeeNotFound(); + } + + public void addEmployee(Employee employee) { + for (Employee emp : employeeList) { + if (emp.getId() == employee.getId()) { + throw new EmployeeAlreadyExists(); + } + } + employeeList.add(employee); + } +} diff --git a/spring-jersey/src/main/java/com/baeldung/server/rest/EmployeeResource.java b/spring-jersey/src/main/java/com/baeldung/server/rest/EmployeeResource.java new file mode 100644 index 0000000000..2301f3eaf3 --- /dev/null +++ b/spring-jersey/src/main/java/com/baeldung/server/rest/EmployeeResource.java @@ -0,0 +1,64 @@ +package com.baeldung.server.rest; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.baeldung.server.model.Employee; +import com.baeldung.server.repository.EmployeeRepository; + +@Path("/employees") +public class EmployeeResource { + + @Autowired + private EmployeeRepository employeeRepository; + + @GET + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public List getAllEmployees() { + return employeeRepository.getAllEmployees(); + } + + @GET + @Path("/{id}") + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Employee getEmployee(@PathParam("id") int id) { + return employeeRepository.getEmployee(id); + } + + @PUT + @Path("/{id}") + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Response updateEmployee(Employee employee, @PathParam("id") int id) { + employeeRepository.updateEmployee(employee, id); + return Response.status(Response.Status.OK.getStatusCode()).build(); + } + + @DELETE + @Path("/{id}") + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Response deleteEmployee(@PathParam("id") int id) { + employeeRepository.deleteEmployee(id); + return Response.status(Response.Status.OK.getStatusCode()).build(); + } + + @POST + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + public Response addEmployee(Employee employee, @Context UriInfo uriInfo) { + employeeRepository.addEmployee(new Employee(employee.getId(), employee.getFirstName())); + return Response.status(Response.Status.CREATED.getStatusCode()).header("Location", String.format("%s/%s", uriInfo.getAbsolutePath().toString(), employee.getId())).build(); + } +} diff --git a/spring-jersey/src/main/resources/logback.xml b/spring-jersey/src/main/resources/logback.xml new file mode 100644 index 0000000000..788096686a --- /dev/null +++ b/spring-jersey/src/main/resources/logback.xml @@ -0,0 +1,15 @@ + + + + + web - %date [%thread] %-5level %logger{36} - + %message%n + + + + + + + + + \ No newline at end of file diff --git a/spring-jersey/src/test/java/com/baeldung/server/JerseyApiLiveTest.java b/spring-jersey/src/test/java/com/baeldung/server/JerseyApiLiveTest.java new file mode 100644 index 0000000000..835f9144ab --- /dev/null +++ b/spring-jersey/src/test/java/com/baeldung/server/JerseyApiLiveTest.java @@ -0,0 +1,89 @@ +package com.baeldung.server; + +import com.baeldung.server.model.Employee; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.Test; + +import java.io.IOException; + +public class JerseyApiLiveTest { + + private static final String SERVICE_URL = "http://localhost:8082/jersey-api/resources/employees"; + + @Test + public void givenGetAllEmployees_whenCorrectRequest_thenResponseCodeSuccess() throws IOException { + final HttpUriRequest request = new HttpGet(SERVICE_URL); + + final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); + + assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK); + } + + @Test + public void givenGetEmployee_whenEmployeeExists_thenResponseCodeSuccess() throws IOException { + final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1"); + + final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); + + assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK); + } + + @Test + public void givenGetEmployee_whenEmployeeDoesNotExist_thenResponseCodeNotFound() throws IOException { + final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1000"); + + final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); + + assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND); + } + + @Test + public void givenGetEmployee_whenJsonRequested_thenCorrectDataRetrieved() throws IOException { + final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1"); + + request.setHeader("Accept", "application/json"); + final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); + ObjectMapper mapper = new ObjectMapper(); + Employee emp = mapper.readValue(httpResponse.getEntity().getContent(), Employee.class); + + assert(emp.getFirstName().equals("Jane")); + } + + @Test + public void givenAddEmployee_whenJsonRequestSent_thenResponseCodeCreated() throws IOException { + final HttpPost request = new HttpPost(SERVICE_URL); + + Employee emp = new Employee(5, "Johny"); + ObjectMapper mapper = new ObjectMapper(); + String empJson = mapper.writeValueAsString(emp); + StringEntity input = new StringEntity(empJson); + input.setContentType("application/json"); + request.setEntity(input); + final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); + + assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED); + } + + @Test + public void givenAddEmployee_whenRequestForExistingObjectSent_thenResponseCodeConflict() throws IOException { + final HttpPost request = new HttpPost(SERVICE_URL); + + Employee emp = new Employee(1, "Johny"); + ObjectMapper mapper = new ObjectMapper(); + String empJson = mapper.writeValueAsString(emp); + StringEntity input = new StringEntity(empJson); + input.setContentType("application/json"); + request.setEntity(input); + final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); + + assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CONFLICT); + } + +} \ No newline at end of file diff --git a/spring-jpa/README.md b/spring-jpa/README.md index 30b39e1a4e..313865e3f8 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -12,6 +12,7 @@ - [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) - [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) - [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) +- [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java new file mode 100644 index 0000000000..586c2467fe --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java @@ -0,0 +1,42 @@ +package com.baeldung.springmvcforms.controller; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.baeldung.springmvcforms.domain.Customer; +import com.baeldung.springmvcforms.validator.CustomerValidator; + +@Controller +public class CustomerController { + + @Autowired + CustomerValidator validator; + + @RequestMapping(value = "/customer", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("customerHome", "customer", new Customer()); + } + + @PostMapping("/addCustomer") + public String submit(@Valid @ModelAttribute("customer") final Customer customer, final BindingResult result, final ModelMap model) { + validator.validate(customer, result); + if (result.hasErrors()) { + return "customerHome"; + } + model.addAttribute("customerId", customer.getCustomerId()); + model.addAttribute("customerName", customer.getCustomerName()); + model.addAttribute("customerContact", customer.getCustomerContact()); + model.addAttribute("customerEmail", customer.getCustomerEmail()); + return "customerView"; + } + +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Customer.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Customer.java new file mode 100644 index 0000000000..8ecb2aa503 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Customer.java @@ -0,0 +1,45 @@ +package com.baeldung.springmvcforms.domain; + +public class Customer { + private String customerId; + private String customerName; + private String customerContact; + private String customerEmail; + + public Customer() { + super(); + } + + public String getCustomerId() { + return customerId; + } + + public void setCustomerId(String customerId) { + this.customerId = customerId; + } + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } + + public String getCustomerContact() { + return customerContact; + } + + public void setCustomerContact(String customerContact) { + this.customerContact = customerContact; + } + + public String getCustomerEmail() { + return customerEmail; + } + + public void setCustomerEmail(String customerEmail) { + this.customerEmail = customerEmail; + } + +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/validator/CustomerValidator.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/validator/CustomerValidator.java new file mode 100644 index 0000000000..94a7bd0ebd --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/validator/CustomerValidator.java @@ -0,0 +1,28 @@ +package com.baeldung.springmvcforms.validator; + +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.validation.ValidationUtils; +import org.springframework.validation.Validator; + +import com.baeldung.springmvcforms.domain.Customer; + +@Component +public class CustomerValidator implements Validator { + + @Override + public boolean supports(Class clazz) { + return Customer.class.isAssignableFrom(clazz); + } + + @Override + public void validate(Object target, Errors errors) { + + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerId", "error.customerId", "Customer Id is required."); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerName", "error.customerName", "Customer Name is required."); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerContact", "error.customerNumber", "Customer Contact is required."); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerEmail", "error.customerEmail", "Customer Email is required."); + + } + +} diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/customerHome.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/customerHome.jsp new file mode 100644 index 0000000000..df34a47cc0 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/customerHome.jsp @@ -0,0 +1,47 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Add Customer + + + +

    Welcome, Enter The Customer Details

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

    Submitted Customer Information

    + + + + + + + + + + + + + + + + + +
    Customer Id :${customerId}
    Customer Name :${customerName}
    Customer Contact :${customerContact}
    Customer Email :${customerEmail}
    + + \ No newline at end of file diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 3da7b42fa3..0f267c5ec9 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -17,3 +17,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) +- [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 38443f2022..7d0cc24d41 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -323,9 +323,9 @@ - + - + 4.3.4.RELEASE diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/BeanNameHandlerMappingConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/BeanNameHandlerMappingConfig.java deleted file mode 100644 index fce1d50a00..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/BeanNameHandlerMappingConfig.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.spring.web.config; - -import com.baeldung.web.controller.handlermapping.ExampleTwoController; -import com.baeldung.web.controller.handlermapping.WelcomeController; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; -import org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -public class BeanNameHandlerMappingConfig { - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } - - @Bean - public BeanNameUrlHandlerMapping controllerClassNameHandlerMapping() { - BeanNameUrlHandlerMapping beanNameUrlHandlerMapping = new BeanNameUrlHandlerMapping(); - return beanNameUrlHandlerMapping; - } - - @Bean(name="/welcomeBean") - public WelcomeController welcomeBean() { - WelcomeController welcome = new WelcomeController(); - return welcome; - } - - @Bean(name="/ex") - public ExampleTwoController exampleTwo() { - ExampleTwoController exampleTwo = new ExampleTwoController(); - return exampleTwo; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ControllerClassNameHandlerMappingConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ControllerClassNameHandlerMappingConfig.java deleted file mode 100644 index b03b781e5a..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ControllerClassNameHandlerMappingConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.spring.web.config; - -import com.baeldung.web.controller.handlermapping.ExampleTwoController; -import com.baeldung.web.controller.handlermapping.WelcomeController; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -public class ControllerClassNameHandlerMappingConfig { - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } - - @Bean - public ControllerClassNameHandlerMapping controllerClassNameHandlerMapping() { - ControllerClassNameHandlerMapping controllerClassNameHandlerMapping = new ControllerClassNameHandlerMapping(); - return controllerClassNameHandlerMapping; - } - - @Bean - public WelcomeController welcome() { - WelcomeController welcome = new WelcomeController(); - return welcome; - } - - @Bean - public ExampleTwoController exampleTwo() { - ExampleTwoController exampleTwo = new ExampleTwoController(); - return exampleTwo; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/SimpleUrlHandlerMappingConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/SimpleUrlHandlerMappingConfig.java deleted file mode 100644 index aef7750dc0..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/SimpleUrlHandlerMappingConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.spring.web.config; - -import com.baeldung.web.controller.handlermapping.ExampleTwoController; -import com.baeldung.web.controller.handlermapping.WelcomeController; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -import java.util.HashMap; -import java.util.Map; - -@Configuration -public class SimpleUrlHandlerMappingConfig { - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } - - @Bean - public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { - SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); - Map urlMap = new HashMap<>(); - urlMap.put("/simpleUrlWelcome", welcome()); - urlMap.put("/exampleTwo", exampleTwo()); - simpleUrlHandlerMapping.setUrlMap(urlMap); - return simpleUrlHandlerMapping; - } - - @Bean - public WelcomeController welcome() { - WelcomeController welcome = new WelcomeController(); - return welcome; - } - - @Bean - public ExampleTwoController exampleTwo() { - ExampleTwoController exampleTwo = new ExampleTwoController(); - return exampleTwo; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/ExampleTwoController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java similarity index 52% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/ExampleTwoController.java rename to spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java index efdec6408c..c40165f842 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/ExampleTwoController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java @@ -1,22 +1,16 @@ package com.baeldung.web.controller.handlermapping; -import org.springframework.stereotype.Controller; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -@Controller -public class ExampleTwoController extends AbstractController -{ +public class BeanNameHandlerMappingController extends AbstractController { @Override - protected ModelAndView handleRequestInternal(HttpServletRequest request, - HttpServletResponse response) throws Exception { - System.out.println("Inside ExampleTwo Controller"); - - ModelAndView model = new ModelAndView("exampleTwo"); - + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + ModelAndView model = new ModelAndView("bean-name-handler-mapping"); return model; } -} \ No newline at end of file + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java new file mode 100644 index 0000000000..7732830d07 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java @@ -0,0 +1,16 @@ +package com.baeldung.web.controller.handlermapping; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class SimpleUrlMappingController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + ModelAndView model = new ModelAndView("simple-url-handler-mapping"); + return model; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java index 396244f01c..1598583127 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java @@ -8,15 +8,10 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Controller -public class WelcomeController extends AbstractController -{ - @Override - protected ModelAndView handleRequestInternal(HttpServletRequest request, - HttpServletResponse response) throws Exception { - System.out.println("Inside BeanNameMappingExampleOne Controller"); +public class WelcomeController extends AbstractController { - ModelAndView model = new ModelAndView("test"); - - return model; + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + return new ModelAndView("welcome"); } } \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java new file mode 100644 index 0000000000..e3dcb15de8 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.config; + +import com.baeldung.web.controller.handlermapping.WelcomeController; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +public class BeanNameUrlHandlerMappingConfig { + + @Bean + BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() { + return new BeanNameUrlHandlerMapping(); + } + + @Bean("/beanNameUrl") + public WelcomeController welcome() { + return new WelcomeController(); + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java new file mode 100644 index 0000000000..6e9318602f --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java @@ -0,0 +1,35 @@ +package com.baeldung.config; + +import com.baeldung.web.controller.handlermapping.WelcomeController; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +public class ControllerClassNameHandlerMappingConfig { + + @Bean + public ViewResolver viewResolver() { + InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setPrefix("/"); + viewResolver.setSuffix(".jsp"); + return viewResolver; + } + + @Bean + public ControllerClassNameHandlerMapping controllerClassNameHandlerMapping() { + ControllerClassNameHandlerMapping controllerClassNameHandlerMapping = new ControllerClassNameHandlerMapping(); + return controllerClassNameHandlerMapping; + } + + @Bean + public WelcomeController welcome() { + return new WelcomeController(); + } + + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java new file mode 100644 index 0000000000..9190d07d6b --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java @@ -0,0 +1,28 @@ +package com.baeldung.config; + +import com.baeldung.web.controller.handlermapping.BeanNameHandlerMappingController; +import com.baeldung.web.controller.handlermapping.SimpleUrlMappingController; +import com.baeldung.web.controller.handlermapping.WelcomeController; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; +import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; + +import java.util.HashMap; +import java.util.Map; + + +@Configuration +public class HandlerMappingDefaultConfig { + + @Bean("/welcome") + public BeanNameHandlerMappingController beanNameHandlerMapping() { + return new BeanNameHandlerMappingController(); + } + + @Bean + public WelcomeController welcome() { + return new WelcomeController(); + } + +} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java new file mode 100644 index 0000000000..2d80dbfeaf --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java @@ -0,0 +1,44 @@ +package com.baeldung.config; + +import java.util.HashMap; +import java.util.Map; + +import com.baeldung.web.controller.handlermapping.SimpleUrlMappingController; +import com.baeldung.web.controller.handlermapping.BeanNameHandlerMappingController; +import com.baeldung.web.controller.handlermapping.WelcomeController; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; +import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; + + +@Configuration +public class HandlerMappingPrioritiesConfig { + + @Bean + BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() { + BeanNameUrlHandlerMapping beanNameUrlHandlerMapping = new BeanNameUrlHandlerMapping(); + beanNameUrlHandlerMapping.setOrder(1); + return beanNameUrlHandlerMapping; + } + + @Bean + public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { + SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); + simpleUrlHandlerMapping.setOrder(0); + Map urlMap = new HashMap<>(); + urlMap.put("/welcome", simpleUrlMapping()); + simpleUrlHandlerMapping.setUrlMap(urlMap); + return simpleUrlHandlerMapping; + } + + @Bean + public SimpleUrlMappingController simpleUrlMapping() { + return new SimpleUrlMappingController(); + } + + @Bean("/welcome") + public BeanNameHandlerMappingController beanNameHandlerMapping() { + return new BeanNameHandlerMappingController(); + } +} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java new file mode 100644 index 0000000000..c7921c2706 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java @@ -0,0 +1,43 @@ +package com.baeldung.config; + +import java.util.HashMap; +import java.util.Map; + +import com.baeldung.web.controller.handlermapping.WelcomeController; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + + + + + +@Configuration +public class SimpleUrlHandlerMappingConfig { + + @Bean + public ViewResolver viewResolver() { + InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setPrefix("/"); + viewResolver.setSuffix(".jsp"); + return viewResolver; + } + + @Bean + public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { + SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); + Map urlMap = new HashMap<>(); + urlMap.put("/simpleUrlWelcome", welcome()); + simpleUrlHandlerMapping.setUrlMap(urlMap); + return simpleUrlHandlerMapping; + } + + @Bean + public WelcomeController welcome() { + return new WelcomeController(); + } + + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/BeanNameMappingConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java similarity index 78% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/BeanNameMappingConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java index dc6d861db2..f58e5cb0a1 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/BeanNameMappingConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java @@ -1,7 +1,6 @@ -package com.baeldung.web.controller; +package com.baeldung.handlermappings; -import com.baeldung.spring.web.config.BeanNameHandlerMappingConfig; -import com.baeldung.spring.web.config.SimpleUrlHandlerMappingConfig; +import com.baeldung.config.BeanNameUrlHandlerMappingConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -19,9 +18,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = BeanNameHandlerMappingConfig.class) +@ContextConfiguration(classes = BeanNameUrlHandlerMappingConfig.class) public class BeanNameMappingConfigTest { @Autowired @@ -36,6 +36,6 @@ public class BeanNameMappingConfigTest { @Test public void whenBeanNameMapping_thenMappedOK() throws Exception { - mockMvc.perform(get("/welcomeBean")).andExpect(status().isOk()).andExpect(view().name("test")).andDo(print()); + mockMvc.perform(get("/beanNameUrl")).andExpect(status().isOk()).andExpect(view().name("welcome")).andDo(print()); } -} +} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ControllerClassNameHandlerMappingTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java similarity index 83% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/ControllerClassNameHandlerMappingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java index ea6243a1eb..6fdd168d0b 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ControllerClassNameHandlerMappingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java @@ -1,6 +1,10 @@ -package com.baeldung.web.controller; +package com.baeldung.handlermappings; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; -import com.baeldung.spring.web.config.ControllerClassNameHandlerMappingConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -13,9 +17,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import com.baeldung.config.ControllerClassNameHandlerMappingConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @@ -34,6 +36,6 @@ public class ControllerClassNameHandlerMappingTest { @Test public void whenControllerClassNameMapping_thenMappedOK() throws Exception { - mockMvc.perform(get("/welcome")).andExpect(status().isOk()).andExpect(view().name("test")).andDo(print()); + mockMvc.perform(get("/welcome")).andExpect(status().isOk()).andExpect(view().name("welcome")).andDo(print()); } -} +} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java new file mode 100644 index 0000000000..01be65b829 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java @@ -0,0 +1,41 @@ +package com.baeldung.handlermappings; + +import com.baeldung.config.HandlerMappingDefaultConfig; +import com.baeldung.config.HandlerMappingPrioritiesConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = HandlerMappingDefaultConfig.class) +public class HandlerMappingDefaultConfigTest { + + @Autowired + private WebApplicationContext webAppContext; + private MockMvc mockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); + } + + @Test + public void whenDefaultConfig_thenMappedOK() throws Exception { + mockMvc.perform(get("/welcome")).andExpect(status().isOk()).andExpect(view().name("bean-name-handler-mapping")).andDo(print()); + } +} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java new file mode 100644 index 0000000000..d6329ca6c1 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java @@ -0,0 +1,40 @@ +package com.baeldung.handlermappings; + +import com.baeldung.config.HandlerMappingPrioritiesConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = HandlerMappingPrioritiesConfig.class) +public class HandlerMappingPriorityConfigTest { + + @Autowired + private WebApplicationContext webAppContext; + private MockMvc mockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); + } + + @Test + public void whenConfiguringPriorities_thenMappedOK() throws Exception { + mockMvc.perform(get("/welcome")).andExpect(status().isOk()).andExpect(view().name("simple-url-handler-mapping")).andDo(print()); + } +} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleUrlMappingConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java similarity index 89% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleUrlMappingConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java index 0f83244738..636339f152 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleUrlMappingConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java @@ -1,6 +1,6 @@ -package com.baeldung.web.controller; +package com.baeldung.handlermappings; -import com.baeldung.spring.web.config.SimpleUrlHandlerMappingConfig; +import com.baeldung.config.SimpleUrlHandlerMappingConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,6 +35,6 @@ public class SimpleUrlMappingConfigTest { @Test public void whenSimpleUrlMapping_thenMappedOK() throws Exception { - mockMvc.perform(get("/simpleUrlWelcome")).andExpect(status().isOk()).andExpect(view().name("test")).andDo(print()); + mockMvc.perform(get("/simpleUrlWelcome")).andExpect(status().isOk()).andExpect(view().name("welcome")).andDo(print()); } -} +} \ No newline at end of file diff --git a/spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml b/spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml new file mode 100644 index 0000000000..2da079540c --- /dev/null +++ b/spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml b/spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml new file mode 100644 index 0000000000..26eaa97595 --- /dev/null +++ b/spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml b/spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml new file mode 100644 index 0000000000..9d20db25ea --- /dev/null +++ b/spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + /welcome=test + /*/welcome=test + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml b/spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml new file mode 100644 index 0000000000..713c16e246 --- /dev/null +++ b/spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + /simpleUrlWelcome=welcome + /*/simpleUrlWelcome=welcome + + + + + + + + + \ No newline at end of file diff --git a/spring-reactor/pom.xml b/spring-reactor/pom.xml index cdabb2f538..7b6b1318cf 100644 --- a/spring-reactor/pom.xml +++ b/spring-reactor/pom.xml @@ -27,6 +27,10 @@ io.projectreactor reactor-bus + + org.springframework.boot + spring-boot-starter-test + diff --git a/spring-reactor/src/main/java/com/baeldung/Application.java b/spring-reactor/src/main/java/com/baeldung/Application.java index b635a39e97..9030d41d26 100644 --- a/spring-reactor/src/main/java/com/baeldung/Application.java +++ b/spring-reactor/src/main/java/com/baeldung/Application.java @@ -4,13 +4,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import com.baeldung.consumer.NotificationConsumer; -import reactor.Environment; import reactor.bus.EventBus; import static reactor.bus.selector.Selectors.$; @@ -18,6 +17,7 @@ import static reactor.bus.selector.Selectors.$; @Configuration @EnableAutoConfiguration @ComponentScan +@Import(Config.class) public class Application implements CommandLineRunner { @Autowired @@ -26,16 +26,6 @@ public class Application implements CommandLineRunner { @Autowired private NotificationConsumer notificationConsumer; - @Bean - Environment env() { - return Environment.initializeIfEmpty().assignErrorJournal(); - } - - @Bean - EventBus createEventBus(Environment env) { - return EventBus.create(env, Environment.THREAD_POOL); - } - @Override public void run(String... args) throws Exception { eventBus.on($("notificationConsumer"), notificationConsumer); diff --git a/spring-reactor/src/main/java/com/baeldung/Config.java b/spring-reactor/src/main/java/com/baeldung/Config.java new file mode 100644 index 0000000000..28f40dda02 --- /dev/null +++ b/spring-reactor/src/main/java/com/baeldung/Config.java @@ -0,0 +1,22 @@ +package com.baeldung; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import reactor.Environment; +import reactor.bus.EventBus; + +@Configuration +public class Config { + + @Bean + Environment env() { + return Environment.initializeIfEmpty().assignErrorJournal(); + } + + @Bean + EventBus createEventBus(Environment env) { + return EventBus.create(env, Environment.THREAD_POOL); + } + +} diff --git a/spring-reactor/src/test/java/com/baeldung/DataLoaderLiveTest.java b/spring-reactor/src/test/java/com/baeldung/DataLoaderLiveTest.java new file mode 100644 index 0000000000..5833bc277c --- /dev/null +++ b/spring-reactor/src/test/java/com/baeldung/DataLoaderLiveTest.java @@ -0,0 +1,14 @@ +package com.baeldung; + +import org.junit.Test; +import org.springframework.web.client.RestTemplate; + +public class DataLoaderLiveTest { + + @Test + public void exampleTest() { + RestTemplate restTemplate = new RestTemplate(); + restTemplate.getForObject("http://localhost:8080/startNotification/10", String.class); + } + +} diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml new file mode 100644 index 0000000000..cfb4af9d85 --- /dev/null +++ b/spring-remoting/pom.xml @@ -0,0 +1,109 @@ + + + 4.0.0 + com.baeldung + spring-remoting + 1.0-SNAPSHOT + pom + + + 3.6.0 + 3.0.0 + + 3.1.0 + 1.1.7 + 4.2.4.RELEASE + + + + + + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + + + ch.qos.logback + logback-core + ${logback.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + + javax.servlet + javax.servlet-api + ${servlet.version} + provided + + + + + ${project.groupId} + api + ${project.version} + + + + + + + + + + + + maven-compiler-plugin + ${maven-compiler-plugin.version} + + true + true + 1.8 + 1.8 + UTF-8 + true + true + + + + + maven-war-plugin + 3.0.0 + + false + + + + + + + + remoting-http + + + \ No newline at end of file diff --git a/spring-remoting/remoting-http/api/pom.xml b/spring-remoting/remoting-http/api/pom.xml new file mode 100644 index 0000000000..633217f7de --- /dev/null +++ b/spring-remoting/remoting-http/api/pom.xml @@ -0,0 +1,14 @@ + + + + spring-remoting-http + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + api + spring-remoting-http-api + API definition shared between client and server. + \ No newline at end of file diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Address.java b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Address.java new file mode 100644 index 0000000000..f2382fabd9 --- /dev/null +++ b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Address.java @@ -0,0 +1,26 @@ +package com.baeldung.api; + +import java.io.Serializable; + +public class Address implements Serializable{ + + private String address; + private String countryCode; + + public Address(String address, String countryCode) { + this.address = address; + this.countryCode = countryCode; + } + + public String getAddress() { + return address; + } + + public String getCountryCode() { + return countryCode; + } + + @Override public String toString() { + return address + " (" + countryCode + ")"; + } +} diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java new file mode 100644 index 0000000000..0f52a7bfbd --- /dev/null +++ b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/Booking.java @@ -0,0 +1,53 @@ +package com.baeldung.api; + +import java.io.Serializable; +import java.util.Date; + +public class Booking implements Serializable { + + private int costInCent; + private int etaInSeconds; + private String bookingCode; + private Date pickUptime; + private Address pickUpAddress; + private Address dropOffAddress; + + public Booking(Address pickUpAddress, Date pickUptime, Address dropOffAddress, int costInCent, int etaInSeconds, String bookingCode) { + this.costInCent = costInCent; + this.etaInSeconds = etaInSeconds; + this.bookingCode = bookingCode; + this.pickUptime = pickUptime; + this.pickUpAddress = pickUpAddress; + this.dropOffAddress = dropOffAddress; + } + + public int getCostInCent() { + return costInCent; + } + + public int getEtaInSeconds() { + return etaInSeconds; + } + + public String getBookingCode() { + return bookingCode; + } + + public Date getPickUptime() { + return pickUptime; + } + + public Address getDropOffAddress() { + return dropOffAddress; + } + + @Override public String toString() { + return String.format("Booking: pick up @ %tr in %s, drop down in %s after %d minutes, %.2f $.", pickUptime, pickUpAddress, dropOffAddress, etaInSeconds/60, costInCent/100.0); + } + + public static void main(String[] args) throws InterruptedException { + System.out.println( + new Booking(new Address("a", "b"), new Date(), new Address("c", "d"), 123_00, 600, "abc") + ); + } +} diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/BookingException.java b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/BookingException.java new file mode 100644 index 0000000000..4099db2908 --- /dev/null +++ b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/BookingException.java @@ -0,0 +1,7 @@ +package com.baeldung.api; + +public class BookingException extends Exception { + public BookingException(String message) { + super(message); + } +} diff --git a/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java new file mode 100644 index 0000000000..25b27264e8 --- /dev/null +++ b/spring-remoting/remoting-http/api/src/main/java/com/baeldung/api/CabBookingService.java @@ -0,0 +1,5 @@ +package com.baeldung.api; + +public interface CabBookingService { + Booking bookPickUp(Address pickUpLocation, Address dropOffLocation, int pax) throws BookingException; +} diff --git a/spring-remoting/remoting-http/client/pom.xml b/spring-remoting/remoting-http/client/pom.xml new file mode 100644 index 0000000000..77891c106a --- /dev/null +++ b/spring-remoting/remoting-http/client/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + + com.baeldung + spring-remoting-http + 1.0-SNAPSHOT + + + spring-remoting-http-client + Shows how to invoke a remote service using Spring Remoting. + + + + + org.springframework + spring-web + + + + + ${project.groupId} + api + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/CabBookingClient.java b/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/CabBookingClient.java new file mode 100644 index 0000000000..7cc8e5183c --- /dev/null +++ b/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/CabBookingClient.java @@ -0,0 +1,25 @@ +package com.baeldug.client; + +import com.baeldung.api.*; + +public class CabBookingClient { + + private CabBookingService cabService; + + public CabBookingClient(CabBookingService cabService) { + this.cabService = cabService; + } + + public void run() { + + Address pickUp = new Address("13 Seagate Blvd, Key Largo, FL 33037", "US"); + Address dropDown = new Address("91831 Overseas Hwy, Tavernier, FL 33070", "US"); + try { + System.out.println( cabService.bookPickUp(pickUp, dropDown, 3) ); + } catch (BookingException e) { + e.printStackTrace(); + } + + } + +} diff --git a/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Main.java b/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Main.java new file mode 100644 index 0000000000..0ddb37c508 --- /dev/null +++ b/spring-remoting/remoting-http/client/src/main/java/com/baeldug/client/Main.java @@ -0,0 +1,34 @@ +package com.baeldug.client; + +import com.baeldung.api.CabBookingService; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean; + +@Configuration +public class Main { + + @Bean + public HttpInvokerProxyFactoryBean invoker() { + HttpInvokerProxyFactoryBean invoker = new HttpInvokerProxyFactoryBean(); + invoker.setServiceUrl("http://localhost:9090/spring-remoting-http-server/booking"); + invoker.setServiceInterface(CabBookingService.class); + return invoker; + } + + @Bean + public CabBookingClient client(CabBookingService service){ + return new CabBookingClient(service); + } + + public static void main(String[] args) throws InterruptedException { + AnnotationConfigApplicationContext rootContext = + new AnnotationConfigApplicationContext(); + rootContext.scan(Main.class.getPackage().getName()); + rootContext.refresh(); + CabBookingClient bean = rootContext.getBean(CabBookingClient.class); + bean.run(); + } + +} diff --git a/spring-remoting/remoting-http/pom.xml b/spring-remoting/remoting-http/pom.xml new file mode 100644 index 0000000000..0d08779bd7 --- /dev/null +++ b/spring-remoting/remoting-http/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + com.baeldung + spring-remoting + 1.0-SNAPSHOT + + spring-remoting-http + Parent for all modules related to HTTP Spring Remoting + pom + + + server + client + api + + \ No newline at end of file diff --git a/spring-remoting/remoting-http/server/pom.xml b/spring-remoting/remoting-http/server/pom.xml new file mode 100644 index 0000000000..32a99716a5 --- /dev/null +++ b/spring-remoting/remoting-http/server/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + com.baeldung + spring-remoting-http + 1.0-SNAPSHOT + + war + + spring-remoting-http-server + Shows how to expose a service using Spring Remoting + + + 2.2 + + + + + + + + + org.springframework + spring-webmvc + + + + + javax.servlet + javax.servlet-api + + + + + ${project.groupId} + api + + + + + + + + maven-compiler-plugin + + + + maven-war-plugin + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + ${tomcat7-maven-plugin.version} + + 9090 + + + + + + \ No newline at end of file diff --git a/spring-remoting/remoting-http/server/readme.md b/spring-remoting/remoting-http/server/readme.md new file mode 100644 index 0000000000..4a2abb5d03 --- /dev/null +++ b/spring-remoting/remoting-http/server/readme.md @@ -0,0 +1,12 @@ +Build and launch with the following command. + + mvn clean package tomcat7:run-war + +Exposed service is available at following URL. + + http://localhost:9090/spring-remoting-http-server/account + +## References + + + diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingConfig.java b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingConfig.java new file mode 100644 index 0000000000..146d2ecadb --- /dev/null +++ b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.server; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public class CabBookingConfig { + + + +} diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingInitializer.java b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingInitializer.java new file mode 100644 index 0000000000..53b3fd5faf --- /dev/null +++ b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingInitializer.java @@ -0,0 +1,34 @@ +package com.baeldung.server; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletRegistration; + +public class CabBookingInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) { + AnnotationConfigWebApplicationContext rootContext = + new AnnotationConfigWebApplicationContext(); + rootContext.register(CabBookingConfig.class); + + // Manage the lifecycle of the root application context + container.addListener(new ContextLoaderListener(rootContext)); + + // Create the dispatcher servlet's Spring application context + AnnotationConfigWebApplicationContext dispatcherContext = + new AnnotationConfigWebApplicationContext(); + dispatcherContext.register(DispatcherConfig.class); + + // Register and map the dispatcher servlet + ServletRegistration.Dynamic dispatcher = + container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/*"); + } + +} diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java new file mode 100644 index 0000000000..5f43c7e707 --- /dev/null +++ b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java @@ -0,0 +1,26 @@ +package com.baeldung.server; + +import com.baeldung.api.Address; +import com.baeldung.api.Booking; +import com.baeldung.api.BookingException; +import com.baeldung.api.CabBookingService; + +import java.util.Date; + +import static java.lang.Math.random; +import static java.lang.System.currentTimeMillis; +import static java.util.UUID.randomUUID; + +public class CabBookingServiceImpl implements CabBookingService { + + @Override public Booking bookPickUp(Address pickUpLocation, Address dropOffLocation, int pax) throws BookingException { + if(random()<0.3){ + throw new BookingException("Cab unavailable"); + } + int tripTimeInMinutes = (int) (5 + random() * 15); + int costInCent = 15_00 + tripTimeInMinutes * 5 * pax; + Date pickUpDate = new Date((long) (currentTimeMillis() + (1000 * 60 * random() * 15))); + return new Booking(pickUpLocation, pickUpDate, dropOffLocation, costInCent, tripTimeInMinutes * 60, + randomUUID().toString()); + } +} diff --git a/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/DispatcherConfig.java b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/DispatcherConfig.java new file mode 100644 index 0000000000..8f9391f8ac --- /dev/null +++ b/spring-remoting/remoting-http/server/src/main/java/com/baeldung/server/DispatcherConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.server; + +import com.baeldung.api.CabBookingService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter; + +@Configuration +public class DispatcherConfig { + + @Bean(name = "/booking") HttpInvokerServiceExporter accountService() { + HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter(); + exporter.setService( new CabBookingServiceImpl() ); + exporter.setServiceInterface( CabBookingService.class ); + return exporter; + } + +} diff --git a/spring-remoting/remoting-http/server/src/main/resources/logback.xml b/spring-remoting/remoting-http/server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7a03574f40 --- /dev/null +++ b/spring-remoting/remoting-http/server/src/main/resources/logback.xml @@ -0,0 +1,27 @@ + + + + + + + + ${logPattern} + + + + + C:\Users\danidemi\tmp\baledung\app.log + false + + ${logPattern} + + + + + + + + \ No newline at end of file diff --git a/spring-rest/README.md b/spring-rest/README.md index 3331b9c69f..85f0e13732 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -12,3 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Binary Data Formats in a Spring REST API](http://www.baeldung.com/spring-rest-api-with-binary-data-formats) - [Guide to UriComponentsBuilder in Spring](http://www.baeldung.com/spring-uricomponentsbuilder) - [Introduction to FindBugs](http://www.baeldung.com/intro-to-findbugs) +- [A Custom Media Type for a Spring REST API](http://www.baeldung.com/spring-rest-custom-media-type) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 9bb3c12945..da26d8abe9 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -357,18 +357,4 @@ - - - - org.codehaus.mojo - findbugs-maven-plugin - ${findbugs-maven-plugin.version} - - Max - FindDeadLocalStores,FindNullDeref - - - - - diff --git a/spring-security-core/README.md b/spring-security-core/README.md index c7e0f645c7..0eb506e865 100644 --- a/spring-security-core/README.md +++ b/spring-security-core/README.md @@ -5,3 +5,6 @@ ``` mvn clean install ``` + +### Relevant Articles: +- [Intro to @PreFilter and @PostFilter in Spring Security](http://www.baeldung.com/spring-security-prefilter-postfilter) diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index bea417a800..a1dfa32c6d 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -12,3 +12,4 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Custom Error Message Handling for REST API](http://www.baeldung.com/global-error-handler-in-a-spring-rest-api) - [An Intro to Spring HATEOAS](http://www.baeldung.com/spring-hateoas-tutorial) +- [Spring Security Context Propagation with @Async](http://www.baeldung.com/spring-security-async-principal-propagation) diff --git a/spring-sleuth/pom.xml b/spring-sleuth/pom.xml new file mode 100644 index 0000000000..80415dc00d --- /dev/null +++ b/spring-sleuth/pom.xml @@ -0,0 +1,64 @@ + + + 4.0.0 + + com.baeldung + spring-sleuth + 1.0.0-SNAPSHOT + jar + + + org.springframework.boot + spring-boot-starter-parent + 1.4.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.cloud + spring-cloud-starter-sleuth + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Camden.SR3 + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + \ No newline at end of file diff --git a/spring-sleuth/src/main/java/com/baeldung/spring/session/SchedulingService.java b/spring-sleuth/src/main/java/com/baeldung/spring/session/SchedulingService.java new file mode 100644 index 0000000000..70d4270b41 --- /dev/null +++ b/spring-sleuth/src/main/java/com/baeldung/spring/session/SchedulingService.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.session; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +@Service +public class SchedulingService { + + private Logger logger = LoggerFactory.getLogger(this.getClass()); + private final SleuthService sleuthService; + + @Autowired + public SchedulingService(SleuthService sleuthService) { + this.sleuthService = sleuthService; + } + + @Scheduled(fixedDelay = 30000) + public void scheduledWork() throws InterruptedException { + logger.info("Start some work from the scheduled task"); + sleuthService.asyncMethod(); + logger.info("End work from scheduled task"); + } +} diff --git a/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthController.java b/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthController.java new file mode 100644 index 0000000000..ada1152a4e --- /dev/null +++ b/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthController.java @@ -0,0 +1,68 @@ +package com.baeldung.spring.session; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.concurrent.Executor; + +@RestController +public class SleuthController { + + private Logger logger = LoggerFactory.getLogger(this.getClass()); + private final SleuthService sleuthService; + private final Executor executor; + + @Autowired + public SleuthController(SleuthService sleuthService, Executor executor) { + this.sleuthService = sleuthService; + this.executor = executor; + } + + @GetMapping("/") + public String helloSleuth() { + logger.info("Hello Sleuth"); + return "success"; + } + + @GetMapping("/same-span") + public String helloSleuthSameSpan() throws InterruptedException { + logger.info("Same Span"); + sleuthService.doSomeWorkSameSpan(); + return "success"; + } + + @GetMapping("/new-span") + public String helloSleuthNewSpan() throws InterruptedException { + logger.info("New Span"); + sleuthService.doSomeWorkNewSpan(); + return "success"; + } + + @GetMapping("/new-thread") + public String helloSleuthNewThread() { + logger.info("New Thread"); + Runnable runnable = () -> { + try { + Thread.sleep(1000L); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("I'm inside the new thread - with a new span"); + }; + executor.execute(runnable); + + logger.info("I'm done - with the original span"); + return "success"; + } + + @GetMapping("/async") + public String helloSleuthAsync() throws InterruptedException { + logger.info("Before Async Method Call"); + sleuthService.asyncMethod(); + logger.info("After Async Method Call"); + return "success"; + } +} diff --git a/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthService.java b/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthService.java new file mode 100644 index 0000000000..38480a9b91 --- /dev/null +++ b/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthService.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.session; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.sleuth.Span; +import org.springframework.cloud.sleuth.Tracer; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +@Service +public class SleuthService { + private Logger logger = LoggerFactory.getLogger(this.getClass()); + private final Tracer tracer; + + @Autowired + public SleuthService(Tracer tracer) { + this.tracer = tracer; + } + + public void doSomeWorkSameSpan() throws InterruptedException { + Thread.sleep(1000L); + logger.info("Doing some work"); + } + + public void doSomeWorkNewSpan() throws InterruptedException { + logger.info("I'm in the original span"); + + Span newSpan = tracer.createSpan("newSpan"); + try { + Thread.sleep(1000L); + logger.info("I'm in the new span doing some cool work that needs its own span"); + } finally { + tracer.close(newSpan); + } + + logger.info("I'm in the original span"); + } + + @Async + public void asyncMethod() throws InterruptedException { + logger.info("Start Async Method"); + Thread.sleep(1000L); + logger.info("End Async Method"); + } +} diff --git a/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthWebApp.java b/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthWebApp.java new file mode 100644 index 0000000000..eb57231f53 --- /dev/null +++ b/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthWebApp.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.session; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SleuthWebApp { + public static void main(String[] args) { + SpringApplication.run(SleuthWebApp.class, args); + } +} diff --git a/spring-sleuth/src/main/java/com/baeldung/spring/session/ThreadConfig.java b/spring-sleuth/src/main/java/com/baeldung/spring/session/ThreadConfig.java new file mode 100644 index 0000000000..650be70f19 --- /dev/null +++ b/spring-sleuth/src/main/java/com/baeldung/spring/session/ThreadConfig.java @@ -0,0 +1,55 @@ +package com.baeldung.spring.session; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.sleuth.instrument.async.LazyTraceExecutor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.AsyncConfigurerSupport; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.SchedulingConfigurer; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.scheduling.config.ScheduledTaskRegistrar; + +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +@Configuration +@EnableAsync +@EnableScheduling +public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer{ + + @Autowired + private BeanFactory beanFactory; + + @Bean + public Executor executor() { + ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); + threadPoolTaskExecutor.setCorePoolSize(1); + threadPoolTaskExecutor.setMaxPoolSize(1); + threadPoolTaskExecutor.initialize(); + + return new LazyTraceExecutor(beanFactory, threadPoolTaskExecutor); + } + + @Override + public Executor getAsyncExecutor() { + ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); + threadPoolTaskExecutor.setCorePoolSize(1); + threadPoolTaskExecutor.setMaxPoolSize(1); + threadPoolTaskExecutor.initialize(); + + return new LazyTraceExecutor(beanFactory, threadPoolTaskExecutor); + } + + @Override + public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { + scheduledTaskRegistrar.setScheduler(schedulingExecutor()); + } + + @Bean(destroyMethod = "shutdown") + public Executor schedulingExecutor() { + return Executors.newScheduledThreadPool(1); + } +} diff --git a/spring-sleuth/src/main/resources/application.properties b/spring-sleuth/src/main/resources/application.properties new file mode 100644 index 0000000000..2678b57b0c --- /dev/null +++ b/spring-sleuth/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=Baeldung Sleuth Tutorial \ No newline at end of file diff --git a/spring-thymeleaf/.gitignore b/spring-thymeleaf/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/spring-thymeleaf/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 6b12bb676c..67bdddaf64 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -8,6 +8,7 @@ - [Thymeleaf: Custom Layout Dialect](http://www.baeldung.com/thymeleaf-spring-layouts) - [Spring and Thymeleaf 3: Expressions](http://www.baeldung.com/spring-thymeleaf-3-expressions) - [Spring MVC + Thymeleaf 3.0: New Features](http://www.baeldung.com/spring-thymeleaf-3) +- [How to Work with Dates in Thymeleaef](http://www.baeldung.com/dates-in-thymeleaf) ### Build the Project diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index b387539aa1..457ac6dd56 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -1,256 +1,272 @@ - 4.0.0 - com.baeldung - spring-thymeleaf - 0.1-SNAPSHOT - war - - 1.8 - - 4.3.4.RELEASE - 4.2.0.RELEASE - 3.1.0 - - 1.7.21 - 1.1.7 - - 3.0.2.RELEASE - 2.1.2 - - 1.1.0.Final - 5.3.3.Final - 5.2.5.Final + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-thymeleaf + 0.1-SNAPSHOT + war + + + + + org.springframework + spring-context + ${org.springframework-version} + + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + ${org.springframework-version} + + + + + org.springframework.security + spring-security-web + ${springframework-security.version} + + + org.springframework.security + spring-security-config + ${springframework-security.version} + + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + + + nz.net.ultraq.thymeleaf + thymeleaf-layout-dialect + ${thymeleaf-layout-dialect.version} + + + org.thymeleaf.extras + thymeleaf-extras-java8time + ${org.thymeleaf.extras-version} + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + + javax.servlet + javax.servlet-api + ${javax.servlet-version} + provided + + + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + + + org.springframework + spring-test + ${org.springframework-version} + test + + + + org.springframework.security + spring-security-test + ${springframework-security.version} + test + + + + junit + junit + ${junit.version} + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java-version} + ${java-version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + 8082 + + + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + ${tomcat7-maven-plugin.version} + + + tomcat-run + + exec-war-only + + package + + / + false + webapp.jar + utf-8 + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + 1.8 + + 4.3.5.RELEASE + 4.2.1.RELEASE + 3.1.0 + + + 1.7.21 + 1.1.7 + + + 3.0.3.RELEASE + 3.0.0.RELEASE + 2.1.2 + + + 1.1.0.Final + 5.3.3.Final + 5.2.5.Final 4.12 - - 3.6.0 - 2.6 - 2.19.1 - 1.6.1 - 2.2 - + + + 3.6.0 + 2.6 + 2.19.1 + 1.6.1 + 2.2 + + - - - - org.springframework - spring-context - ${org.springframework-version} - - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - ${org.springframework-version} - - - - org.springframework.security - spring-security-web - ${springframework-security.version} - - - org.springframework.security - spring-security-config - ${springframework-security.version} - - - - org.thymeleaf - thymeleaf - ${org.thymeleaf-version} - - - org.thymeleaf - thymeleaf-spring4 - ${org.thymeleaf-version} - - - - nz.net.ultraq.thymeleaf - thymeleaf-layout-dialect - ${thymeleaf-layout-dialect.version} - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - javax.servlet - javax.servlet-api - ${javax.servlet-version} - provided - - - - javax.validation - validation-api - ${javax.validation-version} - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - - - org.springframework - spring-test - ${org.springframework-version} - test - - - - - org.springframework.security - spring-security-test - ${springframework-security.version} - test - - - - - junit - junit - ${junit.version} - test - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java-version} - ${java-version} - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - **/*LiveTest.java - - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - 8082 - - - - - - org.apache.tomcat.maven - tomcat7-maven-plugin - ${tomcat7-maven-plugin.version} - - - tomcat-run - - exec-war-only - - package - - / - false - webapp.jar - utf-8 - - - - - - - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java index ab048bdd87..10b9f0b7a0 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -13,6 +13,7 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.thymeleaf.TemplateEngine; +import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring4.view.ThymeleafViewResolver; @@ -25,7 +26,6 @@ import com.baeldung.thymeleaf.utils.ArrayUtil; import nz.net.ultraq.thymeleaf.LayoutDialect; import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; - @Configuration @EnableWebMvc @ComponentScan({ "com.baeldung.thymeleaf" }) @@ -35,23 +35,23 @@ import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; */ public class WebMVCConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware { - private ApplicationContext applicationContext; + private ApplicationContext applicationContext; - public void setApplicationContext(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } - @Bean - public ViewResolver htmlViewResolver() { - ThymeleafViewResolver resolver = new ThymeleafViewResolver(); - resolver.setTemplateEngine(templateEngine(htmlTemplateResolver())); - resolver.setContentType("text/html"); - resolver.setCharacterEncoding("UTF-8"); - resolver.setViewNames(ArrayUtil.array("*.html")); - return resolver; - } - - @Bean + @Bean + public ViewResolver htmlViewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine(htmlTemplateResolver())); + resolver.setContentType("text/html"); + resolver.setCharacterEncoding("UTF-8"); + resolver.setViewNames(ArrayUtil.array("*.html")); + return resolver; + } + + @Bean public ViewResolver javascriptViewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver())); @@ -60,8 +60,8 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application resolver.setViewNames(ArrayUtil.array("*.js")); return resolver; } - - @Bean + + @Bean public ViewResolver plainViewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine(plainTemplateResolver())); @@ -71,9 +71,10 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application return resolver; } - private TemplateEngine templateEngine(ITemplateResolver templateResolver) { + private TemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.addDialect(new LayoutDialect(new GroupingStrategy())); + engine.addDialect(new Java8TimeDialect()); engine.setTemplateResolver(templateResolver); return engine; } @@ -86,7 +87,7 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application resolver.setTemplateMode(TemplateMode.HTML); return resolver; } - + private ITemplateResolver javascriptTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); @@ -95,7 +96,7 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application resolver.setTemplateMode(TemplateMode.JAVASCRIPT); return resolver; } - + private ITemplateResolver plainTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); @@ -105,22 +106,22 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application return resolver; } - @Bean - @Description("Spring Message Resolver") - public ResourceBundleMessageSource messageSource() { - ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setBasename("messages"); - return messageSource; - } + @Bean + @Description("Spring Message Resolver") + public ResourceBundleMessageSource messageSource() { + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); - } + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); + } - @Override - @Description("Custom Conversion Service") - public void addFormatters(FormatterRegistry registry) { - registry.addFormatter(new NameFormatter()); - } + @Override + @Description("Custom Conversion Service") + public void addFormatters(FormatterRegistry registry) { + registry.addFormatter(new NameFormatter()); + } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java index 37844a2976..46bff38a3f 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java @@ -37,13 +37,7 @@ public class WebMVCSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest() - .authenticated() - .and() - .httpBasic() - ; + http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/DatesController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/DatesController.java new file mode 100644 index 0000000000..20f5d02fed --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/DatesController.java @@ -0,0 +1,25 @@ +package com.baeldung.thymeleaf.controller; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Date; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class DatesController { + + @RequestMapping(value = "/dates", method = RequestMethod.GET) + public String getInfo(Model model) { + model.addAttribute("standardDate", new Date()); + model.addAttribute("localDateTime", LocalDateTime.now()); + model.addAttribute("localDate", LocalDate.now()); + model.addAttribute("timestamp", Instant.now()); + return "dates.html"; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java index f30b9b2078..61c3e8de8f 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java @@ -17,17 +17,17 @@ import org.springframework.web.bind.annotation.RequestMethod; @Controller public class ExpressionUtilityObjectsController { - @RequestMapping(value = "/objects", method = RequestMethod.GET) - public String getDates(Model model) { - model.addAttribute("date", new Date()); - model.addAttribute("calendar", Calendar.getInstance()); - model.addAttribute("num", Math.random() * 10); - model.addAttribute("string", "new text"); - model.addAttribute("emptyString", ""); - model.addAttribute("nullString", null); - model.addAttribute("array", new int[] { 1, 3, 4, 5 }); - model.addAttribute("set", new HashSet(Arrays.asList(1, 3, 8))); - return "objects.html"; - } + @RequestMapping(value = "/objects", method = RequestMethod.GET) + public String getDates(Model model) { + model.addAttribute("date", new Date()); + model.addAttribute("calendar", Calendar.getInstance()); + model.addAttribute("num", Math.random() * 10); + model.addAttribute("string", "new text"); + model.addAttribute("emptyString", ""); + model.addAttribute("nullString", null); + model.addAttribute("array", new int[] { 1, 3, 4, 5 }); + model.addAttribute("set", new HashSet(Arrays.asList(1, 3, 8))); + return "objects.html"; + } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java index 9e3f14ac8e..e8e6339663 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java @@ -11,23 +11,23 @@ import com.baeldung.thymeleaf.utils.StudentUtils; @Controller public class InliningController { - @RequestMapping(value = "/html", method = RequestMethod.GET) + @RequestMapping(value = "/html", method = RequestMethod.GET) public String getExampleHTML(Model model) { - model.addAttribute("title", "Baeldung"); - model.addAttribute("description", "Thymeleaf tutorial"); + model.addAttribute("title", "Baeldung"); + model.addAttribute("description", "Thymeleaf tutorial"); return "inliningExample.html"; } - - @RequestMapping(value = "/js", method = RequestMethod.GET) + + @RequestMapping(value = "/js", method = RequestMethod.GET) public String getExampleJS(Model model) { - model.addAttribute("students", StudentUtils.buildStudents()); + model.addAttribute("students", StudentUtils.buildStudents()); return "studentCheck.js"; } - - @RequestMapping(value = "/plain", method = RequestMethod.GET) + + @RequestMapping(value = "/plain", method = RequestMethod.GET) public String getExamplePlain(Model model) { - model.addAttribute("username", SecurityContextHolder.getContext().getAuthentication().getName()); - model.addAttribute("students", StudentUtils.buildStudents()); + model.addAttribute("username", SecurityContextHolder.getContext().getAuthentication().getName()); + model.addAttribute("students", StudentUtils.buildStudents()); return "studentsList.txt"; } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java index 28a38ce30b..af999233bf 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java @@ -7,8 +7,8 @@ import org.springframework.web.bind.annotation.RequestMethod; @Controller public class LayoutDialectController { - - @RequestMapping(value = "/layout", method = RequestMethod.GET) + + @RequestMapping(value = "/layout", method = RequestMethod.GET) public String getNewPage(Model model) { return "content.html"; } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java index 1f40046caa..77cf02c902 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java @@ -21,30 +21,30 @@ import com.baeldung.thymeleaf.utils.StudentUtils; @Controller public class StudentController { - @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) - public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { - if (!errors.hasErrors()) { - // get mock objects - List students = StudentUtils.buildStudents(); - // add current student - students.add(student); - model.addAttribute("students", students); - } - return ((errors.hasErrors()) ? "addStudent.html" : "listStudents.html"); - } + @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) + public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { + if (!errors.hasErrors()) { + // get mock objects + List students = StudentUtils.buildStudents(); + // add current student + students.add(student); + model.addAttribute("students", students); + } + return ((errors.hasErrors()) ? "addStudent.html" : "listStudents.html"); + } - @RequestMapping(value = "/addStudent", method = RequestMethod.GET) - public String addStudent(Model model) { - model.addAttribute("student", new Student()); - return "addStudent.html"; - } + @RequestMapping(value = "/addStudent", method = RequestMethod.GET) + public String addStudent(Model model) { + model.addAttribute("student", new Student()); + return "addStudent.html"; + } - @RequestMapping(value = "/listStudents", method = RequestMethod.GET) - public String listStudent(Model model) { + @RequestMapping(value = "/listStudents", method = RequestMethod.GET) + public String listStudent(Model model) { - model.addAttribute("students", StudentUtils.buildStudents()); + model.addAttribute("students", StudentUtils.buildStudents()); - return "listStudents.html"; - } + return "listStudents.html"; + } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java index d85c70c1b7..5c07476c9b 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java @@ -2,7 +2,7 @@ package com.baeldung.thymeleaf.utils; public class ArrayUtil { - public static String[] array(String... args) { - return args; - } + public static String[] array(String... args) { + return args; + } } \ No newline at end of file diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java index f7ed254641..5ee2b7eb85 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java @@ -7,28 +7,28 @@ import com.baeldung.thymeleaf.model.Student; public class StudentUtils { - private static List students = new ArrayList(); + private static List students = new ArrayList(); - public static List buildStudents() { - if (students.isEmpty()){ - Student student1 = new Student(); - student1.setId(1001); - student1.setName("John Smith"); - student1.setGender('M'); - student1.setPercentage(Float.valueOf("80.45")); + public static List buildStudents() { + if (students.isEmpty()) { + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + student1.setGender('M'); + student1.setPercentage(Float.valueOf("80.45")); - students.add(student1); + students.add(student1); - Student student2 = new Student(); - student2.setId(1002); - student2.setName("Jane Williams"); - student2.setGender('F'); - student2.setPercentage(Float.valueOf("60.25")); + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + student2.setGender('F'); + student2.setPercentage(Float.valueOf("60.25")); - students.add(student2); - } - - return students; - } + students.add(student2); + } + + return students; + } } diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/dates.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/dates.html new file mode 100644 index 0000000000..f8db1030f2 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/dates.html @@ -0,0 +1,35 @@ + + + + +Baeldung - dates + + +

    Format ISO

    +

    +

    +

    +

    + +

    Format manually

    +

    +

    +

    + +

    Show only which day of a week

    +

    +

    +

    + +

    Show the name of the week day

    +

    +

    +

    + +

    Show the second of the day

    +

    +

    + + + \ No newline at end of file diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java index 0638dbbc11..5211136c35 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java @@ -30,9 +30,10 @@ import com.baeldung.thymeleaf.config.WebMVCSecurity; @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) public class ExpressionUtilityObjectsControllerIntegrationTest { - - @Autowired + + @Autowired WebApplicationContext wac; + @Autowired MockHttpSession session; @@ -50,9 +51,14 @@ public class ExpressionUtilityObjectsControllerIntegrationTest { mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); } - @Test - public void testGetDates() throws Exception{ - mockMvc.perform(get("/objects").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("objects.html")); - } + @Test + public void testGetObjects() throws Exception { + mockMvc.perform(get("/objects").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("objects.html")); + } + + @Test + public void testDates() throws Exception { + mockMvc.perform(get("/dates").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("dates.html")); + } } diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java index 23113dc229..62c364f864 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java @@ -31,7 +31,7 @@ import com.baeldung.thymeleaf.config.WebMVCSecurity; @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) public class LayoutDialectControllerIntegrationTest { - @Autowired + @Autowired WebApplicationContext wac; @Autowired MockHttpSession session; @@ -50,9 +50,9 @@ public class LayoutDialectControllerIntegrationTest { mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); } - @Test - public void testGetDates() throws Exception{ - mockMvc.perform(get("/layout").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("content.html")); - } + @Test + public void testGetDates() throws Exception { + mockMvc.perform(get("/layout").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("content.html")); + } } diff --git a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index 3542571bbc..3d8ddfdd5c 100644 --- a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -59,17 +59,17 @@ public class CsrfEnabledIntegrationTest { public void addStudentWithCSRF() throws Exception { mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk()); } - + @Test public void htmlInliningTest() throws Exception { mockMvc.perform(get("/html").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("inliningExample.html")); } - + @Test public void jsInliningTest() throws Exception { mockMvc.perform(get("/js").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("studentCheck.js")); } - + @Test public void plainInliningTest() throws Exception { mockMvc.perform(get("/plain").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("studentsList.txt")); diff --git a/static-analysis/pom.xml b/static-analysis/pom.xml new file mode 100644 index 0000000000..737816ec10 --- /dev/null +++ b/static-analysis/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + com.baeldung + static-analysis + 1.0-SNAPSHOT + + + + + + + + org.apache.maven.plugins + maven-pmd-plugin + 3.7 + + + rulesets/java/braces.xml + rulesets/java/naming.xml + + + + + + + \ No newline at end of file diff --git a/static-analysis/src/main/java/com/baeldung/pmd/Cnt.java b/static-analysis/src/main/java/com/baeldung/pmd/Cnt.java new file mode 100644 index 0000000000..4953646c9d --- /dev/null +++ b/static-analysis/src/main/java/com/baeldung/pmd/Cnt.java @@ -0,0 +1,12 @@ +package com.baeldung.pmd; + +public class Cnt { + + public int d(int a, int b) { + if (b == 0) + return Integer.MAX_VALUE; + else + return a / b; + } + +} diff --git a/static-analysis/src/main/resources/customruleset.xml b/static-analysis/src/main/resources/customruleset.xml new file mode 100644 index 0000000000..e0a009dd4a --- /dev/null +++ b/static-analysis/src/main/resources/customruleset.xml @@ -0,0 +1,37 @@ + + + + + This ruleset checks my code for bad stuff + + + + + + + + + + + + + + 2 + + + + + + + + + + + + + + + \ No newline at end of file