diff --git a/.gitignore b/.gitignore index e841cc4bf5..784627b616 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,5 @@ target/ spring-openid/src/main/resources/application.properties .recommenders/ +/spring-hibernate4/nbproject/ +spring-security-openid/src/main/resources/application.properties diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000..c2a369a1b3 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,17 @@ +language: java + +install: travis_wait 40 mvn -q clean install -Dgib.enabled=true + +jdk: + - oraclejdk8 + +sudo: false +addons: + apt: + packages: + - oracle-java8-installer + +cache: + directories: + - .autoconf + - $HOME/.m2 \ No newline at end of file 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..1d41f46adb --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java @@ -0,0 +1,57 @@ +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..07606bde4b --- /dev/null +++ b/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java @@ -0,0 +1,75 @@ +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/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java index 0883e108e7..18d8f9a8a9 100644 --- a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java +++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java @@ -27,17 +27,12 @@ public class BuilderProcessor extends AbstractProcessor { Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); - Map> annotatedMethods = annotatedElements.stream() - .collect(Collectors.partitioningBy(element -> - ((ExecutableType) element.asType()).getParameterTypes().size() == 1 - && element.getSimpleName().toString().startsWith("set"))); + Map> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set"))); List setters = annotatedMethods.get(true); List otherMethods = annotatedMethods.get(false); - otherMethods.forEach(element -> - processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, - "@BuilderProperty must be applied to a setXxx method with a single argument", element)); + otherMethods.forEach(element -> processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@BuilderProperty must be applied to a setXxx method with a single argument", element)); if (setters.isEmpty()) { continue; @@ -45,11 +40,7 @@ public class BuilderProcessor extends AbstractProcessor { String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString(); - Map setterMap = setters.stream().collect(Collectors.toMap( - setter -> setter.getSimpleName().toString(), - setter -> ((ExecutableType) setter.asType()) - .getParameterTypes().get(0).toString() - )); + Map setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString())); try { writeBuilderFile(className, setterMap); diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java index 72f9ac8bc7..8d01f8a517 100644 --- a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java +++ b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java @@ -9,10 +9,7 @@ public class PersonBuilderTest { @Test public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() { - Person person = new PersonBuilder() - .setAge(25) - .setName("John") - .build(); + Person person = new PersonBuilder().setAge(25).setName("John").build(); assertEquals(25, person.getAge()); assertEquals("John", person.getName()); 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/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java index 0e5af60b9d..2ac649f4c5 100644 --- a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java +++ b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java @@ -8,7 +8,7 @@ public class Server { String address = "http://localhost:8080/baeldung"; Endpoint.publish(address, implementor); System.out.println("Server ready..."); - Thread.sleep(60 * 1000); + Thread.sleep(60 * 1000); System.out.println("Server exiting"); System.exit(0); } diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java index d3ed2eb70e..0605aef7b3 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java @@ -11,7 +11,7 @@ public class RestfulServer { factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository())); factoryBean.setAddress("http://localhost:8080/"); Server server = factoryBean.create(); - + System.out.println("Server ready..."); Thread.sleep(60 * 1000); System.out.println("Server exiting"); 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..10fe8ba2e7 --- /dev/null +++ b/apache-poi/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi) +- [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel) diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml index d94b2e2ad1..d8a2cc72e0 100644 --- a/apache-poi/pom.xml +++ b/apache-poi/pom.xml @@ -9,6 +9,7 @@ 3.6.0 4.12 3.15 + 1.0.6 @@ -37,5 +38,10 @@ poi-ooxml ${poi.version} + + org.jxls + jxls-jexcel + ${jexcel.version} + diff --git a/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java new file mode 100644 index 0000000000..4ad3fc766c --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java @@ -0,0 +1,74 @@ +package com.baeldung.jexcel; + +import jxl.*; +import java.util.Map; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.List; +import jxl.read.biff.BiffException; +import java.io.File; +import java.io.IOException; +import jxl.write.*; +import jxl.write.Number; +import jxl.format.Colour; + +public class JExcelHelper { + + public Map> readJExcel(String fileLocation) throws IOException, BiffException { + Map> data = new HashMap<>(); + + Workbook workbook = Workbook.getWorkbook(new File(fileLocation)); + Sheet sheet = workbook.getSheet(0); + int rows = sheet.getRows(); + int columns = sheet.getColumns(); + + for (int i = 0; i < rows; i++) { + data.put(i, new ArrayList()); + for (int j = 0; j < columns; j++) { + data.get(i).add(sheet.getCell(j, i).getContents()); + } + } + return data; + } + + public void writeJExcel() throws IOException, WriteException { + WritableWorkbook workbook = null; + try { + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + String fileLocation = path.substring(0, path.length() - 1) + "temp.xls"; + + workbook = Workbook.createWorkbook(new File(fileLocation)); + + WritableSheet sheet = workbook.createSheet("Sheet 1", 0); + + WritableCellFormat headerFormat = new WritableCellFormat(); + WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD); + headerFormat.setFont(font); + headerFormat.setBackground(Colour.LIGHT_BLUE); + headerFormat.setWrap(true); + Label headerLabel = new Label(0, 0, "Name", headerFormat); + sheet.setColumnView(0, 60); + sheet.addCell(headerLabel); + + headerLabel = new Label(1, 0, "Age", headerFormat); + sheet.setColumnView(0, 40); + sheet.addCell(headerLabel); + + WritableCellFormat cellFormat = new WritableCellFormat(); + cellFormat.setWrap(true); + + Label cellLabel = new Label(0, 2, "John Smith", cellFormat); + sheet.addCell(cellLabel); + Number cellNumber = new Number(1, 2, 20, cellFormat); + sheet.addCell(cellNumber); + + workbook.write(); + } finally { + if (workbook != null) { + workbook.close(); + } + } + + } +} \ No newline at end of file diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java new file mode 100644 index 0000000000..b6b0cbef20 --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java @@ -0,0 +1,128 @@ +package com.baeldung.poi.excel; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.ss.usermodel.FillPatternType; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.List; + +public class ExcelPOIHelper { + + public Map> readExcel(String fileLocation) throws IOException { + + Map> data = new HashMap<>(); + FileInputStream file = new FileInputStream(new File(fileLocation)); + Workbook workbook = new XSSFWorkbook(file); + Sheet sheet = workbook.getSheetAt(0); + int i = 0; + for (Row row : sheet) { + data.put(i, new ArrayList()); + for (Cell cell : row) { + switch (cell.getCellTypeEnum()) { + case STRING: + data.get(i) + .add(cell.getRichStringCellValue() + .getString()); + break; + case NUMERIC: + if (DateUtil.isCellDateFormatted(cell)) { + data.get(i) + .add(cell.getDateCellValue() + ""); + } else { + data.get(i) + .add((int)cell.getNumericCellValue() + ""); + } + break; + case BOOLEAN: + data.get(i) + .add(cell.getBooleanCellValue() + ""); + break; + case FORMULA: + data.get(i) + .add(cell.getCellFormula() + ""); + break; + default: + data.get(i) + .add(" "); + } + } + i++; + } + if (workbook != null){ + workbook.close(); + } + return data; + } + + public void writeExcel() throws IOException { + Workbook workbook = new XSSFWorkbook(); + + try { + Sheet sheet = workbook.createSheet("Persons"); + sheet.setColumnWidth(0, 6000); + sheet.setColumnWidth(1, 4000); + + Row header = sheet.createRow(0); + + CellStyle headerStyle = workbook.createCellStyle(); + + headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex()); + headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); + + XSSFFont font = ((XSSFWorkbook) workbook).createFont(); + font.setFontName("Arial"); + font.setFontHeightInPoints((short) 16); + font.setBold(true); + headerStyle.setFont(font); + + Cell headerCell = header.createCell(0); + headerCell.setCellValue("Name"); + headerCell.setCellStyle(headerStyle); + + headerCell = header.createCell(1); + headerCell.setCellValue("Age"); + headerCell.setCellStyle(headerStyle); + + CellStyle style = workbook.createCellStyle(); + style.setWrapText(true); + + Row row = sheet.createRow(2); + Cell cell = row.createCell(0); + cell.setCellValue("John Smith"); + cell.setCellStyle(style); + + cell = row.createCell(1); + cell.setCellValue(20); + cell.setCellStyle(style); + + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx"; + + FileOutputStream outputStream = new FileOutputStream(fileLocation); + workbook.write(outputStream); + } finally { + if (workbook != null) { + + workbook.close(); + + } + } + } + +} \ No newline at end of file diff --git a/apache-poi/src/main/java/com/baeldung/poi/word/WordDocument.java b/apache-poi/src/main/java/com/baeldung/poi/word/WordDocument.java index c05c323447..599da86eaa 100644 --- a/apache-poi/src/main/java/com/baeldung/poi/word/WordDocument.java +++ b/apache-poi/src/main/java/com/baeldung/poi/word/WordDocument.java @@ -1,5 +1,8 @@ package com.baeldung.poi.word; +import org.apache.poi.util.Units; +import org.apache.poi.xwpf.usermodel.*; + import java.io.FileOutputStream; import java.io.IOException; import java.net.URISyntaxException; @@ -9,13 +12,6 @@ import java.nio.file.Paths; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.ParagraphAlignment; -import org.apache.poi.xwpf.usermodel.UnderlinePatterns; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; - public class WordDocument { public static String logo = "logo-leaf.png"; public static String paragraph1 = "poi-word-para1.txt"; diff --git a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java new file mode 100644 index 0000000000..8ee465be34 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java @@ -0,0 +1,56 @@ +package com.baeldung.jexcel; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import jxl.read.biff.BiffException; +import java.util.Map; +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.jexcel.JExcelHelper; + +import jxl.write.WriteException; +import jxl.read.biff.BiffException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.Before; + +public class JExcelTest { + + private JExcelHelper jExcelHelper; + private static String FILE_NAME = "temp.xls"; + private String fileLocation; + + @Before + public void generateExcelFile() throws IOException, WriteException { + + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; + + jExcelHelper = new JExcelHelper(); + jExcelHelper.writeJExcel(); + + } + + @Test + public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException { + Map> data = jExcelHelper.readJExcel(fileLocation); + + assertEquals("Name", data.get(0) + .get(0)); + assertEquals("Age", data.get(0) + .get(1)); + + assertEquals("John Smith", data.get(2) + .get(0)); + assertEquals("20", data.get(2) + .get(1)); + } + +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java new file mode 100644 index 0000000000..34fa64dd94 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java @@ -0,0 +1,53 @@ +package com.baeldung.poi.excel; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import jxl.read.biff.BiffException; +import java.util.Map; +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.poi.excel.ExcelPOIHelper; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.Before; + +public class ExcelTest { + + private ExcelPOIHelper excelPOIHelper; + private static String FILE_NAME = "temp.xlsx"; + private String fileLocation; + + @Before + public void generateExcelFile() throws IOException { + + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; + + excelPOIHelper = new ExcelPOIHelper(); + excelPOIHelper.writeExcel(); + + } + + @Test + public void whenParsingPOIExcelFile_thenCorrect() throws IOException { + Map> data = excelPOIHelper.readExcel(fileLocation); + + assertEquals("Name", data.get(0) + .get(0)); + assertEquals("Age", data.get(0) + .get(1)); + + assertEquals("John Smith", data.get(1) + .get(0)); + assertEquals("20", data.get(1) + .get(1)); + } + +} \ No newline at end of file diff --git a/apache-poi/temp.xls b/apache-poi/temp.xls new file mode 100644 index 0000000000..1fad76d88d Binary files /dev/null and b/apache-poi/temp.xls differ diff --git a/apache-poi/temp.xlsx b/apache-poi/temp.xlsx new file mode 100644 index 0000000000..da67ca9e9e Binary files /dev/null and b/apache-poi/temp.xlsx differ diff --git a/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformResource.java b/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformResource.java new file mode 100644 index 0000000000..6cb5af0695 --- /dev/null +++ b/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformResource.java @@ -0,0 +1,579 @@ +/** + * Autogenerated by Thrift Compiler (0.10.0) + * + * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING + * @generated + */ +package com.baeldung.thrift.impl; + +@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) +@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01") +public class CrossPlatformResource implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CrossPlatformResource"); + + private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I32, (short)1); + private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)2); + private static final org.apache.thrift.protocol.TField SALUTATION_FIELD_DESC = new org.apache.thrift.protocol.TField("salutation", org.apache.thrift.protocol.TType.STRING, (short)3); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new CrossPlatformResourceStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new CrossPlatformResourceTupleSchemeFactory(); + + public int id; // required + public java.lang.String name; // required + public java.lang.String salutation; // optional + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + ID((short)1, "id"), + NAME((short)2, "name"), + SALUTATION((short)3, "salutation"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // ID + return ID; + case 2: // NAME + return NAME; + case 3: // SALUTATION + return SALUTATION; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(java.lang.String name) { + return byName.get(name); + } + + private final short _thriftId; + private final java.lang.String _fieldName; + + _Fields(short thriftId, java.lang.String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public java.lang.String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + private static final int __ID_ISSET_ID = 0; + private byte __isset_bitfield = 0; + private static final _Fields optionals[] = {_Fields.SALUTATION}; + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); + tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + tmpMap.put(_Fields.SALUTATION, new org.apache.thrift.meta_data.FieldMetaData("salutation", org.apache.thrift.TFieldRequirementType.OPTIONAL, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CrossPlatformResource.class, metaDataMap); + } + + public CrossPlatformResource() { + } + + public CrossPlatformResource( + int id, + java.lang.String name) + { + this(); + this.id = id; + setIdIsSet(true); + this.name = name; + } + + /** + * Performs a deep copy on other. + */ + public CrossPlatformResource(CrossPlatformResource other) { + __isset_bitfield = other.__isset_bitfield; + this.id = other.id; + if (other.isSetName()) { + this.name = other.name; + } + if (other.isSetSalutation()) { + this.salutation = other.salutation; + } + } + + public CrossPlatformResource deepCopy() { + return new CrossPlatformResource(this); + } + + @Override + public void clear() { + setIdIsSet(false); + this.id = 0; + this.name = null; + this.salutation = null; + } + + public int getId() { + return this.id; + } + + public CrossPlatformResource setId(int id) { + this.id = id; + setIdIsSet(true); + return this; + } + + public void unsetId() { + __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID); + } + + /** Returns true if field id is set (has been assigned a value) and false otherwise */ + public boolean isSetId() { + return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID); + } + + public void setIdIsSet(boolean value) { + __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value); + } + + public java.lang.String getName() { + return this.name; + } + + public CrossPlatformResource setName(java.lang.String name) { + this.name = name; + return this; + } + + public void unsetName() { + this.name = null; + } + + /** Returns true if field name is set (has been assigned a value) and false otherwise */ + public boolean isSetName() { + return this.name != null; + } + + public void setNameIsSet(boolean value) { + if (!value) { + this.name = null; + } + } + + public java.lang.String getSalutation() { + return this.salutation; + } + + public CrossPlatformResource setSalutation(java.lang.String salutation) { + this.salutation = salutation; + return this; + } + + public void unsetSalutation() { + this.salutation = null; + } + + /** Returns true if field salutation is set (has been assigned a value) and false otherwise */ + public boolean isSetSalutation() { + return this.salutation != null; + } + + public void setSalutationIsSet(boolean value) { + if (!value) { + this.salutation = null; + } + } + + public void setFieldValue(_Fields field, java.lang.Object value) { + switch (field) { + case ID: + if (value == null) { + unsetId(); + } else { + setId((java.lang.Integer)value); + } + break; + + case NAME: + if (value == null) { + unsetName(); + } else { + setName((java.lang.String)value); + } + break; + + case SALUTATION: + if (value == null) { + unsetSalutation(); + } else { + setSalutation((java.lang.String)value); + } + break; + + } + } + + public java.lang.Object getFieldValue(_Fields field) { + switch (field) { + case ID: + return getId(); + + case NAME: + return getName(); + + case SALUTATION: + return getSalutation(); + + } + throw new java.lang.IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new java.lang.IllegalArgumentException(); + } + + switch (field) { + case ID: + return isSetId(); + case NAME: + return isSetName(); + case SALUTATION: + return isSetSalutation(); + } + throw new java.lang.IllegalStateException(); + } + + @Override + public boolean equals(java.lang.Object that) { + if (that == null) + return false; + if (that instanceof CrossPlatformResource) + return this.equals((CrossPlatformResource)that); + return false; + } + + public boolean equals(CrossPlatformResource that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_id = true; + boolean that_present_id = true; + if (this_present_id || that_present_id) { + if (!(this_present_id && that_present_id)) + return false; + if (this.id != that.id) + return false; + } + + boolean this_present_name = true && this.isSetName(); + boolean that_present_name = true && that.isSetName(); + if (this_present_name || that_present_name) { + if (!(this_present_name && that_present_name)) + return false; + if (!this.name.equals(that.name)) + return false; + } + + boolean this_present_salutation = true && this.isSetSalutation(); + boolean that_present_salutation = true && that.isSetSalutation(); + if (this_present_salutation || that_present_salutation) { + if (!(this_present_salutation && that_present_salutation)) + return false; + if (!this.salutation.equals(that.salutation)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + id; + + hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287); + if (isSetName()) + hashCode = hashCode * 8191 + name.hashCode(); + + hashCode = hashCode * 8191 + ((isSetSalutation()) ? 131071 : 524287); + if (isSetSalutation()) + hashCode = hashCode * 8191 + salutation.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(CrossPlatformResource other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = java.lang.Boolean.valueOf(isSetId()).compareTo(other.isSetId()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetId()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); + if (lastComparison != 0) { + return lastComparison; + } + } + lastComparison = java.lang.Boolean.valueOf(isSetName()).compareTo(other.isSetName()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetName()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); + if (lastComparison != 0) { + return lastComparison; + } + } + lastComparison = java.lang.Boolean.valueOf(isSetSalutation()).compareTo(other.isSetSalutation()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetSalutation()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.salutation, other.salutation); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public java.lang.String toString() { + java.lang.StringBuilder sb = new java.lang.StringBuilder("CrossPlatformResource("); + boolean first = true; + + sb.append("id:"); + sb.append(this.id); + first = false; + if (!first) sb.append(", "); + sb.append("name:"); + if (this.name == null) { + sb.append("null"); + } else { + sb.append(this.name); + } + first = false; + if (isSetSalutation()) { + if (!first) sb.append(", "); + sb.append("salutation:"); + if (this.salutation == null) { + sb.append("null"); + } else { + sb.append(this.salutation); + } + first = false; + } + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { + try { + // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. + __isset_bitfield = 0; + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class CrossPlatformResourceStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public CrossPlatformResourceStandardScheme getScheme() { + return new CrossPlatformResourceStandardScheme(); + } + } + + private static class CrossPlatformResourceStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, CrossPlatformResource struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // ID + if (schemeField.type == org.apache.thrift.protocol.TType.I32) { + struct.id = iprot.readI32(); + struct.setIdIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + case 2: // NAME + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.name = iprot.readString(); + struct.setNameIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + case 3: // SALUTATION + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.salutation = iprot.readString(); + struct.setSalutationIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, CrossPlatformResource struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + oprot.writeFieldBegin(ID_FIELD_DESC); + oprot.writeI32(struct.id); + oprot.writeFieldEnd(); + if (struct.name != null) { + oprot.writeFieldBegin(NAME_FIELD_DESC); + oprot.writeString(struct.name); + oprot.writeFieldEnd(); + } + if (struct.salutation != null) { + if (struct.isSetSalutation()) { + oprot.writeFieldBegin(SALUTATION_FIELD_DESC); + oprot.writeString(struct.salutation); + oprot.writeFieldEnd(); + } + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class CrossPlatformResourceTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public CrossPlatformResourceTupleScheme getScheme() { + return new CrossPlatformResourceTupleScheme(); + } + } + + private static class CrossPlatformResourceTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, CrossPlatformResource struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetId()) { + optionals.set(0); + } + if (struct.isSetName()) { + optionals.set(1); + } + if (struct.isSetSalutation()) { + optionals.set(2); + } + oprot.writeBitSet(optionals, 3); + if (struct.isSetId()) { + oprot.writeI32(struct.id); + } + if (struct.isSetName()) { + oprot.writeString(struct.name); + } + if (struct.isSetSalutation()) { + oprot.writeString(struct.salutation); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, CrossPlatformResource struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(3); + if (incoming.get(0)) { + struct.id = iprot.readI32(); + struct.setIdIsSet(true); + } + if (incoming.get(1)) { + struct.name = iprot.readString(); + struct.setNameIsSet(true); + } + if (incoming.get(2)) { + struct.salutation = iprot.readString(); + struct.setSalutationIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } +} + diff --git a/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformService.java b/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformService.java new file mode 100644 index 0000000000..4e4537f7b6 --- /dev/null +++ b/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformService.java @@ -0,0 +1,3745 @@ +/** + * Autogenerated by Thrift Compiler (0.10.0) + * + * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING + * @generated + */ +package com.baeldung.thrift.impl; + +@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) +@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01") +public class CrossPlatformService { + + public interface Iface { + + public CrossPlatformResource get(int id) throws InvalidOperationException, org.apache.thrift.TException; + + public void save(CrossPlatformResource resource) throws InvalidOperationException, org.apache.thrift.TException; + + public java.util.List getList() throws InvalidOperationException, org.apache.thrift.TException; + + public boolean ping() throws InvalidOperationException, org.apache.thrift.TException; + + } + + public interface AsyncIface { + + public void get(int id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; + + public void save(CrossPlatformResource resource, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; + + public void getList(org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws org.apache.thrift.TException; + + public void ping(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; + + } + + public static class Client extends org.apache.thrift.TServiceClient implements Iface { + public static class Factory implements org.apache.thrift.TServiceClientFactory { + public Factory() {} + public Client getClient(org.apache.thrift.protocol.TProtocol prot) { + return new Client(prot); + } + public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { + return new Client(iprot, oprot); + } + } + + public Client(org.apache.thrift.protocol.TProtocol prot) + { + super(prot, prot); + } + + public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { + super(iprot, oprot); + } + + public CrossPlatformResource get(int id) throws InvalidOperationException, org.apache.thrift.TException + { + send_get(id); + return recv_get(); + } + + public void send_get(int id) throws org.apache.thrift.TException + { + get_args args = new get_args(); + args.setId(id); + sendBase("get", args); + } + + public CrossPlatformResource recv_get() throws InvalidOperationException, org.apache.thrift.TException + { + get_result result = new get_result(); + receiveBase(result, "get"); + if (result.isSetSuccess()) { + return result.success; + } + if (result.e != null) { + throw result.e; + } + throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "get failed: unknown result"); + } + + public void save(CrossPlatformResource resource) throws InvalidOperationException, org.apache.thrift.TException + { + send_save(resource); + recv_save(); + } + + public void send_save(CrossPlatformResource resource) throws org.apache.thrift.TException + { + save_args args = new save_args(); + args.setResource(resource); + sendBase("save", args); + } + + public void recv_save() throws InvalidOperationException, org.apache.thrift.TException + { + save_result result = new save_result(); + receiveBase(result, "save"); + if (result.e != null) { + throw result.e; + } + return; + } + + public java.util.List getList() throws InvalidOperationException, org.apache.thrift.TException + { + send_getList(); + return recv_getList(); + } + + public void send_getList() throws org.apache.thrift.TException + { + getList_args args = new getList_args(); + sendBase("getList", args); + } + + public java.util.List recv_getList() throws InvalidOperationException, org.apache.thrift.TException + { + getList_result result = new getList_result(); + receiveBase(result, "getList"); + if (result.isSetSuccess()) { + return result.success; + } + if (result.e != null) { + throw result.e; + } + throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getList failed: unknown result"); + } + + public boolean ping() throws InvalidOperationException, org.apache.thrift.TException + { + send_ping(); + return recv_ping(); + } + + public void send_ping() throws org.apache.thrift.TException + { + ping_args args = new ping_args(); + sendBase("ping", args); + } + + public boolean recv_ping() throws InvalidOperationException, org.apache.thrift.TException + { + ping_result result = new ping_result(); + receiveBase(result, "ping"); + if (result.isSetSuccess()) { + return result.success; + } + if (result.e != null) { + throw result.e; + } + throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "ping failed: unknown result"); + } + + } + public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { + public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { + private org.apache.thrift.async.TAsyncClientManager clientManager; + private org.apache.thrift.protocol.TProtocolFactory protocolFactory; + public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { + this.clientManager = clientManager; + this.protocolFactory = protocolFactory; + } + public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { + return new AsyncClient(protocolFactory, clientManager, transport); + } + } + + public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { + super(protocolFactory, clientManager, transport); + } + + public void get(int id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + checkReady(); + get_call method_call = new get_call(id, resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class get_call extends org.apache.thrift.async.TAsyncMethodCall { + private int id; + public get_call(int id, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + this.id = id; + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("get", org.apache.thrift.protocol.TMessageType.CALL, 0)); + get_args args = new get_args(); + args.setId(id); + args.write(prot); + prot.writeMessageEnd(); + } + + public CrossPlatformResource getResult() throws InvalidOperationException, org.apache.thrift.TException { + if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { + throw new java.lang.IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return (new Client(prot)).recv_get(); + } + } + + public void save(CrossPlatformResource resource, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + checkReady(); + save_call method_call = new save_call(resource, resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class save_call extends org.apache.thrift.async.TAsyncMethodCall { + private CrossPlatformResource resource; + public save_call(CrossPlatformResource resource, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + this.resource = resource; + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("save", org.apache.thrift.protocol.TMessageType.CALL, 0)); + save_args args = new save_args(); + args.setResource(resource); + args.write(prot); + prot.writeMessageEnd(); + } + + public Void getResult() throws InvalidOperationException, org.apache.thrift.TException { + if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { + throw new java.lang.IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return null; + } + } + + public void getList(org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws org.apache.thrift.TException { + checkReady(); + getList_call method_call = new getList_call(resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class getList_call extends org.apache.thrift.async.TAsyncMethodCall> { + public getList_call(org.apache.thrift.async.AsyncMethodCallback> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getList", org.apache.thrift.protocol.TMessageType.CALL, 0)); + getList_args args = new getList_args(); + args.write(prot); + prot.writeMessageEnd(); + } + + public java.util.List getResult() throws InvalidOperationException, org.apache.thrift.TException { + if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { + throw new java.lang.IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return (new Client(prot)).recv_getList(); + } + } + + public void ping(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + checkReady(); + ping_call method_call = new ping_call(resultHandler, this, ___protocolFactory, ___transport); + this.___currentMethod = method_call; + ___manager.call(method_call); + } + + public static class ping_call extends org.apache.thrift.async.TAsyncMethodCall { + public ping_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { + super(client, protocolFactory, transport, resultHandler, false); + } + + public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { + prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("ping", org.apache.thrift.protocol.TMessageType.CALL, 0)); + ping_args args = new ping_args(); + args.write(prot); + prot.writeMessageEnd(); + } + + public java.lang.Boolean getResult() throws InvalidOperationException, org.apache.thrift.TException { + if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { + throw new java.lang.IllegalStateException("Method call not finished!"); + } + org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); + org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); + return (new Client(prot)).recv_ping(); + } + } + + } + + public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { + private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName()); + public Processor(I iface) { + super(iface, getProcessMap(new java.util.HashMap>())); + } + + protected Processor(I iface, java.util.Map> processMap) { + super(iface, getProcessMap(processMap)); + } + + private static java.util.Map> getProcessMap(java.util.Map> processMap) { + processMap.put("get", new get()); + processMap.put("save", new save()); + processMap.put("getList", new getList()); + processMap.put("ping", new ping()); + return processMap; + } + + public static class get extends org.apache.thrift.ProcessFunction { + public get() { + super("get"); + } + + public get_args getEmptyArgsInstance() { + return new get_args(); + } + + protected boolean isOneway() { + return false; + } + + public get_result getResult(I iface, get_args args) throws org.apache.thrift.TException { + get_result result = new get_result(); + try { + result.success = iface.get(args.id); + } catch (InvalidOperationException e) { + result.e = e; + } + return result; + } + } + + public static class save extends org.apache.thrift.ProcessFunction { + public save() { + super("save"); + } + + public save_args getEmptyArgsInstance() { + return new save_args(); + } + + protected boolean isOneway() { + return false; + } + + public save_result getResult(I iface, save_args args) throws org.apache.thrift.TException { + save_result result = new save_result(); + try { + iface.save(args.resource); + } catch (InvalidOperationException e) { + result.e = e; + } + return result; + } + } + + public static class getList extends org.apache.thrift.ProcessFunction { + public getList() { + super("getList"); + } + + public getList_args getEmptyArgsInstance() { + return new getList_args(); + } + + protected boolean isOneway() { + return false; + } + + public getList_result getResult(I iface, getList_args args) throws org.apache.thrift.TException { + getList_result result = new getList_result(); + try { + result.success = iface.getList(); + } catch (InvalidOperationException e) { + result.e = e; + } + return result; + } + } + + public static class ping extends org.apache.thrift.ProcessFunction { + public ping() { + super("ping"); + } + + public ping_args getEmptyArgsInstance() { + return new ping_args(); + } + + protected boolean isOneway() { + return false; + } + + public ping_result getResult(I iface, ping_args args) throws org.apache.thrift.TException { + ping_result result = new ping_result(); + try { + result.success = iface.ping(); + result.setSuccessIsSet(true); + } catch (InvalidOperationException e) { + result.e = e; + } + return result; + } + } + + } + + public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor { + private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName()); + public AsyncProcessor(I iface) { + super(iface, getProcessMap(new java.util.HashMap>())); + } + + protected AsyncProcessor(I iface, java.util.Map> processMap) { + super(iface, getProcessMap(processMap)); + } + + private static java.util.Map> getProcessMap(java.util.Map> processMap) { + processMap.put("get", new get()); + processMap.put("save", new save()); + processMap.put("getList", new getList()); + processMap.put("ping", new ping()); + return processMap; + } + + public static class get extends org.apache.thrift.AsyncProcessFunction { + public get() { + super("get"); + } + + public get_args getEmptyArgsInstance() { + return new get_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback() { + public void onComplete(CrossPlatformResource o) { + get_result result = new get_result(); + result.success = o; + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (java.lang.Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(java.lang.Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + get_result result = new get_result(); + if (e instanceof InvalidOperationException) { + result.e = (InvalidOperationException) e; + result.setEIsSet(true); + msg = result; + } else if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (java.lang.Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, get_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + iface.get(args.id,resultHandler); + } + } + + public static class save extends org.apache.thrift.AsyncProcessFunction { + public save() { + super("save"); + } + + public save_args getEmptyArgsInstance() { + return new save_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback() { + public void onComplete(Void o) { + save_result result = new save_result(); + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (java.lang.Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(java.lang.Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + save_result result = new save_result(); + if (e instanceof InvalidOperationException) { + result.e = (InvalidOperationException) e; + result.setEIsSet(true); + msg = result; + } else if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (java.lang.Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, save_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + iface.save(args.resource,resultHandler); + } + } + + public static class getList extends org.apache.thrift.AsyncProcessFunction> { + public getList() { + super("getList"); + } + + public getList_args getEmptyArgsInstance() { + return new getList_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback>() { + public void onComplete(java.util.List o) { + getList_result result = new getList_result(); + result.success = o; + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (java.lang.Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(java.lang.Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + getList_result result = new getList_result(); + if (e instanceof InvalidOperationException) { + result.e = (InvalidOperationException) e; + result.setEIsSet(true); + msg = result; + } else if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (java.lang.Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, getList_args args, org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws org.apache.thrift.TException { + iface.getList(resultHandler); + } + } + + public static class ping extends org.apache.thrift.AsyncProcessFunction { + public ping() { + super("ping"); + } + + public ping_args getEmptyArgsInstance() { + return new ping_args(); + } + + public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { + final org.apache.thrift.AsyncProcessFunction fcall = this; + return new org.apache.thrift.async.AsyncMethodCallback() { + public void onComplete(java.lang.Boolean o) { + ping_result result = new ping_result(); + result.success = o; + result.setSuccessIsSet(true); + try { + fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); + } catch (org.apache.thrift.transport.TTransportException e) { + _LOGGER.error("TTransportException writing to internal frame buffer", e); + fb.close(); + } catch (java.lang.Exception e) { + _LOGGER.error("Exception writing to internal frame buffer", e); + onError(e); + } + } + public void onError(java.lang.Exception e) { + byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; + org.apache.thrift.TSerializable msg; + ping_result result = new ping_result(); + if (e instanceof InvalidOperationException) { + result.e = (InvalidOperationException) e; + result.setEIsSet(true); + msg = result; + } else if (e instanceof org.apache.thrift.transport.TTransportException) { + _LOGGER.error("TTransportException inside handler", e); + fb.close(); + return; + } else if (e instanceof org.apache.thrift.TApplicationException) { + _LOGGER.error("TApplicationException inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = (org.apache.thrift.TApplicationException)e; + } else { + _LOGGER.error("Exception inside handler", e); + msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; + msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); + } + try { + fcall.sendResponse(fb,msg,msgType,seqid); + } catch (java.lang.Exception ex) { + _LOGGER.error("Exception writing to internal frame buffer", ex); + fb.close(); + } + } + }; + } + + protected boolean isOneway() { + return false; + } + + public void start(I iface, ping_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { + iface.ping(resultHandler); + } + } + + } + + public static class get_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("get_args"); + + private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I32, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new get_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new get_argsTupleSchemeFactory(); + + public int id; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + ID((short)1, "id"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // ID + return ID; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(java.lang.String name) { + return byName.get(name); + } + + private final short _thriftId; + private final java.lang.String _fieldName; + + _Fields(short thriftId, java.lang.String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public java.lang.String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + private static final int __ID_ISSET_ID = 0; + private byte __isset_bitfield = 0; + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(get_args.class, metaDataMap); + } + + public get_args() { + } + + public get_args( + int id) + { + this(); + this.id = id; + setIdIsSet(true); + } + + /** + * Performs a deep copy on other. + */ + public get_args(get_args other) { + __isset_bitfield = other.__isset_bitfield; + this.id = other.id; + } + + public get_args deepCopy() { + return new get_args(this); + } + + @Override + public void clear() { + setIdIsSet(false); + this.id = 0; + } + + public int getId() { + return this.id; + } + + public get_args setId(int id) { + this.id = id; + setIdIsSet(true); + return this; + } + + public void unsetId() { + __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID); + } + + /** Returns true if field id is set (has been assigned a value) and false otherwise */ + public boolean isSetId() { + return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID); + } + + public void setIdIsSet(boolean value) { + __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value); + } + + public void setFieldValue(_Fields field, java.lang.Object value) { + switch (field) { + case ID: + if (value == null) { + unsetId(); + } else { + setId((java.lang.Integer)value); + } + break; + + } + } + + public java.lang.Object getFieldValue(_Fields field) { + switch (field) { + case ID: + return getId(); + + } + throw new java.lang.IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new java.lang.IllegalArgumentException(); + } + + switch (field) { + case ID: + return isSetId(); + } + throw new java.lang.IllegalStateException(); + } + + @Override + public boolean equals(java.lang.Object that) { + if (that == null) + return false; + if (that instanceof get_args) + return this.equals((get_args)that); + return false; + } + + public boolean equals(get_args that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_id = true; + boolean that_present_id = true; + if (this_present_id || that_present_id) { + if (!(this_present_id && that_present_id)) + return false; + if (this.id != that.id) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + id; + + return hashCode; + } + + @Override + public int compareTo(get_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = java.lang.Boolean.valueOf(isSetId()).compareTo(other.isSetId()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetId()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public java.lang.String toString() { + java.lang.StringBuilder sb = new java.lang.StringBuilder("get_args("); + boolean first = true; + + sb.append("id:"); + sb.append(this.id); + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { + try { + // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. + __isset_bitfield = 0; + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class get_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public get_argsStandardScheme getScheme() { + return new get_argsStandardScheme(); + } + } + + private static class get_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, get_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // ID + if (schemeField.type == org.apache.thrift.protocol.TType.I32) { + struct.id = iprot.readI32(); + struct.setIdIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, get_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + oprot.writeFieldBegin(ID_FIELD_DESC); + oprot.writeI32(struct.id); + oprot.writeFieldEnd(); + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class get_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public get_argsTupleScheme getScheme() { + return new get_argsTupleScheme(); + } + } + + private static class get_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, get_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetId()) { + optionals.set(0); + } + oprot.writeBitSet(optionals, 1); + if (struct.isSetId()) { + oprot.writeI32(struct.id); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, get_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(1); + if (incoming.get(0)) { + struct.id = iprot.readI32(); + struct.setIdIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class get_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("get_result"); + + private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); + private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new get_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new get_resultTupleSchemeFactory(); + + public CrossPlatformResource success; // required + public InvalidOperationException e; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + SUCCESS((short)0, "success"), + E((short)1, "e"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 0: // SUCCESS + return SUCCESS; + case 1: // E + return E; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(java.lang.String name) { + return byName.get(name); + } + + private final short _thriftId; + private final java.lang.String _fieldName; + + _Fields(short thriftId, java.lang.String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public java.lang.String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CrossPlatformResource.class))); + tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, InvalidOperationException.class))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(get_result.class, metaDataMap); + } + + public get_result() { + } + + public get_result( + CrossPlatformResource success, + InvalidOperationException e) + { + this(); + this.success = success; + this.e = e; + } + + /** + * Performs a deep copy on other. + */ + public get_result(get_result other) { + if (other.isSetSuccess()) { + this.success = new CrossPlatformResource(other.success); + } + if (other.isSetE()) { + this.e = new InvalidOperationException(other.e); + } + } + + public get_result deepCopy() { + return new get_result(this); + } + + @Override + public void clear() { + this.success = null; + this.e = null; + } + + public CrossPlatformResource getSuccess() { + return this.success; + } + + public get_result setSuccess(CrossPlatformResource success) { + this.success = success; + return this; + } + + public void unsetSuccess() { + this.success = null; + } + + /** Returns true if field success is set (has been assigned a value) and false otherwise */ + public boolean isSetSuccess() { + return this.success != null; + } + + public void setSuccessIsSet(boolean value) { + if (!value) { + this.success = null; + } + } + + public InvalidOperationException getE() { + return this.e; + } + + public get_result setE(InvalidOperationException e) { + this.e = e; + return this; + } + + public void unsetE() { + this.e = null; + } + + /** Returns true if field e is set (has been assigned a value) and false otherwise */ + public boolean isSetE() { + return this.e != null; + } + + public void setEIsSet(boolean value) { + if (!value) { + this.e = null; + } + } + + public void setFieldValue(_Fields field, java.lang.Object value) { + switch (field) { + case SUCCESS: + if (value == null) { + unsetSuccess(); + } else { + setSuccess((CrossPlatformResource)value); + } + break; + + case E: + if (value == null) { + unsetE(); + } else { + setE((InvalidOperationException)value); + } + break; + + } + } + + public java.lang.Object getFieldValue(_Fields field) { + switch (field) { + case SUCCESS: + return getSuccess(); + + case E: + return getE(); + + } + throw new java.lang.IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new java.lang.IllegalArgumentException(); + } + + switch (field) { + case SUCCESS: + return isSetSuccess(); + case E: + return isSetE(); + } + throw new java.lang.IllegalStateException(); + } + + @Override + public boolean equals(java.lang.Object that) { + if (that == null) + return false; + if (that instanceof get_result) + return this.equals((get_result)that); + return false; + } + + public boolean equals(get_result that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_success = true && this.isSetSuccess(); + boolean that_present_success = true && that.isSetSuccess(); + if (this_present_success || that_present_success) { + if (!(this_present_success && that_present_success)) + return false; + if (!this.success.equals(that.success)) + return false; + } + + boolean this_present_e = true && this.isSetE(); + boolean that_present_e = true && that.isSetE(); + if (this_present_e || that_present_e) { + if (!(this_present_e && that_present_e)) + return false; + if (!this.e.equals(that.e)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); + if (isSetSuccess()) + hashCode = hashCode * 8191 + success.hashCode(); + + hashCode = hashCode * 8191 + ((isSetE()) ? 131071 : 524287); + if (isSetE()) + hashCode = hashCode * 8191 + e.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(get_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = java.lang.Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetSuccess()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); + if (lastComparison != 0) { + return lastComparison; + } + } + lastComparison = java.lang.Boolean.valueOf(isSetE()).compareTo(other.isSetE()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetE()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public java.lang.String toString() { + java.lang.StringBuilder sb = new java.lang.StringBuilder("get_result("); + boolean first = true; + + sb.append("success:"); + if (this.success == null) { + sb.append("null"); + } else { + sb.append(this.success); + } + first = false; + if (!first) sb.append(", "); + sb.append("e:"); + if (this.e == null) { + sb.append("null"); + } else { + sb.append(this.e); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + if (success != null) { + success.validate(); + } + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class get_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public get_resultStandardScheme getScheme() { + return new get_resultStandardScheme(); + } + } + + private static class get_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, get_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 0: // SUCCESS + if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { + struct.success = new CrossPlatformResource(); + struct.success.read(iprot); + struct.setSuccessIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + case 1: // E + if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { + struct.e = new InvalidOperationException(); + struct.e.read(iprot); + struct.setEIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, get_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.success != null) { + oprot.writeFieldBegin(SUCCESS_FIELD_DESC); + struct.success.write(oprot); + oprot.writeFieldEnd(); + } + if (struct.e != null) { + oprot.writeFieldBegin(E_FIELD_DESC); + struct.e.write(oprot); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class get_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public get_resultTupleScheme getScheme() { + return new get_resultTupleScheme(); + } + } + + private static class get_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, get_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetSuccess()) { + optionals.set(0); + } + if (struct.isSetE()) { + optionals.set(1); + } + oprot.writeBitSet(optionals, 2); + if (struct.isSetSuccess()) { + struct.success.write(oprot); + } + if (struct.isSetE()) { + struct.e.write(oprot); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, get_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(2); + if (incoming.get(0)) { + struct.success = new CrossPlatformResource(); + struct.success.read(iprot); + struct.setSuccessIsSet(true); + } + if (incoming.get(1)) { + struct.e = new InvalidOperationException(); + struct.e.read(iprot); + struct.setEIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class save_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("save_args"); + + private static final org.apache.thrift.protocol.TField RESOURCE_FIELD_DESC = new org.apache.thrift.protocol.TField("resource", org.apache.thrift.protocol.TType.STRUCT, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new save_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new save_argsTupleSchemeFactory(); + + public CrossPlatformResource resource; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + RESOURCE((short)1, "resource"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // RESOURCE + return RESOURCE; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(java.lang.String name) { + return byName.get(name); + } + + private final short _thriftId; + private final java.lang.String _fieldName; + + _Fields(short thriftId, java.lang.String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public java.lang.String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.RESOURCE, new org.apache.thrift.meta_data.FieldMetaData("resource", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CrossPlatformResource.class))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(save_args.class, metaDataMap); + } + + public save_args() { + } + + public save_args( + CrossPlatformResource resource) + { + this(); + this.resource = resource; + } + + /** + * Performs a deep copy on other. + */ + public save_args(save_args other) { + if (other.isSetResource()) { + this.resource = new CrossPlatformResource(other.resource); + } + } + + public save_args deepCopy() { + return new save_args(this); + } + + @Override + public void clear() { + this.resource = null; + } + + public CrossPlatformResource getResource() { + return this.resource; + } + + public save_args setResource(CrossPlatformResource resource) { + this.resource = resource; + return this; + } + + public void unsetResource() { + this.resource = null; + } + + /** Returns true if field resource is set (has been assigned a value) and false otherwise */ + public boolean isSetResource() { + return this.resource != null; + } + + public void setResourceIsSet(boolean value) { + if (!value) { + this.resource = null; + } + } + + public void setFieldValue(_Fields field, java.lang.Object value) { + switch (field) { + case RESOURCE: + if (value == null) { + unsetResource(); + } else { + setResource((CrossPlatformResource)value); + } + break; + + } + } + + public java.lang.Object getFieldValue(_Fields field) { + switch (field) { + case RESOURCE: + return getResource(); + + } + throw new java.lang.IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new java.lang.IllegalArgumentException(); + } + + switch (field) { + case RESOURCE: + return isSetResource(); + } + throw new java.lang.IllegalStateException(); + } + + @Override + public boolean equals(java.lang.Object that) { + if (that == null) + return false; + if (that instanceof save_args) + return this.equals((save_args)that); + return false; + } + + public boolean equals(save_args that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_resource = true && this.isSetResource(); + boolean that_present_resource = true && that.isSetResource(); + if (this_present_resource || that_present_resource) { + if (!(this_present_resource && that_present_resource)) + return false; + if (!this.resource.equals(that.resource)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetResource()) ? 131071 : 524287); + if (isSetResource()) + hashCode = hashCode * 8191 + resource.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(save_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = java.lang.Boolean.valueOf(isSetResource()).compareTo(other.isSetResource()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetResource()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.resource, other.resource); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public java.lang.String toString() { + java.lang.StringBuilder sb = new java.lang.StringBuilder("save_args("); + boolean first = true; + + sb.append("resource:"); + if (this.resource == null) { + sb.append("null"); + } else { + sb.append(this.resource); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + if (resource != null) { + resource.validate(); + } + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class save_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public save_argsStandardScheme getScheme() { + return new save_argsStandardScheme(); + } + } + + private static class save_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, save_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // RESOURCE + if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { + struct.resource = new CrossPlatformResource(); + struct.resource.read(iprot); + struct.setResourceIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, save_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.resource != null) { + oprot.writeFieldBegin(RESOURCE_FIELD_DESC); + struct.resource.write(oprot); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class save_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public save_argsTupleScheme getScheme() { + return new save_argsTupleScheme(); + } + } + + private static class save_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, save_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetResource()) { + optionals.set(0); + } + oprot.writeBitSet(optionals, 1); + if (struct.isSetResource()) { + struct.resource.write(oprot); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, save_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(1); + if (incoming.get(0)) { + struct.resource = new CrossPlatformResource(); + struct.resource.read(iprot); + struct.setResourceIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class save_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("save_result"); + + private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new save_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new save_resultTupleSchemeFactory(); + + public InvalidOperationException e; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + E((short)1, "e"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // E + return E; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(java.lang.String name) { + return byName.get(name); + } + + private final short _thriftId; + private final java.lang.String _fieldName; + + _Fields(short thriftId, java.lang.String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public java.lang.String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, InvalidOperationException.class))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(save_result.class, metaDataMap); + } + + public save_result() { + } + + public save_result( + InvalidOperationException e) + { + this(); + this.e = e; + } + + /** + * Performs a deep copy on other. + */ + public save_result(save_result other) { + if (other.isSetE()) { + this.e = new InvalidOperationException(other.e); + } + } + + public save_result deepCopy() { + return new save_result(this); + } + + @Override + public void clear() { + this.e = null; + } + + public InvalidOperationException getE() { + return this.e; + } + + public save_result setE(InvalidOperationException e) { + this.e = e; + return this; + } + + public void unsetE() { + this.e = null; + } + + /** Returns true if field e is set (has been assigned a value) and false otherwise */ + public boolean isSetE() { + return this.e != null; + } + + public void setEIsSet(boolean value) { + if (!value) { + this.e = null; + } + } + + public void setFieldValue(_Fields field, java.lang.Object value) { + switch (field) { + case E: + if (value == null) { + unsetE(); + } else { + setE((InvalidOperationException)value); + } + break; + + } + } + + public java.lang.Object getFieldValue(_Fields field) { + switch (field) { + case E: + return getE(); + + } + throw new java.lang.IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new java.lang.IllegalArgumentException(); + } + + switch (field) { + case E: + return isSetE(); + } + throw new java.lang.IllegalStateException(); + } + + @Override + public boolean equals(java.lang.Object that) { + if (that == null) + return false; + if (that instanceof save_result) + return this.equals((save_result)that); + return false; + } + + public boolean equals(save_result that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_e = true && this.isSetE(); + boolean that_present_e = true && that.isSetE(); + if (this_present_e || that_present_e) { + if (!(this_present_e && that_present_e)) + return false; + if (!this.e.equals(that.e)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetE()) ? 131071 : 524287); + if (isSetE()) + hashCode = hashCode * 8191 + e.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(save_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = java.lang.Boolean.valueOf(isSetE()).compareTo(other.isSetE()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetE()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public java.lang.String toString() { + java.lang.StringBuilder sb = new java.lang.StringBuilder("save_result("); + boolean first = true; + + sb.append("e:"); + if (this.e == null) { + sb.append("null"); + } else { + sb.append(this.e); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class save_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public save_resultStandardScheme getScheme() { + return new save_resultStandardScheme(); + } + } + + private static class save_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, save_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // E + if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { + struct.e = new InvalidOperationException(); + struct.e.read(iprot); + struct.setEIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, save_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.e != null) { + oprot.writeFieldBegin(E_FIELD_DESC); + struct.e.write(oprot); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class save_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public save_resultTupleScheme getScheme() { + return new save_resultTupleScheme(); + } + } + + private static class save_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, save_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetE()) { + optionals.set(0); + } + oprot.writeBitSet(optionals, 1); + if (struct.isSetE()) { + struct.e.write(oprot); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, save_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(1); + if (incoming.get(0)) { + struct.e = new InvalidOperationException(); + struct.e.read(iprot); + struct.setEIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class getList_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getList_args"); + + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new getList_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new getList_argsTupleSchemeFactory(); + + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { +; + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(java.lang.String name) { + return byName.get(name); + } + + private final short _thriftId; + private final java.lang.String _fieldName; + + _Fields(short thriftId, java.lang.String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public java.lang.String getFieldName() { + return _fieldName; + } + } + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getList_args.class, metaDataMap); + } + + public getList_args() { + } + + /** + * Performs a deep copy on other. + */ + public getList_args(getList_args other) { + } + + public getList_args deepCopy() { + return new getList_args(this); + } + + @Override + public void clear() { + } + + public void setFieldValue(_Fields field, java.lang.Object value) { + switch (field) { + } + } + + public java.lang.Object getFieldValue(_Fields field) { + switch (field) { + } + throw new java.lang.IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new java.lang.IllegalArgumentException(); + } + + switch (field) { + } + throw new java.lang.IllegalStateException(); + } + + @Override + public boolean equals(java.lang.Object that) { + if (that == null) + return false; + if (that instanceof getList_args) + return this.equals((getList_args)that); + return false; + } + + public boolean equals(getList_args that) { + if (that == null) + return false; + if (this == that) + return true; + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + return hashCode; + } + + @Override + public int compareTo(getList_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public java.lang.String toString() { + java.lang.StringBuilder sb = new java.lang.StringBuilder("getList_args("); + boolean first = true; + + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class getList_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public getList_argsStandardScheme getScheme() { + return new getList_argsStandardScheme(); + } + } + + private static class getList_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, getList_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, getList_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class getList_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public getList_argsTupleScheme getScheme() { + return new getList_argsTupleScheme(); + } + } + + private static class getList_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, getList_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, getList_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class getList_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getList_result"); + + private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.LIST, (short)0); + private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new getList_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new getList_resultTupleSchemeFactory(); + + public java.util.List success; // required + public InvalidOperationException e; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + SUCCESS((short)0, "success"), + E((short)1, "e"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 0: // SUCCESS + return SUCCESS; + case 1: // E + return E; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(java.lang.String name) { + return byName.get(name); + } + + private final short _thriftId; + private final java.lang.String _fieldName; + + _Fields(short thriftId, java.lang.String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public java.lang.String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, + new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CrossPlatformResource.class)))); + tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, InvalidOperationException.class))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getList_result.class, metaDataMap); + } + + public getList_result() { + } + + public getList_result( + java.util.List success, + InvalidOperationException e) + { + this(); + this.success = success; + this.e = e; + } + + /** + * Performs a deep copy on other. + */ + public getList_result(getList_result other) { + if (other.isSetSuccess()) { + java.util.List __this__success = new java.util.ArrayList(other.success.size()); + for (CrossPlatformResource other_element : other.success) { + __this__success.add(new CrossPlatformResource(other_element)); + } + this.success = __this__success; + } + if (other.isSetE()) { + this.e = new InvalidOperationException(other.e); + } + } + + public getList_result deepCopy() { + return new getList_result(this); + } + + @Override + public void clear() { + this.success = null; + this.e = null; + } + + public int getSuccessSize() { + return (this.success == null) ? 0 : this.success.size(); + } + + public java.util.Iterator getSuccessIterator() { + return (this.success == null) ? null : this.success.iterator(); + } + + public void addToSuccess(CrossPlatformResource elem) { + if (this.success == null) { + this.success = new java.util.ArrayList(); + } + this.success.add(elem); + } + + public java.util.List getSuccess() { + return this.success; + } + + public getList_result setSuccess(java.util.List success) { + this.success = success; + return this; + } + + public void unsetSuccess() { + this.success = null; + } + + /** Returns true if field success is set (has been assigned a value) and false otherwise */ + public boolean isSetSuccess() { + return this.success != null; + } + + public void setSuccessIsSet(boolean value) { + if (!value) { + this.success = null; + } + } + + public InvalidOperationException getE() { + return this.e; + } + + public getList_result setE(InvalidOperationException e) { + this.e = e; + return this; + } + + public void unsetE() { + this.e = null; + } + + /** Returns true if field e is set (has been assigned a value) and false otherwise */ + public boolean isSetE() { + return this.e != null; + } + + public void setEIsSet(boolean value) { + if (!value) { + this.e = null; + } + } + + public void setFieldValue(_Fields field, java.lang.Object value) { + switch (field) { + case SUCCESS: + if (value == null) { + unsetSuccess(); + } else { + setSuccess((java.util.List)value); + } + break; + + case E: + if (value == null) { + unsetE(); + } else { + setE((InvalidOperationException)value); + } + break; + + } + } + + public java.lang.Object getFieldValue(_Fields field) { + switch (field) { + case SUCCESS: + return getSuccess(); + + case E: + return getE(); + + } + throw new java.lang.IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new java.lang.IllegalArgumentException(); + } + + switch (field) { + case SUCCESS: + return isSetSuccess(); + case E: + return isSetE(); + } + throw new java.lang.IllegalStateException(); + } + + @Override + public boolean equals(java.lang.Object that) { + if (that == null) + return false; + if (that instanceof getList_result) + return this.equals((getList_result)that); + return false; + } + + public boolean equals(getList_result that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_success = true && this.isSetSuccess(); + boolean that_present_success = true && that.isSetSuccess(); + if (this_present_success || that_present_success) { + if (!(this_present_success && that_present_success)) + return false; + if (!this.success.equals(that.success)) + return false; + } + + boolean this_present_e = true && this.isSetE(); + boolean that_present_e = true && that.isSetE(); + if (this_present_e || that_present_e) { + if (!(this_present_e && that_present_e)) + return false; + if (!this.e.equals(that.e)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); + if (isSetSuccess()) + hashCode = hashCode * 8191 + success.hashCode(); + + hashCode = hashCode * 8191 + ((isSetE()) ? 131071 : 524287); + if (isSetE()) + hashCode = hashCode * 8191 + e.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(getList_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = java.lang.Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetSuccess()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); + if (lastComparison != 0) { + return lastComparison; + } + } + lastComparison = java.lang.Boolean.valueOf(isSetE()).compareTo(other.isSetE()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetE()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public java.lang.String toString() { + java.lang.StringBuilder sb = new java.lang.StringBuilder("getList_result("); + boolean first = true; + + sb.append("success:"); + if (this.success == null) { + sb.append("null"); + } else { + sb.append(this.success); + } + first = false; + if (!first) sb.append(", "); + sb.append("e:"); + if (this.e == null) { + sb.append("null"); + } else { + sb.append(this.e); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class getList_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public getList_resultStandardScheme getScheme() { + return new getList_resultStandardScheme(); + } + } + + private static class getList_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, getList_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 0: // SUCCESS + if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { + { + org.apache.thrift.protocol.TList _list0 = iprot.readListBegin(); + struct.success = new java.util.ArrayList(_list0.size); + CrossPlatformResource _elem1; + for (int _i2 = 0; _i2 < _list0.size; ++_i2) + { + _elem1 = new CrossPlatformResource(); + _elem1.read(iprot); + struct.success.add(_elem1); + } + iprot.readListEnd(); + } + struct.setSuccessIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + case 1: // E + if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { + struct.e = new InvalidOperationException(); + struct.e.read(iprot); + struct.setEIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, getList_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.success != null) { + oprot.writeFieldBegin(SUCCESS_FIELD_DESC); + { + oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.success.size())); + for (CrossPlatformResource _iter3 : struct.success) + { + _iter3.write(oprot); + } + oprot.writeListEnd(); + } + oprot.writeFieldEnd(); + } + if (struct.e != null) { + oprot.writeFieldBegin(E_FIELD_DESC); + struct.e.write(oprot); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class getList_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public getList_resultTupleScheme getScheme() { + return new getList_resultTupleScheme(); + } + } + + private static class getList_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, getList_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetSuccess()) { + optionals.set(0); + } + if (struct.isSetE()) { + optionals.set(1); + } + oprot.writeBitSet(optionals, 2); + if (struct.isSetSuccess()) { + { + oprot.writeI32(struct.success.size()); + for (CrossPlatformResource _iter4 : struct.success) + { + _iter4.write(oprot); + } + } + } + if (struct.isSetE()) { + struct.e.write(oprot); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, getList_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(2); + if (incoming.get(0)) { + { + org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); + struct.success = new java.util.ArrayList(_list5.size); + CrossPlatformResource _elem6; + for (int _i7 = 0; _i7 < _list5.size; ++_i7) + { + _elem6 = new CrossPlatformResource(); + _elem6.read(iprot); + struct.success.add(_elem6); + } + } + struct.setSuccessIsSet(true); + } + if (incoming.get(1)) { + struct.e = new InvalidOperationException(); + struct.e.read(iprot); + struct.setEIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class ping_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ping_args"); + + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new ping_argsStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new ping_argsTupleSchemeFactory(); + + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { +; + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(java.lang.String name) { + return byName.get(name); + } + + private final short _thriftId; + private final java.lang.String _fieldName; + + _Fields(short thriftId, java.lang.String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public java.lang.String getFieldName() { + return _fieldName; + } + } + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ping_args.class, metaDataMap); + } + + public ping_args() { + } + + /** + * Performs a deep copy on other. + */ + public ping_args(ping_args other) { + } + + public ping_args deepCopy() { + return new ping_args(this); + } + + @Override + public void clear() { + } + + public void setFieldValue(_Fields field, java.lang.Object value) { + switch (field) { + } + } + + public java.lang.Object getFieldValue(_Fields field) { + switch (field) { + } + throw new java.lang.IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new java.lang.IllegalArgumentException(); + } + + switch (field) { + } + throw new java.lang.IllegalStateException(); + } + + @Override + public boolean equals(java.lang.Object that) { + if (that == null) + return false; + if (that instanceof ping_args) + return this.equals((ping_args)that); + return false; + } + + public boolean equals(ping_args that) { + if (that == null) + return false; + if (this == that) + return true; + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + return hashCode; + } + + @Override + public int compareTo(ping_args other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public java.lang.String toString() { + java.lang.StringBuilder sb = new java.lang.StringBuilder("ping_args("); + boolean first = true; + + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { + try { + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class ping_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public ping_argsStandardScheme getScheme() { + return new ping_argsStandardScheme(); + } + } + + private static class ping_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, ping_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, ping_args struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class ping_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public ping_argsTupleScheme getScheme() { + return new ping_argsTupleScheme(); + } + } + + private static class ping_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, ping_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, ping_args struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + + public static class ping_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ping_result"); + + private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0); + private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new ping_resultStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new ping_resultTupleSchemeFactory(); + + public boolean success; // required + public InvalidOperationException e; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + SUCCESS((short)0, "success"), + E((short)1, "e"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 0: // SUCCESS + return SUCCESS; + case 1: // E + return E; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(java.lang.String name) { + return byName.get(name); + } + + private final short _thriftId; + private final java.lang.String _fieldName; + + _Fields(short thriftId, java.lang.String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public java.lang.String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + private static final int __SUCCESS_ISSET_ID = 0; + private byte __isset_bitfield = 0; + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); + tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, InvalidOperationException.class))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ping_result.class, metaDataMap); + } + + public ping_result() { + } + + public ping_result( + boolean success, + InvalidOperationException e) + { + this(); + this.success = success; + setSuccessIsSet(true); + this.e = e; + } + + /** + * Performs a deep copy on other. + */ + public ping_result(ping_result other) { + __isset_bitfield = other.__isset_bitfield; + this.success = other.success; + if (other.isSetE()) { + this.e = new InvalidOperationException(other.e); + } + } + + public ping_result deepCopy() { + return new ping_result(this); + } + + @Override + public void clear() { + setSuccessIsSet(false); + this.success = false; + this.e = null; + } + + public boolean isSuccess() { + return this.success; + } + + public ping_result setSuccess(boolean success) { + this.success = success; + setSuccessIsSet(true); + return this; + } + + public void unsetSuccess() { + __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID); + } + + /** Returns true if field success is set (has been assigned a value) and false otherwise */ + public boolean isSetSuccess() { + return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID); + } + + public void setSuccessIsSet(boolean value) { + __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value); + } + + public InvalidOperationException getE() { + return this.e; + } + + public ping_result setE(InvalidOperationException e) { + this.e = e; + return this; + } + + public void unsetE() { + this.e = null; + } + + /** Returns true if field e is set (has been assigned a value) and false otherwise */ + public boolean isSetE() { + return this.e != null; + } + + public void setEIsSet(boolean value) { + if (!value) { + this.e = null; + } + } + + public void setFieldValue(_Fields field, java.lang.Object value) { + switch (field) { + case SUCCESS: + if (value == null) { + unsetSuccess(); + } else { + setSuccess((java.lang.Boolean)value); + } + break; + + case E: + if (value == null) { + unsetE(); + } else { + setE((InvalidOperationException)value); + } + break; + + } + } + + public java.lang.Object getFieldValue(_Fields field) { + switch (field) { + case SUCCESS: + return isSuccess(); + + case E: + return getE(); + + } + throw new java.lang.IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new java.lang.IllegalArgumentException(); + } + + switch (field) { + case SUCCESS: + return isSetSuccess(); + case E: + return isSetE(); + } + throw new java.lang.IllegalStateException(); + } + + @Override + public boolean equals(java.lang.Object that) { + if (that == null) + return false; + if (that instanceof ping_result) + return this.equals((ping_result)that); + return false; + } + + public boolean equals(ping_result that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_success = true; + boolean that_present_success = true; + if (this_present_success || that_present_success) { + if (!(this_present_success && that_present_success)) + return false; + if (this.success != that.success) + return false; + } + + boolean this_present_e = true && this.isSetE(); + boolean that_present_e = true && that.isSetE(); + if (this_present_e || that_present_e) { + if (!(this_present_e && that_present_e)) + return false; + if (!this.e.equals(that.e)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + ((success) ? 131071 : 524287); + + hashCode = hashCode * 8191 + ((isSetE()) ? 131071 : 524287); + if (isSetE()) + hashCode = hashCode * 8191 + e.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(ping_result other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = java.lang.Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetSuccess()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); + if (lastComparison != 0) { + return lastComparison; + } + } + lastComparison = java.lang.Boolean.valueOf(isSetE()).compareTo(other.isSetE()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetE()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public java.lang.String toString() { + java.lang.StringBuilder sb = new java.lang.StringBuilder("ping_result("); + boolean first = true; + + sb.append("success:"); + sb.append(this.success); + first = false; + if (!first) sb.append(", "); + sb.append("e:"); + if (this.e == null) { + sb.append("null"); + } else { + sb.append(this.e); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { + try { + // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. + __isset_bitfield = 0; + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class ping_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public ping_resultStandardScheme getScheme() { + return new ping_resultStandardScheme(); + } + } + + private static class ping_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, ping_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 0: // SUCCESS + if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { + struct.success = iprot.readBool(); + struct.setSuccessIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + case 1: // E + if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { + struct.e = new InvalidOperationException(); + struct.e.read(iprot); + struct.setEIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, ping_result struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + if (struct.isSetSuccess()) { + oprot.writeFieldBegin(SUCCESS_FIELD_DESC); + oprot.writeBool(struct.success); + oprot.writeFieldEnd(); + } + if (struct.e != null) { + oprot.writeFieldBegin(E_FIELD_DESC); + struct.e.write(oprot); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class ping_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public ping_resultTupleScheme getScheme() { + return new ping_resultTupleScheme(); + } + } + + private static class ping_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, ping_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetSuccess()) { + optionals.set(0); + } + if (struct.isSetE()) { + optionals.set(1); + } + oprot.writeBitSet(optionals, 2); + if (struct.isSetSuccess()) { + oprot.writeBool(struct.success); + } + if (struct.isSetE()) { + struct.e.write(oprot); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, ping_result struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(2); + if (incoming.get(0)) { + struct.success = iprot.readBool(); + struct.setSuccessIsSet(true); + } + if (incoming.get(1)) { + struct.e = new InvalidOperationException(); + struct.e.read(iprot); + struct.setEIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } + } + +} diff --git a/apache-thrift/generated/com/baeldung/thrift/impl/InvalidOperationException.java b/apache-thrift/generated/com/baeldung/thrift/impl/InvalidOperationException.java new file mode 100644 index 0000000000..c07616a00e --- /dev/null +++ b/apache-thrift/generated/com/baeldung/thrift/impl/InvalidOperationException.java @@ -0,0 +1,472 @@ +/** + * Autogenerated by Thrift Compiler (0.10.0) + * + * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING + * @generated + */ +package com.baeldung.thrift.impl; + +@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) +@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01") +public class InvalidOperationException extends org.apache.thrift.TException implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { + private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InvalidOperationException"); + + private static final org.apache.thrift.protocol.TField CODE_FIELD_DESC = new org.apache.thrift.protocol.TField("code", org.apache.thrift.protocol.TType.I32, (short)1); + private static final org.apache.thrift.protocol.TField DESCRIPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("description", org.apache.thrift.protocol.TType.STRING, (short)2); + + private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new InvalidOperationExceptionStandardSchemeFactory(); + private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new InvalidOperationExceptionTupleSchemeFactory(); + + public int code; // required + public java.lang.String description; // required + + /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ + public enum _Fields implements org.apache.thrift.TFieldIdEnum { + CODE((short)1, "code"), + DESCRIPTION((short)2, "description"); + + private static final java.util.Map byName = new java.util.HashMap(); + + static { + for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { + byName.put(field.getFieldName(), field); + } + } + + /** + * Find the _Fields constant that matches fieldId, or null if its not found. + */ + public static _Fields findByThriftId(int fieldId) { + switch(fieldId) { + case 1: // CODE + return CODE; + case 2: // DESCRIPTION + return DESCRIPTION; + default: + return null; + } + } + + /** + * Find the _Fields constant that matches fieldId, throwing an exception + * if it is not found. + */ + public static _Fields findByThriftIdOrThrow(int fieldId) { + _Fields fields = findByThriftId(fieldId); + if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); + return fields; + } + + /** + * Find the _Fields constant that matches name, or null if its not found. + */ + public static _Fields findByName(java.lang.String name) { + return byName.get(name); + } + + private final short _thriftId; + private final java.lang.String _fieldName; + + _Fields(short thriftId, java.lang.String fieldName) { + _thriftId = thriftId; + _fieldName = fieldName; + } + + public short getThriftFieldId() { + return _thriftId; + } + + public java.lang.String getFieldName() { + return _fieldName; + } + } + + // isset id assignments + private static final int __CODE_ISSET_ID = 0; + private byte __isset_bitfield = 0; + public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; + static { + java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); + tmpMap.put(_Fields.CODE, new org.apache.thrift.meta_data.FieldMetaData("code", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); + tmpMap.put(_Fields.DESCRIPTION, new org.apache.thrift.meta_data.FieldMetaData("description", org.apache.thrift.TFieldRequirementType.DEFAULT, + new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); + metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); + org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(InvalidOperationException.class, metaDataMap); + } + + public InvalidOperationException() { + } + + public InvalidOperationException( + int code, + java.lang.String description) + { + this(); + this.code = code; + setCodeIsSet(true); + this.description = description; + } + + /** + * Performs a deep copy on other. + */ + public InvalidOperationException(InvalidOperationException other) { + __isset_bitfield = other.__isset_bitfield; + this.code = other.code; + if (other.isSetDescription()) { + this.description = other.description; + } + } + + public InvalidOperationException deepCopy() { + return new InvalidOperationException(this); + } + + @Override + public void clear() { + setCodeIsSet(false); + this.code = 0; + this.description = null; + } + + public int getCode() { + return this.code; + } + + public InvalidOperationException setCode(int code) { + this.code = code; + setCodeIsSet(true); + return this; + } + + public void unsetCode() { + __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __CODE_ISSET_ID); + } + + /** Returns true if field code is set (has been assigned a value) and false otherwise */ + public boolean isSetCode() { + return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __CODE_ISSET_ID); + } + + public void setCodeIsSet(boolean value) { + __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __CODE_ISSET_ID, value); + } + + public java.lang.String getDescription() { + return this.description; + } + + public InvalidOperationException setDescription(java.lang.String description) { + this.description = description; + return this; + } + + public void unsetDescription() { + this.description = null; + } + + /** Returns true if field description is set (has been assigned a value) and false otherwise */ + public boolean isSetDescription() { + return this.description != null; + } + + public void setDescriptionIsSet(boolean value) { + if (!value) { + this.description = null; + } + } + + public void setFieldValue(_Fields field, java.lang.Object value) { + switch (field) { + case CODE: + if (value == null) { + unsetCode(); + } else { + setCode((java.lang.Integer)value); + } + break; + + case DESCRIPTION: + if (value == null) { + unsetDescription(); + } else { + setDescription((java.lang.String)value); + } + break; + + } + } + + public java.lang.Object getFieldValue(_Fields field) { + switch (field) { + case CODE: + return getCode(); + + case DESCRIPTION: + return getDescription(); + + } + throw new java.lang.IllegalStateException(); + } + + /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ + public boolean isSet(_Fields field) { + if (field == null) { + throw new java.lang.IllegalArgumentException(); + } + + switch (field) { + case CODE: + return isSetCode(); + case DESCRIPTION: + return isSetDescription(); + } + throw new java.lang.IllegalStateException(); + } + + @Override + public boolean equals(java.lang.Object that) { + if (that == null) + return false; + if (that instanceof InvalidOperationException) + return this.equals((InvalidOperationException)that); + return false; + } + + public boolean equals(InvalidOperationException that) { + if (that == null) + return false; + if (this == that) + return true; + + boolean this_present_code = true; + boolean that_present_code = true; + if (this_present_code || that_present_code) { + if (!(this_present_code && that_present_code)) + return false; + if (this.code != that.code) + return false; + } + + boolean this_present_description = true && this.isSetDescription(); + boolean that_present_description = true && that.isSetDescription(); + if (this_present_description || that_present_description) { + if (!(this_present_description && that_present_description)) + return false; + if (!this.description.equals(that.description)) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hashCode = 1; + + hashCode = hashCode * 8191 + code; + + hashCode = hashCode * 8191 + ((isSetDescription()) ? 131071 : 524287); + if (isSetDescription()) + hashCode = hashCode * 8191 + description.hashCode(); + + return hashCode; + } + + @Override + public int compareTo(InvalidOperationException other) { + if (!getClass().equals(other.getClass())) { + return getClass().getName().compareTo(other.getClass().getName()); + } + + int lastComparison = 0; + + lastComparison = java.lang.Boolean.valueOf(isSetCode()).compareTo(other.isSetCode()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetCode()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.code, other.code); + if (lastComparison != 0) { + return lastComparison; + } + } + lastComparison = java.lang.Boolean.valueOf(isSetDescription()).compareTo(other.isSetDescription()); + if (lastComparison != 0) { + return lastComparison; + } + if (isSetDescription()) { + lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.description, other.description); + if (lastComparison != 0) { + return lastComparison; + } + } + return 0; + } + + public _Fields fieldForId(int fieldId) { + return _Fields.findByThriftId(fieldId); + } + + public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { + scheme(iprot).read(iprot, this); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { + scheme(oprot).write(oprot, this); + } + + @Override + public java.lang.String toString() { + java.lang.StringBuilder sb = new java.lang.StringBuilder("InvalidOperationException("); + boolean first = true; + + sb.append("code:"); + sb.append(this.code); + first = false; + if (!first) sb.append(", "); + sb.append("description:"); + if (this.description == null) { + sb.append("null"); + } else { + sb.append(this.description); + } + first = false; + sb.append(")"); + return sb.toString(); + } + + public void validate() throws org.apache.thrift.TException { + // check for required fields + // check for sub-struct validity + } + + private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { + try { + write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { + try { + // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. + __isset_bitfield = 0; + read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); + } catch (org.apache.thrift.TException te) { + throw new java.io.IOException(te); + } + } + + private static class InvalidOperationExceptionStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public InvalidOperationExceptionStandardScheme getScheme() { + return new InvalidOperationExceptionStandardScheme(); + } + } + + private static class InvalidOperationExceptionStandardScheme extends org.apache.thrift.scheme.StandardScheme { + + public void read(org.apache.thrift.protocol.TProtocol iprot, InvalidOperationException struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TField schemeField; + iprot.readStructBegin(); + while (true) + { + schemeField = iprot.readFieldBegin(); + if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { + break; + } + switch (schemeField.id) { + case 1: // CODE + if (schemeField.type == org.apache.thrift.protocol.TType.I32) { + struct.code = iprot.readI32(); + struct.setCodeIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + case 2: // DESCRIPTION + if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { + struct.description = iprot.readString(); + struct.setDescriptionIsSet(true); + } else { + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + break; + default: + org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); + } + iprot.readFieldEnd(); + } + iprot.readStructEnd(); + + // check for required fields of primitive type, which can't be checked in the validate method + struct.validate(); + } + + public void write(org.apache.thrift.protocol.TProtocol oprot, InvalidOperationException struct) throws org.apache.thrift.TException { + struct.validate(); + + oprot.writeStructBegin(STRUCT_DESC); + oprot.writeFieldBegin(CODE_FIELD_DESC); + oprot.writeI32(struct.code); + oprot.writeFieldEnd(); + if (struct.description != null) { + oprot.writeFieldBegin(DESCRIPTION_FIELD_DESC); + oprot.writeString(struct.description); + oprot.writeFieldEnd(); + } + oprot.writeFieldStop(); + oprot.writeStructEnd(); + } + + } + + private static class InvalidOperationExceptionTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { + public InvalidOperationExceptionTupleScheme getScheme() { + return new InvalidOperationExceptionTupleScheme(); + } + } + + private static class InvalidOperationExceptionTupleScheme extends org.apache.thrift.scheme.TupleScheme { + + @Override + public void write(org.apache.thrift.protocol.TProtocol prot, InvalidOperationException struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet optionals = new java.util.BitSet(); + if (struct.isSetCode()) { + optionals.set(0); + } + if (struct.isSetDescription()) { + optionals.set(1); + } + oprot.writeBitSet(optionals, 2); + if (struct.isSetCode()) { + oprot.writeI32(struct.code); + } + if (struct.isSetDescription()) { + oprot.writeString(struct.description); + } + } + + @Override + public void read(org.apache.thrift.protocol.TProtocol prot, InvalidOperationException struct) throws org.apache.thrift.TException { + org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; + java.util.BitSet incoming = iprot.readBitSet(2); + if (incoming.get(0)) { + struct.code = iprot.readI32(); + struct.setCodeIsSet(true); + } + if (incoming.get(1)) { + struct.description = iprot.readString(); + struct.setDescriptionIsSet(true); + } + } + } + + private static S scheme(org.apache.thrift.protocol.TProtocol proto) { + return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); + } +} + diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml new file mode 100644 index 0000000000..66cfb2bb41 --- /dev/null +++ b/apache-thrift/pom.xml @@ -0,0 +1,68 @@ + + 4.0.0 + com.baeldung + apache-thrift + 0.0.1-SNAPSHOT + pom + + + 1.8 + 4.12 + 3.6.0 + 0.10.0 + 0.1.11 + + + + + org.apache.thrift + libthrift + ${thrift.version} + + + + junit + junit + ${junit.version} + test + + + + org.slf4j + slf4j-simple + 1.7.12 + test + + + + + install + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + org.codehaus.mojo + build-helper-maven-plugin + + + generate-sources + add-source + + + generated + + + + + + + + diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/Application.java b/apache-thrift/src/main/java/com/baeldung/thrift/Application.java new file mode 100644 index 0000000000..3321a0927a --- /dev/null +++ b/apache-thrift/src/main/java/com/baeldung/thrift/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.thrift; + +import org.apache.thrift.transport.TTransportException; + +public class Application { + + public static void main(String[] args) throws TTransportException { + CrossPlatformServiceServer server = new CrossPlatformServiceServer(); + server.start(); + } +} diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceClient.java b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceClient.java new file mode 100644 index 0000000000..8c369acccb --- /dev/null +++ b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceClient.java @@ -0,0 +1,41 @@ +package com.baeldung.thrift; + +import com.baeldung.thrift.impl.CrossPlatformService; + +import org.apache.thrift.TException; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.transport.TSocket; +import org.apache.thrift.transport.TTransport; +import org.apache.thrift.transport.TTransportException; + +public class CrossPlatformServiceClient { + + public boolean ping() { + try { + TTransport transport; + + transport = new TSocket("localhost", 9090); + transport.open(); + + TProtocol protocol = new TBinaryProtocol(transport); + CrossPlatformService.Client client = new CrossPlatformService.Client(protocol); + + System.out.print("Calling remote method..."); + + boolean result = client.ping(); + + System.out.println("done."); + + transport.close(); + + return result; + } catch (TTransportException e) { + e.printStackTrace(); + } catch (TException x) { + x.printStackTrace(); + } + + return false; + } +} diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceImpl.java b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceImpl.java new file mode 100644 index 0000000000..008fc05ee7 --- /dev/null +++ b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceImpl.java @@ -0,0 +1,35 @@ +package com.baeldung.thrift; + +import com.baeldung.thrift.impl.CrossPlatformResource; +import com.baeldung.thrift.impl.CrossPlatformService; +import com.baeldung.thrift.impl.InvalidOperationException; + +import org.apache.thrift.TException; + +import java.util.Collections; +import java.util.List; + +public class CrossPlatformServiceImpl implements CrossPlatformService.Iface { + + @Override + public CrossPlatformResource get(final int id) throws InvalidOperationException, TException { + // add some action + return new CrossPlatformResource(); + } + + @Override + public void save(final CrossPlatformResource resource) throws InvalidOperationException, TException { + // add some action + } + + @Override + public List getList() throws InvalidOperationException, TException { + // add some action + return Collections.emptyList(); + } + + @Override + public boolean ping() throws InvalidOperationException, TException { + return true; + } +} diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java new file mode 100644 index 0000000000..32c7891ef2 --- /dev/null +++ b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java @@ -0,0 +1,36 @@ +package com.baeldung.thrift; + +import com.baeldung.thrift.impl.CrossPlatformService; + +import org.apache.thrift.server.TServer; +import org.apache.thrift.server.TSimpleServer; +import org.apache.thrift.transport.TServerSocket; +import org.apache.thrift.transport.TServerTransport; +import org.apache.thrift.transport.TTransportException; + +public class CrossPlatformServiceServer { + + private TServer server; + + public void start() throws TTransportException { + TServerTransport serverTransport = new TServerSocket(9090); + server = new TSimpleServer(new TServer.Args(serverTransport) + .processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl()))); + + System.out.print("Starting the server... "); + + server.serve(); + + System.out.println("done."); + } + + public void stop() { + if (server != null && server.isServing()) { + System.out.print("Stopping the server... "); + + server.stop(); + + System.out.println("done."); + } + } +} diff --git a/apache-thrift/src/main/resources/cross-platform-service.thrift b/apache-thrift/src/main/resources/cross-platform-service.thrift new file mode 100644 index 0000000000..d6d3c51e18 --- /dev/null +++ b/apache-thrift/src/main/resources/cross-platform-service.thrift @@ -0,0 +1,24 @@ +namespace cpp com.baeldung.thrift.impl +namespace java com.baeldung.thrift.impl + +exception InvalidOperationException { + 1: i32 code, + 2: string description +} + +struct CrossPlatformResource { + 1: i32 id, + 2: string name, + 3: optional string salutation +} + +service CrossPlatformService { + + CrossPlatformResource get(1:i32 id) throws (1:InvalidOperationException e), + + void save(1:CrossPlatformResource resource) throws (1:InvalidOperationException e), + + list getList() throws (1:InvalidOperationException e), + + bool ping() throws (1:InvalidOperationException e) +} \ No newline at end of file diff --git a/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java new file mode 100644 index 0000000000..4ba9ef2914 --- /dev/null +++ b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java @@ -0,0 +1,40 @@ +package com.baeldung.thrift; + +import org.apache.thrift.transport.TTransportException; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class CrossPlatformServiceTest { + + private CrossPlatformServiceServer server = new CrossPlatformServiceServer(); + + @Before + public void setUp() { + new Thread(() -> { + try { + server.start(); + } catch (TTransportException e) { + e.printStackTrace(); + } + }).start(); + try { + // wait for the server start up + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @After + public void tearDown() { + server.stop(); + } + + @Test + public void ping() { + CrossPlatformServiceClient client = new CrossPlatformServiceClient(); + Assert.assertTrue(client.ping()); + } +} 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/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java index fc134ece00..10bb011903 100644 --- a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java +++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java @@ -38,8 +38,7 @@ public class AssertJCoreTest { public void whenCheckingForElement_thenContains() throws Exception { List list = Arrays.asList("1", "2", "3"); - assertThat(list) - .contains("1"); + assertThat(list).contains("1"); } @Test @@ -50,12 +49,7 @@ public class AssertJCoreTest { assertThat(list).startsWith("1"); assertThat(list).doesNotContainNull(); - assertThat(list) - .isNotEmpty() - .contains("1") - .startsWith("1") - .doesNotContainNull() - .containsSequence("2", "3"); + assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3"); } @Test @@ -67,11 +61,7 @@ public class AssertJCoreTest { public void whenCheckingCharacter_thenIsUnicode() throws Exception { char someCharacter = 'c'; - assertThat(someCharacter) - .isNotEqualTo('a') - .inUnicode() - .isGreaterThanOrEqualTo('b') - .isLowerCase(); + assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase(); } @Test @@ -94,11 +84,7 @@ public class AssertJCoreTest { final File someFile = File.createTempFile("aaa", "bbb"); someFile.deleteOnExit(); - assertThat(someFile) - .exists() - .isFile() - .canRead() - .canWrite(); + assertThat(someFile).exists().isFile().canRead().canWrite(); } @Test @@ -113,20 +99,14 @@ public class AssertJCoreTest { public void whenGivenMap_then() throws Exception { Map map = Maps.newHashMap(2, "a"); - assertThat(map) - .isNotEmpty() - .containsKey(2) - .doesNotContainKeys(10) - .contains(entry(2, "a")); + assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a")); } @Test public void whenGivenException_then() throws Exception { Exception ex = new Exception("abc"); - assertThat(ex) - .hasNoCause() - .hasMessageEndingWith("c"); + assertThat(ex).hasNoCause().hasMessageEndingWith("c"); } @Ignore // IN ORDER TO TEST, REMOVE THIS LINE @@ -134,8 +114,6 @@ public class AssertJCoreTest { public void whenRunningAssertion_thenDescribed() throws Exception { Person person = new Person("Alex", 34); - assertThat(person.getAge()) - .as("%s's age should be equal to 100") - .isEqualTo(100); + assertThat(person.getAge()).as("%s's age should be equal to 100").isEqualTo(100); } } diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java index aee803ada1..84aaf46dd1 100644 --- a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java +++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java @@ -26,9 +26,7 @@ public class AssertJGuavaTest { final File temp1 = File.createTempFile("bael", "dung1"); final File temp2 = File.createTempFile("bael", "dung2"); - assertThat(Files.asByteSource(temp1)) - .hasSize(0) - .hasSameContentAs(Files.asByteSource(temp2)); + assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2)); } @Test @@ -37,11 +35,7 @@ public class AssertJGuavaTest { mmap.put(1, "one"); mmap.put(1, "1"); - assertThat(mmap) - .hasSize(2) - .containsKeys(1) - .contains(entry(1, "one")) - .contains(entry(1, "1")); + assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1")); } @Test @@ -62,31 +56,21 @@ public class AssertJGuavaTest { mmap2.put(1, "one"); mmap2.put(1, "1"); - assertThat(mmap1) - .containsAllEntriesOf(mmap2) - .containsAllEntriesOf(mmap1_clone) - .hasSameEntriesAs(mmap1_clone); + assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone); } @Test public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception { final Optional something = Optional.of("something"); - assertThat(something) - .isPresent() - .extractingValue() - .isEqualTo("something"); + assertThat(something).isPresent().extractingValue().isEqualTo("something"); } @Test public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception { final Range range = Range.openClosed("a", "g"); - assertThat(range) - .hasOpenedLowerBound() - .isNotEmpty() - .hasClosedUpperBound() - .contains("b"); + assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b"); } @Test @@ -96,10 +80,7 @@ public class AssertJGuavaTest { map.put(Range.closed(0, 60), "F"); map.put(Range.closed(61, 70), "D"); - assertThat(map) - .isNotEmpty() - .containsKeys(0) - .contains(MapEntry.entry(34, "F")); + assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F")); } @Test @@ -109,13 +90,7 @@ public class AssertJGuavaTest { table.put(1, "A", "PRESENT"); table.put(1, "B", "ABSENT"); - assertThat(table) - .hasRowCount(1) - .containsValues("ABSENT") - .containsCell(1, "B", "ABSENT"); + assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT"); } - - - } diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java index 0cdbd0f7ea..f89defaed1 100644 --- a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java +++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java @@ -20,20 +20,14 @@ public class AssertJJava8Test { public void givenOptional_shouldAssert() throws Exception { final Optional givenOptional = Optional.of("something"); - assertThat(givenOptional) - .isPresent() - .hasValue("something"); + assertThat(givenOptional).isPresent().hasValue("something"); } @Test public void givenPredicate_shouldAssert() throws Exception { final Predicate predicate = s -> s.length() > 4; - assertThat(predicate) - .accepts("aaaaa", "bbbbb") - .rejects("a", "b") - .acceptsAll(asList("aaaaa", "bbbbb")) - .rejectsAll(asList("a", "b")); + assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b")); } @Test @@ -41,92 +35,74 @@ public class AssertJJava8Test { final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8); final LocalDate todayDate = LocalDate.now(); - assertThat(givenLocalDate) - .isBefore(LocalDate.of(2020, 7, 8)) - .isAfterOrEqualTo(LocalDate.of(1989, 7, 8)); + assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8)); - assertThat(todayDate) - .isAfter(LocalDate.of(1989, 7, 8)) - .isToday(); + assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday(); } @Test public void givenLocalDateTime_shouldAssert() throws Exception { final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0); - assertThat(givenLocalDate) - .isBefore(LocalDateTime.of(2020, 7, 8, 11, 2)); + assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2)); } @Test public void givenLocalTime_shouldAssert() throws Exception { final LocalTime givenLocalTime = LocalTime.of(12, 15); - assertThat(givenLocalTime) - .isAfter(LocalTime.of(1, 0)) - .hasSameHourAs(LocalTime.of(12, 0)); + assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0)); } @Test public void givenList_shouldAssertFlatExtracting() throws Exception { final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); - assertThat(givenList) - .flatExtracting(LocalDate::getYear) - .contains(2015); + assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015); } @Test public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception { final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); - assertThat(givenList) - .flatExtracting(LocalDate::isLeapYear) - .contains(true); + assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true); } @Test public void givenList_shouldAssertFlatExtractingClass() throws Exception { final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); - assertThat(givenList) - .flatExtracting(Object::getClass) - .contains(LocalDate.class); + assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class); } @Test public void givenList_shouldAssertMultipleFlatExtracting() throws Exception { final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); - assertThat(givenList) - .flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth) - .contains(2015, 6); + assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6); } @Test public void givenString_shouldSatisfy() throws Exception { final String givenString = "someString"; - assertThat(givenString) - .satisfies(s -> { - assertThat(s).isNotEmpty(); - assertThat(s).hasSize(10); - }); + assertThat(givenString).satisfies(s -> { + assertThat(s).isNotEmpty(); + assertThat(s).hasSize(10); + }); } @Test public void givenString_shouldMatch() throws Exception { final String emptyString = ""; - assertThat(emptyString) - .matches(String::isEmpty); + assertThat(emptyString).matches(String::isEmpty); } @Test public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception { final List givenList = Arrays.asList(""); - assertThat(givenList) - .hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty()); + assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty()); } } 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/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java index ef39f499d1..5da6b48c81 100644 --- a/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java +++ b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java @@ -4,12 +4,12 @@ import com.google.auto.value.AutoValue; @AutoValue public abstract class AutoValueMoney { - public abstract String getCurrency(); + public abstract String getCurrency(); - public abstract long getAmount(); + public abstract long getAmount(); - public static AutoValueMoney create(String currency, long amount) { - return new AutoValue_AutoValueMoney(currency, amount); + public static AutoValueMoney create(String currency, long amount) { + return new AutoValue_AutoValueMoney(currency, amount); - } + } } diff --git a/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java index a7ac93e45b..8a4dbcd5a5 100644 --- a/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java +++ b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java @@ -4,20 +4,20 @@ import com.google.auto.value.AutoValue; @AutoValue public abstract class AutoValueMoneyWithBuilder { - public abstract String getCurrency(); + public abstract String getCurrency(); - public abstract long getAmount(); + public abstract long getAmount(); - static Builder builder() { - return new AutoValue_AutoValueMoneyWithBuilder.Builder(); - } + static Builder builder() { + return new AutoValue_AutoValueMoneyWithBuilder.Builder(); + } - @AutoValue.Builder - abstract static class Builder { - abstract Builder setCurrency(String currency); + @AutoValue.Builder + abstract static class Builder { + abstract Builder setCurrency(String currency); - abstract Builder setAmount(long amount); + abstract Builder setAmount(long amount); - abstract AutoValueMoneyWithBuilder build(); - } + abstract AutoValueMoneyWithBuilder build(); + } } diff --git a/autovalue/src/main/java/com/baeldung/autovalue/Foo.java b/autovalue/src/main/java/com/baeldung/autovalue/Foo.java index bb90070f6d..7bc893b044 100644 --- a/autovalue/src/main/java/com/baeldung/autovalue/Foo.java +++ b/autovalue/src/main/java/com/baeldung/autovalue/Foo.java @@ -3,49 +3,49 @@ package com.baeldung.autovalue; import java.util.Objects; public final class Foo { - private final String text; - private final int number; + private final String text; + private final int number; - public Foo(String text, int number) { - this.text = text; - this.number = number; - } + public Foo(String text, int number) { + this.text = text; + this.number = number; + } - public String getText() { - return text; - } + public String getText() { + return text; + } - public int getNumber() { - return number; - } + public int getNumber() { + return number; + } - @Override - public int hashCode() { - return Objects.hash(text, number); - } + @Override + public int hashCode() { + return Objects.hash(text, number); + } - @Override - public String toString() { - return "Foo [text=" + text + ", number=" + number + "]"; - } + @Override + public String toString() { + return "Foo [text=" + text + ", number=" + number + "]"; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Foo other = (Foo) obj; - if (number != other.number) - return false; - if (text == null) { - if (other.text != null) - return false; - } else if (!text.equals(other.text)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Foo other = (Foo) obj; + if (number != other.number) + return false; + if (text == null) { + if (other.text != null) + return false; + } else if (!text.equals(other.text)) + return false; + return true; + } } diff --git a/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java index 04d29b6b09..d715f2047c 100644 --- a/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java +++ b/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java @@ -1,52 +1,53 @@ package com.baeldung.autovalue; + public final class ImmutableMoney { - private final long amount; - private final String currency; - public ImmutableMoney(long amount, String currency) { - this.amount = amount; - this.currency = currency; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (int) (amount ^ (amount >>> 32)); - result = prime * result - + ((currency == null) ? 0 : currency.hashCode()); - return result; - } + private final long amount; + private final String currency; - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ImmutableMoney other = (ImmutableMoney) obj; - if (amount != other.amount) - return false; - if (currency == null) { - if (other.currency != null) - return false; - } else if (!currency.equals(other.currency)) - return false; - return true; - } + public ImmutableMoney(long amount, String currency) { + this.amount = amount; + this.currency = currency; + } - public long getAmount() { - return amount; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) (amount ^ (amount >>> 32)); + result = prime * result + ((currency == null) ? 0 : currency.hashCode()); + return result; + } - public String getCurrency() { - return currency; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ImmutableMoney other = (ImmutableMoney) obj; + if (amount != other.amount) + return false; + if (currency == null) { + if (other.currency != null) + return false; + } else if (!currency.equals(other.currency)) + return false; + return true; + } - @Override - public String toString() { - return "ImmutableMoney [amount=" + amount + ", currency=" + currency - + "]"; - } + public long getAmount() { + return amount; + } + + public String getCurrency() { + return currency; + } + + @Override + public String toString() { + return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]"; + } } diff --git a/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java index 6cf8b75f7d..d04a330a56 100644 --- a/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java +++ b/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java @@ -1,35 +1,34 @@ package com.baeldung.autovalue; public class MutableMoney { - @Override - public String toString() { - return "MutableMoney [amount=" + amount + ", currency=" + currency - + "]"; - } + @Override + public String toString() { + return "MutableMoney [amount=" + amount + ", currency=" + currency + "]"; + } - public long getAmount() { - return amount; - } + public long getAmount() { + return amount; + } - public void setAmount(long amount) { - this.amount = amount; - } + public void setAmount(long amount) { + this.amount = amount; + } - public String getCurrency() { - return currency; - } + public String getCurrency() { + return currency; + } - public void setCurrency(String currency) { - this.currency = currency; - } + public void setCurrency(String currency) { + this.currency = currency; + } - private long amount; - private String currency; + private long amount; + private String currency; - public MutableMoney(long amount, String currency) { - super(); - this.amount = amount; - this.currency = currency; - } + public MutableMoney(long amount, String currency) { + super(); + this.amount = amount; + this.currency = currency; + } } diff --git a/autovalue/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java b/autovalue/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java index a9482125a6..f0dffa43a7 100644 --- a/autovalue/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java +++ b/autovalue/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java @@ -5,55 +5,59 @@ import static org.junit.Assert.*; import org.junit.Test; public class MoneyUnitTest { - @Test - public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() { - MutableMoney m1 = new MutableMoney(10000, "USD"); - MutableMoney m2 = new MutableMoney(10000, "USD"); - assertFalse(m1.equals(m2)); - } + @Test + public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() { + MutableMoney m1 = new MutableMoney(10000, "USD"); + MutableMoney m2 = new MutableMoney(10000, "USD"); + assertFalse(m1.equals(m2)); + } - @Test - public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() { - ImmutableMoney m1 = new ImmutableMoney(10000, "USD"); - ImmutableMoney m2 = new ImmutableMoney(10000, "USD"); - assertTrue(m1.equals(m2)); - } + @Test + public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() { + ImmutableMoney m1 = new ImmutableMoney(10000, "USD"); + ImmutableMoney m2 = new ImmutableMoney(10000, "USD"); + assertTrue(m1.equals(m2)); + } - @Test - public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() { - AutoValueMoney m = AutoValueMoney.create("USD", 10000); - assertEquals(m.getAmount(), 10000); - assertEquals(m.getCurrency(), "USD"); - } + @Test + public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() { + AutoValueMoney m = AutoValueMoney.create("USD", 10000); + assertEquals(m.getAmount(), 10000); + assertEquals(m.getCurrency(), "USD"); + } - @Test - public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() { - AutoValueMoney m1 = AutoValueMoney.create("USD", 5000); - AutoValueMoney m2 = AutoValueMoney.create("USD", 5000); - assertTrue(m1.equals(m2)); - } - @Test - public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() { - AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000); - AutoValueMoney m2 = AutoValueMoney.create("USD", 5000); - assertFalse(m1.equals(m2)); - } - @Test - public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() { - AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); - AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); - assertTrue(m1.equals(m2)); - } - @Test - public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() { - AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); - AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build(); - assertFalse(m1.equals(m2)); - } - @Test - public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() { - AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); - assertEquals(m.getAmount(), 5000); - assertEquals(m.getCurrency(), "USD"); - } + @Test + public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() { + AutoValueMoney m1 = AutoValueMoney.create("USD", 5000); + AutoValueMoney m2 = AutoValueMoney.create("USD", 5000); + assertTrue(m1.equals(m2)); + } + + @Test + public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() { + AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000); + AutoValueMoney m2 = AutoValueMoney.create("USD", 5000); + assertFalse(m1.equals(m2)); + } + + @Test + public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() { + AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); + AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); + assertTrue(m1.equals(m2)); + } + + @Test + public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() { + AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); + AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build(); + assertFalse(m1.equals(m2)); + } + + @Test + public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() { + AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); + assertEquals(m.getAmount(), 5000); + assertEquals(m.getCurrency(), "USD"); + } } 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/pom.xml b/aws/pom.xml new file mode 100644 index 0000000000..f3ae672a2f --- /dev/null +++ b/aws/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + com.baeldung + aws + 0.1.0-SNAPSHOT + jar + aws + + + + com.amazonaws + aws-lambda-java-core + 1.1.0 + + + + commons-io + commons-io + 2.5 + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.3 + + false + + + + package + + shade + + + + + + + \ No newline at end of file diff --git a/aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java b/aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java new file mode 100644 index 0000000000..dc21476290 --- /dev/null +++ b/aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java @@ -0,0 +1,10 @@ +package com.baeldung.lambda; + +import com.amazonaws.services.lambda.runtime.Context; + +public class LambdaMethodHandler { + public String handleRequest(String input, Context context) { + context.getLogger().log("Input: " + input); + return "Hello World - " + input; + } +} diff --git a/aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java b/aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java new file mode 100644 index 0000000000..85385555d2 --- /dev/null +++ b/aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java @@ -0,0 +1,11 @@ +package com.baeldung.lambda; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; + +public class LambdaRequestHandler implements RequestHandler { + public String handleRequest(String input, Context context) { + context.getLogger().log("Input: " + input); + return "Hello World - " + input; + } +} diff --git a/aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java b/aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java new file mode 100644 index 0000000000..6e8a33c42d --- /dev/null +++ b/aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java @@ -0,0 +1,17 @@ +package com.baeldung.lambda; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestStreamHandler; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +public class LambdaRequestStreamHandler implements RequestStreamHandler { + + public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { + String input = IOUtils.toString(inputStream, "UTF-8"); + outputStream.write(("Hello World - " + input).getBytes()); + } +} 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..9d1ff29ef7 100644 --- a/core-java-9/pom.xml +++ b/core-java-9/pom.xml @@ -1,91 +1,90 @@ - - 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 + + - + + 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} - + - + + + UTF-8 + + + 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-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java index fd6a496b18..f7b2fad891 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java +++ b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java @@ -1,16 +1,16 @@ package com.baeldung.java9.language; public interface PrivateInterface { - + private static String staticPrivate() { return "static private"; } - + private String instancePrivate() { return "instance private"; } - - public default void check(){ + + public default void check() { String result = staticPrivate(); if (!result.equals("static private")) throw new AssertionError("Incorrect result for static private interface method"); diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java index d6682bd0c8..5cd2567fb3 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java @@ -8,37 +8,36 @@ import java.time.Duration; import java.time.Instant; import java.util.stream.Stream; - public class ProcessUtils { - public static String getClassPath(){ + public static String getClassPath() { String cp = System.getProperty("java.class.path"); - System.out.println("ClassPath is "+cp); + System.out.println("ClassPath is " + cp); return cp; } - public static File getJavaCmd() throws IOException{ + public static File getJavaCmd() throws IOException { String javaHome = System.getProperty("java.home"); File javaCmd; - if(System.getProperty("os.name").startsWith("Win")){ + if (System.getProperty("os.name").startsWith("Win")) { javaCmd = new File(javaHome, "bin/java.exe"); - }else{ + } else { javaCmd = new File(javaHome, "bin/java"); } - if(javaCmd.canExecute()){ + if (javaCmd.canExecute()) { return javaCmd; - }else{ + } else { throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable"); } } - public static String getMainClass(){ + public static String getMainClass() { return System.getProperty("sun.java.command"); } - public static String getSystemProperties(){ - StringBuilder sb = new StringBuilder(); - System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) ); + public static String getSystemProperties() { + StringBuilder sb = new StringBuilder(); + System.getProperties().forEach((s1, s2) -> sb.append(s1 + " - " + s2)); return sb.toString(); } } diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java index 458f746496..299f74e877 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java @@ -8,7 +8,6 @@ public class ServiceMain { ProcessHandle thisProcess = ProcessHandle.current(); long pid = thisProcess.getPid(); - Optional opArgs = Optional.ofNullable(args); String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command")); diff --git a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java index b0684a94f8..121c17a860 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java @@ -19,10 +19,7 @@ public class Java9OptionalsStreamTest { public void filterOutPresentOptionalsWithFilter() { assertEquals(4, listOfOptionals.size()); - List filteredList = listOfOptionals.stream() - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList()); + List filteredList = listOfOptionals.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()); assertEquals(2, filteredList.size()); assertEquals("foo", filteredList.get(0)); @@ -33,9 +30,7 @@ public class Java9OptionalsStreamTest { public void filterOutPresentOptionalsWithFlatMap() { assertEquals(4, listOfOptionals.size()); - List filteredList = listOfOptionals.stream() - .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) - .collect(Collectors.toList()); + List filteredList = listOfOptionals.stream().flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList()); assertEquals(2, filteredList.size()); assertEquals("foo", filteredList.get(0)); @@ -46,9 +41,7 @@ public class Java9OptionalsStreamTest { public void filterOutPresentOptionalsWithFlatMap2() { assertEquals(4, listOfOptionals.size()); - List filteredList = listOfOptionals.stream() - .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) - .collect(Collectors.toList()); + List filteredList = listOfOptionals.stream().flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList()); assertEquals(2, filteredList.size()); assertEquals("foo", filteredList.get(0)); @@ -59,9 +52,7 @@ public class Java9OptionalsStreamTest { public void filterOutPresentOptionalsWithJava9() { assertEquals(4, listOfOptionals.size()); - List filteredList = listOfOptionals.stream() - .flatMap(Optional::stream) - .collect(Collectors.toList()); + List filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList()); assertEquals(2, filteredList.size()); assertEquals("foo", filteredList.get(0)); diff --git a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java index a00646e4db..c0a5042b58 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java @@ -1,5 +1,5 @@ package com.baeldung.java9; - + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -13,7 +13,6 @@ import org.junit.Test; public class MultiResultionImageTest { - @Test public void baseMultiResImageTest() { int baseIndex = 1; @@ -38,10 +37,8 @@ public class MultiResultionImageTest { return 8 * (i + 1); } - private static BufferedImage createImage(int i) { - return new BufferedImage(getSize(i), getSize(i), - BufferedImage.TYPE_INT_RGB); + return new BufferedImage(getSize(i), getSize(i), BufferedImage.TYPE_INT_RGB); } } diff --git a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java index ab28b0a805..442a18cbf3 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java @@ -1,6 +1,4 @@ -package com.baeldung.java9.httpclient; - - +package com.baeldung.java9.httpclient; import static java.net.HttpURLConnection.HTTP_OK; import static org.junit.Assert.assertTrue; @@ -28,8 +26,8 @@ import org.junit.Test; public class SimpleHttpRequestsTest { - private URI httpURI; - + private URI httpURI; + @Before public void init() throws URISyntaxException { httpURI = new URI("http://www.baeldung.com/"); @@ -37,26 +35,26 @@ public class SimpleHttpRequestsTest { @Test public void quickGet() throws IOException, InterruptedException, URISyntaxException { - HttpRequest request = HttpRequest.create( httpURI ).GET(); + HttpRequest request = HttpRequest.create(httpURI).GET(); HttpResponse response = request.response(); int responseStatusCode = response.statusCode(); String responseBody = response.body(HttpResponse.asString()); - assertTrue("Get response status code is bigger then 400", responseStatusCode < 400); + assertTrue("Get response status code is bigger then 400", responseStatusCode < 400); } - + @Test - public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{ + public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException { HttpRequest request = HttpRequest.create(httpURI).GET(); long before = System.currentTimeMillis(); CompletableFuture futureResponse = request.responseAsync(); - futureResponse.thenAccept( response -> { + futureResponse.thenAccept(response -> { String responseBody = response.body(HttpResponse.asString()); - }); + }); HttpResponse resp = futureResponse.get(); HttpHeaders hs = resp.headers(); - assertTrue("There should be more then 1 header.", hs.map().size() >1); + assertTrue("There should be more then 1 header.", hs.map().size() > 1); } - + @Test public void postMehtod() throws URISyntaxException, IOException, InterruptedException { HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI); @@ -66,61 +64,63 @@ public class SimpleHttpRequestsTest { int statusCode = response.statusCode(); assertTrue("HTTP return code", statusCode == HTTP_OK); } - + @Test - public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{ + public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException { CookieManager cManager = new CookieManager(); cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); - - SSLParameters sslParam = new SSLParameters (new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" }); - + + SSLParameters sslParam = new SSLParameters(new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" }); + HttpClient.Builder hcBuilder = HttpClient.create(); hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam); HttpClient httpClient = hcBuilder.build(); HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com")); - + HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET(); HttpResponse response = request.response(); int statusCode = response.statusCode(); assertTrue("HTTP return code", statusCode == HTTP_OK); } - - SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{ + + SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException { SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters(); - String [] proto = sslP1.getApplicationProtocols(); - String [] cifers = sslP1.getCipherSuites(); + String[] proto = sslP1.getApplicationProtocols(); + String[] cifers = sslP1.getCipherSuites(); System.out.println(printStringArr(proto)); System.out.println(printStringArr(cifers)); return sslP1; } - - String printStringArr(String ... args ){ - if(args == null){ + + String printStringArr(String... args) { + if (args == null) { return null; } StringBuilder sb = new StringBuilder(); - for (String s : args){ + for (String s : args) { sb.append(s); sb.append("\n"); } return sb.toString(); } - - String printHeaders(HttpHeaders h){ - if(h == null){ + + String printHeaders(HttpHeaders h) { + if (h == null) { return null; } - - StringBuilder sb = new StringBuilder(); - Map> hMap = h.map(); - for(String k : hMap.keySet()){ - sb.append(k).append(":"); - List l = hMap.get(k); - if( l != null ){ - l.forEach( s -> { sb.append(s).append(","); } ); - } - sb.append("\n"); - } - return sb.toString(); + + StringBuilder sb = new StringBuilder(); + Map> hMap = h.map(); + for (String k : hMap.keySet()) { + sb.append(k).append(":"); + List l = hMap.get(k); + if (l != null) { + l.forEach(s -> { + sb.append(s).append(","); + }); + } + sb.append("\n"); + } + return sb.toString(); } } diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java index 687dfbc390..6bec3125cc 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java @@ -7,7 +7,7 @@ public class TryWithResourcesTest { static int closeCount = 0; - static class MyAutoCloseable implements AutoCloseable{ + static class MyAutoCloseable implements AutoCloseable { final FinalWrapper finalWrapper = new FinalWrapper(); public void close() { @@ -57,7 +57,6 @@ public class TryWithResourcesTest { assertEquals("Expected and Actual does not match", 5, closeCount); } - static class CloseableException extends Exception implements AutoCloseable { @Override public void close() { @@ -66,5 +65,3 @@ public class TryWithResourcesTest { } } - - diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/collections/ListFactoryMethodsTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/collections/ListFactoryMethodsTest.java new file mode 100644 index 0000000000..8e19d00b6a --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/collections/ListFactoryMethodsTest.java @@ -0,0 +1,61 @@ +package com.baeldung.java9.language.collections; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class ListFactoryMethodsTest { + + @Test + public void whenListCreated_thenSuccess() { + List traditionlList = new ArrayList(); + traditionlList.add("foo"); + traditionlList.add("bar"); + traditionlList.add("baz"); + List factoryCreatedList = List.of("foo", "bar", "baz"); + assertEquals(traditionlList, factoryCreatedList); + } + + @Test(expected = UnsupportedOperationException.class) + public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() { + List list = List.of("foo", "bar"); + list.add("baz"); + } + + @Test(expected = UnsupportedOperationException.class) + public void onElemModify_ifUnSupportedOpExpnThrown_thenSuccess() { + List list = List.of("foo", "bar"); + list.set(0, "baz"); + } + + @Test(expected = UnsupportedOperationException.class) + public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() { + List list = List.of("foo", "bar"); + list.remove("foo"); + } + + @Test(expected = NullPointerException.class) + public void onNullElem_ifNullPtrExpnThrown_thenSuccess() { + List.of("foo", "bar", null); + } + + @Test + public void ifNotArrayList_thenSuccess() { + List list = List.of("foo", "bar"); + assertFalse(list instanceof ArrayList); + } + + @Test + public void ifListSizeIsOne_thenSuccess() { + int[] arr = { 1, 2, 3, 4 }; + List list = List.of(arr); + assertEquals(1, list.size()); + assertArrayEquals(arr, list.get(0)); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/collections/MapFactoryMethodsTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/collections/MapFactoryMethodsTest.java new file mode 100644 index 0000000000..13469ff93d --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/collections/MapFactoryMethodsTest.java @@ -0,0 +1,62 @@ +package com.baeldung.java9.language.collections; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class MapFactoryMethodsTest { + + @Test + public void whenMapCreated_thenSuccess() { + Map traditionlMap = new HashMap(); + traditionlMap.put("foo", "a"); + traditionlMap.put("bar", "b"); + traditionlMap.put("baz", "c"); + Map factoryCreatedMap = Map.of("foo", "a", "bar", "b", "baz", "c"); + assertEquals(traditionlMap, factoryCreatedMap); + } + + @Test(expected = UnsupportedOperationException.class) + public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() { + Map map = Map.of("foo", "a", "bar", "b"); + map.put("baz", "c"); + } + + @Test(expected = UnsupportedOperationException.class) + public void onElemModify_ifUnSupportedOpExpnThrown_thenSuccess() { + Map map = Map.of("foo", "a", "bar", "b"); + map.put("foo", "c"); + } + + @Test(expected = UnsupportedOperationException.class) + public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() { + Map map = Map.of("foo", "a", "bar", "b"); + map.remove("foo"); + } + + @Test(expected = IllegalArgumentException.class) + public void givenDuplicateKeys_ifIllegalArgExp_thenSuccess() { + Map.of("foo", "a", "foo", "b"); + } + + @Test(expected = NullPointerException.class) + public void onNullKey_ifNullPtrExp_thenSuccess() { + Map.of("foo", "a", null, "b"); + } + + @Test(expected = NullPointerException.class) + public void onNullValue_ifNullPtrExp_thenSuccess() { + Map.of("foo", "a", "bar", null); + } + + @Test + public void ifNotHashMap_thenSuccess() { + Map map = Map.of("foo", "a", "bar", "b"); + assertFalse(map instanceof HashMap); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/collections/SetFactoryMethodsTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/collections/SetFactoryMethodsTest.java new file mode 100644 index 0000000000..b8537d7c82 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/collections/SetFactoryMethodsTest.java @@ -0,0 +1,60 @@ +package com.baeldung.java9.language.collections; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class SetFactoryMethodsTest { + + @Test + public void whenSetCreated_thenSuccess() { + Set traditionlSet = new HashSet(); + traditionlSet.add("foo"); + traditionlSet.add("bar"); + traditionlSet.add("baz"); + Set factoryCreatedSet = Set.of("foo", "bar", "baz"); + assertEquals(traditionlSet, factoryCreatedSet); + } + + @Test(expected = IllegalArgumentException.class) + public void onDuplicateElem_IfIllegalArgExp_thenSuccess() { + Set.of("foo", "bar", "baz", "foo"); + } + + @Test(expected = UnsupportedOperationException.class) + public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() { + Set set = Set.of("foo", "bar"); + set.add("baz"); + } + + @Test(expected = UnsupportedOperationException.class) + public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() { + Set set = Set.of("foo", "bar", "baz"); + set.remove("foo"); + } + + @Test(expected = NullPointerException.class) + public void onNullElem_ifNullPtrExpnThrown_thenSuccess() { + Set.of("foo", "bar", null); + } + + @Test + public void ifNotHashSet_thenSuccess() { + Set list = Set.of("foo", "bar"); + assertFalse(list instanceof HashSet); + } + + @Test + public void ifSetSizeIsOne_thenSuccess() { + int[] arr = { 1, 2, 3, 4 }; + Set set = Set.of(arr); + assertEquals(1, set.size()); + assertArrayEquals(arr, set.iterator().next()); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementTest.java new file mode 100644 index 0000000000..ea76a76a5f --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementTest.java @@ -0,0 +1,61 @@ +package com.baeldung.java9.language.stream; + +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.function.Function; + +import static org.junit.Assert.assertEquals; + +public class CollectorImprovementTest { + @Test + public void givenList_whenSatifyPredicate_thenMapValueWithOccurences() { + List numbers = List.of(1, 2, 3, 5, 5); + + Map result = numbers.stream().filter(val -> val > 3).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + + assertEquals(1, result.size()); + + result = numbers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.filtering(val -> val > 3, Collectors.counting()))); + + assertEquals(4, result.size()); + } + + @Test + public void givenListOfBlogs_whenAuthorName_thenMapAuthorWithComments() { + Blog blog1 = new Blog("1", "Nice", "Very Nice"); + Blog blog2 = new Blog("2", "Disappointing", "Ok", "Could be better"); + List blogs = List.of(blog1, blog2); + + Map>> authorComments1 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.mapping(Blog::getComments, Collectors.toList()))); + + assertEquals(2, authorComments1.size()); + assertEquals(2, authorComments1.get("1").get(0).size()); + assertEquals(3, authorComments1.get("2").get(0).size()); + + Map> authorComments2 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.flatMapping(blog -> blog.getComments().stream(), Collectors.toList()))); + + assertEquals(2, authorComments2.size()); + assertEquals(2, authorComments2.get("1").size()); + assertEquals(3, authorComments2.get("2").size()); + } +} + +class Blog { + private String authorName; + private List comments; + + public Blog(String authorName, String... comments) { + this.authorName = authorName; + this.comments = List.of(comments); + } + + public String getAuthorName() { + return this.authorName; + } + + public List getComments() { + return this.comments; + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java index a260e84164..72d17498a9 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java @@ -17,16 +17,11 @@ public class StreamFeaturesTest { public static class TakeAndDropWhileTest { public Stream getStreamAfterTakeWhileOperation() { - return Stream - .iterate("", s -> s + "s") - .takeWhile(s -> s.length() < 10); + return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10); } public Stream getStreamAfterDropWhileOperation() { - return Stream - .iterate("", s -> s + "s") - .takeWhile(s -> s.length() < 10) - .dropWhile(s -> !s.contains("sssss")); + return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10).dropWhile(s -> !s.contains("sssss")); } @Test @@ -72,25 +67,25 @@ public class StreamFeaturesTest { } - public static class OfNullableTest { + public static class OfNullableTest { private List collection = Arrays.asList("A", "B", "C"); - private Map map = new HashMap<>() {{ - put("A", 10); - put("C", 30); - }}; + private Map map = new HashMap<>() { + { + put("A", 10); + put("C", 30); + } + }; private Stream getStreamWithOfNullable() { - return collection.stream() - .flatMap(s -> Stream.ofNullable(map.get(s))); + return collection.stream().flatMap(s -> Stream.ofNullable(map.get(s))); } private Stream getStream() { - return collection.stream() - .flatMap(s -> { - Integer temp = map.get(s); - return temp != null ? Stream.of(temp) : Stream.empty(); - }); + return collection.stream().flatMap(s -> { + Integer temp = map.get(s); + return temp != null ? Stream.of(temp) : Stream.empty(); + }); } private List testOfNullableFrom(Stream stream) { @@ -107,10 +102,7 @@ public class StreamFeaturesTest { @Test public void testOfNullable() { - assertEquals( - testOfNullableFrom(getStream()), - testOfNullableFrom(getStreamWithOfNullable()) - ); + assertEquals(testOfNullableFrom(getStream()), testOfNullableFrom(getStreamWithOfNullable())); } diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java index 419516cb64..9c9951bc54 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java +++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java @@ -22,90 +22,89 @@ import static org.junit.Assert.assertTrue; public class ProcessApi { - @Before public void init() { } @Test - public void processInfoExample()throws NoSuchAlgorithmException{ + public void processInfoExample() throws NoSuchAlgorithmException { ProcessHandle self = ProcessHandle.current(); long PID = self.getPid(); ProcessHandle.Info procInfo = self.info(); Optional args = procInfo.arguments(); - Optional cmd = procInfo.commandLine(); + Optional cmd = procInfo.commandLine(); Optional startTime = procInfo.startInstant(); Optional cpuUsage = procInfo.totalCpuDuration(); waistCPU(); - System.out.println("Args "+ args); - System.out.println("Command " +cmd.orElse("EmptyCmd")); - System.out.println("Start time: "+ startTime.get().toString()); + System.out.println("Args " + args); + System.out.println("Command " + cmd.orElse("EmptyCmd")); + System.out.println("Start time: " + startTime.get().toString()); System.out.println(cpuUsage.get().toMillis()); - + Stream allProc = ProcessHandle.current().children(); allProc.forEach(p -> { - System.out.println("Proc "+ p.getPid()); + System.out.println("Proc " + p.getPid()); }); } @Test - public void createAndDestroyProcess() throws IOException, InterruptedException{ + public void createAndDestroyProcess() throws IOException, InterruptedException { int numberOfChildProcesses = 5; - for(int i=0; i < numberOfChildProcesses; i++){ + for (int i = 0; i < numberOfChildProcesses; i++) { createNewJVM(ServiceMain.class, i).getPid(); } - - Stream childProc = ProcessHandle.current().children(); - assertEquals( childProc.count(), numberOfChildProcesses); - + + Stream childProc = ProcessHandle.current().children(); + assertEquals(childProc.count(), numberOfChildProcesses); + childProc = ProcessHandle.current().children(); childProc.forEach(processHandle -> { - assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive()); + assertTrue("Process " + processHandle.getPid() + " should be alive!", processHandle.isAlive()); CompletableFuture onProcExit = processHandle.onExit(); onProcExit.thenAccept(procHandle -> { - System.out.println("Process with PID "+ procHandle.getPid() + " has stopped"); + System.out.println("Process with PID " + procHandle.getPid() + " has stopped"); }); }); - + Thread.sleep(10000); - + childProc = ProcessHandle.current().children(); childProc.forEach(procHandle -> { - assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy()); + assertTrue("Could not kill process " + procHandle.getPid(), procHandle.destroy()); }); - + Thread.sleep(5000); - + childProc = ProcessHandle.current().children(); childProc.forEach(procHandle -> { - assertFalse("Process "+ procHandle.getPid() +" should not be alive!", procHandle.isAlive()); + assertFalse("Process " + procHandle.getPid() + " should not be alive!", procHandle.isAlive()); }); - + } - private Process createNewJVM(Class mainClass, int number) throws IOException{ + private Process createNewJVM(Class mainClass, int number) throws IOException { ArrayList cmdParams = new ArrayList(5); cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath()); cmdParams.add("-cp"); cmdParams.add(ProcessUtils.getClassPath()); cmdParams.add(mainClass.getName()); - cmdParams.add("Service "+ number); + cmdParams.add("Service " + number); ProcessBuilder myService = new ProcessBuilder(cmdParams); myService.inheritIO(); return myService.start(); } - - private void waistCPU() throws NoSuchAlgorithmException{ + + private void waistCPU() throws NoSuchAlgorithmException { ArrayList randArr = new ArrayList(4096); SecureRandom sr = SecureRandom.getInstanceStrong(); Duration somecpu = Duration.ofMillis(4200L); Instant end = Instant.now().plus(somecpu); while (Instant.now().isBefore(end)) { - //System.out.println(sr.nextInt()); - randArr.add( sr.nextInt() ); + // System.out.println(sr.nextInt()); + randArr.add(sr.nextInt()); } } diff --git a/core-java/.gitignore b/core-java/.gitignore index 464f7e5e38..251a8755bd 100644 --- a/core-java/.gitignore +++ b/core-java/.gitignore @@ -16,3 +16,7 @@ *.txt /bin/ /temp + +#IntelliJ specific +.idea +*.iml \ No newline at end of file diff --git a/core-java/README.md b/core-java/README.md index 3abe1ba808..cd16935864 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -46,3 +46,14 @@ - [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) +- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) +- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future) +- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue) +- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch) diff --git a/core-java/pom.xml b/core-java/pom.xml index 6979d980b7..2b6f065c85 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung core-java @@ -10,6 +10,44 @@ + + org.neo4j + neo4j + 3.1.0 + + + + org.neo4j.driver + neo4j-java-driver + 1.1.1 + + + + org.neo4j + neo4j-jdbc-driver + 3.0.1 + + + + org.neo4j + neo4j-ogm-core + 2.1.1 + + + + org.neo4j + neo4j-ogm-embedded-driver + 2.1.1 + + + + com.google.inject + guice + 4.1.0 + no_aop + test + + net.sourceforge.collections @@ -153,6 +191,12 @@ ${mockito.version} test + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + commons-codec @@ -262,7 +306,8 @@ true - + org.baeldung.executable.ExecutableMavenJar @@ -352,7 +397,7 @@ 1.1.7 - 19.0 + 21.0 3.5 1.55 1.10 @@ -370,6 +415,7 @@ 1.10.19 6.10 3.6.1 + 1.7.0 3.6.0 diff --git a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java index 9394bbdbb8..3f7c8bf4b3 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java +++ b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java @@ -3,6 +3,7 @@ package com.baeldung.algorithms; import java.util.Scanner; import com.baeldung.algorithms.annealing.SimulatedAnnealing; +import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; import com.baeldung.algorithms.slope_one.SlopeOne; public class RunAlgorithm { @@ -12,6 +13,7 @@ public class RunAlgorithm { System.out.println("Run algorithm:"); System.out.println("1 - Simulated Annealing"); System.out.println("2 - Slope One"); + System.out.println("3 - Simple Genetic Algorithm"); int decision = in.nextInt(); switch (decision) { case 1: @@ -21,6 +23,10 @@ public class RunAlgorithm { case 2: SlopeOne.slopeOne(3); break; + case 3: + SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); + ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); + break; default: System.out.println("Unknown option"); break; diff --git a/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java b/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java index 0f060c73c2..77e8652df0 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java +++ b/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java @@ -5,18 +5,18 @@ import lombok.Data; @Data public class City { - private int x; - private int y; + private int x; + private int y; - public City() { - this.x = (int) (Math.random() * 500); - this.y = (int) (Math.random() * 500); - } + public City() { + this.x = (int) (Math.random() * 500); + this.y = (int) (Math.random() * 500); + } - public double distanceToCity(City city) { - int x = Math.abs(getX() - city.getX()); - int y = Math.abs(getY() - city.getY()); - return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); - } + public double distanceToCity(City city) { + int x = Math.abs(getX() - city.getX()); + int y = Math.abs(getY() - city.getY()); + return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java b/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java index c02b0b8285..a7dc974e97 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java +++ b/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java @@ -24,7 +24,7 @@ public class SimulatedAnnealing { } t *= coolingRate; } else { - continue; + continue; } if (i % 100 == 0) { System.out.println("Iteration #" + i); diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java new file mode 100644 index 0000000000..2a740777f3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java @@ -0,0 +1,44 @@ +package com.baeldung.algorithms.ga.binary; + +import lombok.Data; + +@Data +public class Individual { + + protected int defaultGeneLength = 64; + private byte[] genes = new byte[defaultGeneLength]; + private int fitness = 0; + + public Individual() { + for (int i = 0; i < genes.length; i++) { + byte gene = (byte) Math.round(Math.random()); + genes[i] = gene; + } + } + + protected byte getSingleGene(int index) { + return genes[index]; + } + + protected void setSingleGene(int index, byte value) { + genes[index] = value; + fitness = 0; + } + + public int getFitness() { + if (fitness == 0) { + fitness = SimpleGeneticAlgorithm.getFitness(this); + } + return fitness; + } + + @Override + public String toString() { + String geneString = ""; + for (int i = 0; i < genes.length; i++) { + geneString += getSingleGene(i); + } + return geneString; + } + +} diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java new file mode 100644 index 0000000000..47677d7d88 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java @@ -0,0 +1,40 @@ +package com.baeldung.algorithms.ga.binary; + +import java.util.ArrayList; +import java.util.List; + +import lombok.Data; + +@Data +public class Population { + + private List individuals; + + public Population(int size, boolean createNew) { + individuals = new ArrayList<>(); + if (createNew) { + createNewPopulation(size); + } + } + + protected Individual getIndividual(int index) { + return individuals.get(index); + } + + protected Individual getFittest() { + Individual fittest = individuals.get(0); + for (int i = 0; i < individuals.size(); i++) { + if (fittest.getFitness() <= getIndividual(i).getFitness()) { + fittest = getIndividual(i); + } + } + return fittest; + } + + private void createNewPopulation(int size) { + for (int i = 0; i < size; i++) { + Individual newIndividual = new Individual(); + individuals.add(i, newIndividual); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java new file mode 100644 index 0000000000..e62eab0d57 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java @@ -0,0 +1,117 @@ +package com.baeldung.algorithms.ga.binary; + +import lombok.Data; + +@Data +public class SimpleGeneticAlgorithm { + + private static final double uniformRate = 0.5; + private static final double mutationRate = 0.025; + private static final int tournamentSize = 5; + private static final boolean elitism = true; + private static byte[] solution = new byte[64]; + + public boolean runAlgorithm(int populationSize, String solution) { + if (solution.length() != SimpleGeneticAlgorithm.solution.length) { + throw new RuntimeException("The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes"); + } + setSolution(solution); + Population myPop = new Population(populationSize, true); + + int generationCount = 1; + while (myPop.getFittest().getFitness() < getMaxFitness()) { + System.out.println("Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness()); + myPop = evolvePopulation(myPop); + generationCount++; + } + System.out.println("Solution found!"); + System.out.println("Generation: " + generationCount); + System.out.println("Genes: "); + System.out.println(myPop.getFittest()); + return true; + } + + public Population evolvePopulation(Population pop) { + int elitismOffset; + Population newPopulation = new Population(pop.getIndividuals().size(), false); + + if (elitism) { + newPopulation.getIndividuals().add(0, pop.getFittest()); + elitismOffset = 1; + } else { + elitismOffset = 0; + } + + for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) { + Individual indiv1 = tournamentSelection(pop); + Individual indiv2 = tournamentSelection(pop); + Individual newIndiv = crossover(indiv1, indiv2); + newPopulation.getIndividuals().add(i, newIndiv); + } + + for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) { + mutate(newPopulation.getIndividual(i)); + } + + return newPopulation; + } + + private Individual crossover(Individual indiv1, Individual indiv2) { + Individual newSol = new Individual(); + for (int i = 0; i < newSol.getDefaultGeneLength(); i++) { + if (Math.random() <= uniformRate) { + newSol.setSingleGene(i, indiv1.getSingleGene(i)); + } else { + newSol.setSingleGene(i, indiv2.getSingleGene(i)); + } + } + return newSol; + } + + private void mutate(Individual indiv) { + for (int i = 0; i < indiv.getDefaultGeneLength(); i++) { + if (Math.random() <= mutationRate) { + byte gene = (byte) Math.round(Math.random()); + indiv.setSingleGene(i, gene); + } + } + } + + private Individual tournamentSelection(Population pop) { + Population tournament = new Population(tournamentSize, false); + for (int i = 0; i < tournamentSize; i++) { + int randomId = (int) (Math.random() * pop.getIndividuals().size()); + tournament.getIndividuals().add(i, pop.getIndividual(randomId)); + } + Individual fittest = tournament.getFittest(); + return fittest; + } + + protected static int getFitness(Individual individual) { + int fitness = 0; + for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) { + if (individual.getSingleGene(i) == solution[i]) { + fitness++; + } + } + return fitness; + } + + protected int getMaxFitness() { + int maxFitness = solution.length; + return maxFitness; + } + + protected void setSolution(String newSolution) { + solution = new byte[newSolution.length()]; + for (int i = 0; i < newSolution.length(); i++) { + String character = newSolution.substring(i, i + 1); + if (character.contains("0") || character.contains("1")) { + solution[i] = Byte.parseByte(character); + } else { + solution[i] = 0; + } + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java b/core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java index 548f7ae4da..68a0f11b62 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java +++ b/core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java @@ -11,26 +11,25 @@ import lombok.Data; @Data public class InputData { - - protected static List items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), - new Item("Snacks")); - public static Map> initializeData(int numberOfUsers) { - Map> data = new HashMap<>(); - HashMap newUser; - Set newRecommendationSet; - for (int i = 0; i < numberOfUsers; i++) { - newUser = new HashMap(); - newRecommendationSet = new HashSet<>(); - for (int j = 0; j < 3; j++) { - newRecommendationSet.add(items.get((int) (Math.random() * 5))); - } - for (Item item : newRecommendationSet) { - newUser.put(item, Math.random()); - } - data.put(new User("User " + i), newUser); - } - return data; - } + protected static List items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), new Item("Snacks")); + + public static Map> initializeData(int numberOfUsers) { + Map> data = new HashMap<>(); + HashMap newUser; + Set newRecommendationSet; + for (int i = 0; i < numberOfUsers; i++) { + newUser = new HashMap(); + newRecommendationSet = new HashSet<>(); + for (int j = 0; j < 3; j++) { + newRecommendationSet.add(items.get((int) (Math.random() * 5))); + } + for (Item item : newRecommendationSet) { + newUser.put(item, Math.random()); + } + data.put(new User("User " + i), newUser); + } + return data; + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java b/core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java index 818a6d4601..dec1eb9e2c 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java +++ b/core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java @@ -9,5 +9,5 @@ import lombok.NoArgsConstructor; @AllArgsConstructor public class Item { - private String itemName; + private String itemName; } diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java b/core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java index f11538356a..d5eea279de 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java +++ b/core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java @@ -11,114 +11,114 @@ import java.util.Map.Entry; */ public class SlopeOne { - private static Map> diff = new HashMap<>(); - private static Map> freq = new HashMap<>(); - private static Map> inputData; - private static Map> outputData = new HashMap<>(); + private static Map> diff = new HashMap<>(); + private static Map> freq = new HashMap<>(); + private static Map> inputData; + private static Map> outputData = new HashMap<>(); - public static void slopeOne(int numberOfUsers) { - inputData = InputData.initializeData(numberOfUsers); - System.out.println("Slope One - Before the Prediction\n"); - buildDifferencesMatrix(inputData); - System.out.println("\nSlope One - With Predictions\n"); - predict(inputData); - } + public static void slopeOne(int numberOfUsers) { + inputData = InputData.initializeData(numberOfUsers); + System.out.println("Slope One - Before the Prediction\n"); + buildDifferencesMatrix(inputData); + System.out.println("\nSlope One - With Predictions\n"); + predict(inputData); + } - /** - * Based on the available data, calculate the relationships between the - * items and number of occurences - * - * @param data - * existing user data and their items' ratings - */ - private static void buildDifferencesMatrix(Map> data) { - for (HashMap user : data.values()) { - for (Entry e : user.entrySet()) { - if (!diff.containsKey(e.getKey())) { - diff.put(e.getKey(), new HashMap()); - freq.put(e.getKey(), new HashMap()); - } - for (Entry e2 : user.entrySet()) { - int oldCount = 0; - if (freq.get(e.getKey()).containsKey(e2.getKey())) { - oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue(); - } - double oldDiff = 0.0; - if (diff.get(e.getKey()).containsKey(e2.getKey())) { - oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue(); - } - double observedDiff = e.getValue() - e2.getValue(); - freq.get(e.getKey()).put(e2.getKey(), oldCount + 1); - diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff); - } - } - } - for (Item j : diff.keySet()) { - for (Item i : diff.get(j).keySet()) { - double oldValue = diff.get(j).get(i).doubleValue(); - int count = freq.get(j).get(i).intValue(); - diff.get(j).put(i, oldValue / count); - } - } - printData(data); - } + /** + * Based on the available data, calculate the relationships between the + * items and number of occurences + * + * @param data + * existing user data and their items' ratings + */ + private static void buildDifferencesMatrix(Map> data) { + for (HashMap user : data.values()) { + for (Entry e : user.entrySet()) { + if (!diff.containsKey(e.getKey())) { + diff.put(e.getKey(), new HashMap()); + freq.put(e.getKey(), new HashMap()); + } + for (Entry e2 : user.entrySet()) { + int oldCount = 0; + if (freq.get(e.getKey()).containsKey(e2.getKey())) { + oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue(); + } + double oldDiff = 0.0; + if (diff.get(e.getKey()).containsKey(e2.getKey())) { + oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue(); + } + double observedDiff = e.getValue() - e2.getValue(); + freq.get(e.getKey()).put(e2.getKey(), oldCount + 1); + diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff); + } + } + } + for (Item j : diff.keySet()) { + for (Item i : diff.get(j).keySet()) { + double oldValue = diff.get(j).get(i).doubleValue(); + int count = freq.get(j).get(i).intValue(); + diff.get(j).put(i, oldValue / count); + } + } + printData(data); + } - /** - * Based on existing data predict all missing ratings. If prediction is not - * possible, the value will be equal to -1 - * - * @param data - * existing user data and their items' ratings - */ - private static void predict(Map> data) { - HashMap uPred = new HashMap(); - HashMap uFreq = new HashMap(); - for (Item j : diff.keySet()) { - uFreq.put(j, 0); - uPred.put(j, 0.0); - } - for (Entry> e : data.entrySet()) { - for (Item j : e.getValue().keySet()) { - for (Item k : diff.keySet()) { - try { - double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue(); - double finalValue = predictedValue * freq.get(k).get(j).intValue(); - uPred.put(k, uPred.get(k) + finalValue); - uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue()); - } catch (NullPointerException e1) { - } - } - } - HashMap clean = new HashMap(); - for (Item j : uPred.keySet()) { - if (uFreq.get(j) > 0) { - clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue()); - } - } - for (Item j : InputData.items) { - if (e.getValue().containsKey(j)) { - clean.put(j, e.getValue().get(j)); - } else { - clean.put(j, -1.0); - } - } - outputData.put(e.getKey(), clean); - } - printData(outputData); - } + /** + * Based on existing data predict all missing ratings. If prediction is not + * possible, the value will be equal to -1 + * + * @param data + * existing user data and their items' ratings + */ + private static void predict(Map> data) { + HashMap uPred = new HashMap(); + HashMap uFreq = new HashMap(); + for (Item j : diff.keySet()) { + uFreq.put(j, 0); + uPred.put(j, 0.0); + } + for (Entry> e : data.entrySet()) { + for (Item j : e.getValue().keySet()) { + for (Item k : diff.keySet()) { + try { + double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue(); + double finalValue = predictedValue * freq.get(k).get(j).intValue(); + uPred.put(k, uPred.get(k) + finalValue); + uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue()); + } catch (NullPointerException e1) { + } + } + } + HashMap clean = new HashMap(); + for (Item j : uPred.keySet()) { + if (uFreq.get(j) > 0) { + clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue()); + } + } + for (Item j : InputData.items) { + if (e.getValue().containsKey(j)) { + clean.put(j, e.getValue().get(j)); + } else { + clean.put(j, -1.0); + } + } + outputData.put(e.getKey(), clean); + } + printData(outputData); + } - private static void printData(Map> data) { - for (User user : data.keySet()) { - System.out.println(user.getUsername() + ":"); - print(data.get(user)); - } - } + private static void printData(Map> data) { + for (User user : data.keySet()) { + System.out.println(user.getUsername() + ":"); + print(data.get(user)); + } + } - private static void print(HashMap hashMap) { - NumberFormat formatter = new DecimalFormat("#0.000"); - for (Item j : hashMap.keySet()) { - System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue())); - } - } + private static void print(HashMap hashMap) { + NumberFormat formatter = new DecimalFormat("#0.000"); + for (Item j : hashMap.keySet()) { + System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue())); + } + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java b/core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java index 57f16f6748..32bbe84d17 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java +++ b/core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java @@ -8,7 +8,7 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class User { - - private String username; + + private String username; } diff --git a/core-java/src/main/java/com/baeldung/chainedexception/LogWithChain.java b/core-java/src/main/java/com/baeldung/chainedexception/LogWithChain.java new file mode 100644 index 0000000000..3d66c2b535 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/chainedexception/LogWithChain.java @@ -0,0 +1,41 @@ +package com.baeldung.chainedexception; + +import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException; +import com.baeldung.chainedexception.exceptions.ManagerUpsetException; +import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException; +import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException; + +public class LogWithChain { + + public static void main(String[] args) throws Exception { + getLeave(); + } + + private static void getLeave() throws NoLeaveGrantedException { + try { + howIsTeamLead(); + } catch (TeamLeadUpsetException e) { + throw new NoLeaveGrantedException("Leave not sanctioned.", e); + } + } + + private static void howIsTeamLead() throws TeamLeadUpsetException { + try { + howIsManager(); + } catch (ManagerUpsetException e) { + throw new TeamLeadUpsetException("Team lead is not in good mood", e); + } + } + + private static void howIsManager() throws ManagerUpsetException { + try { + howIsGirlFriendOfManager(); + } catch (GirlFriendOfManagerUpsetException e) { + throw new ManagerUpsetException("Manager is in bad mood", e); + } + } + + private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException { + throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood"); + } +} diff --git a/core-java/src/main/java/com/baeldung/chainedexception/LogWithoutChain.java b/core-java/src/main/java/com/baeldung/chainedexception/LogWithoutChain.java new file mode 100644 index 0000000000..7556e30663 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/chainedexception/LogWithoutChain.java @@ -0,0 +1,44 @@ +package com.baeldung.chainedexception; + +import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException; +import com.baeldung.chainedexception.exceptions.ManagerUpsetException; +import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException; +import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException; + +public class LogWithoutChain { + + public static void main(String[] args) throws Exception { + getLeave(); + } + + private static void getLeave() throws NoLeaveGrantedException { + try { + howIsTeamLead(); + } catch (TeamLeadUpsetException e) { + e.printStackTrace(); + throw new NoLeaveGrantedException("Leave not sanctioned."); + } + } + + private static void howIsTeamLead() throws TeamLeadUpsetException { + try { + howIsManager(); + } catch (ManagerUpsetException e) { + e.printStackTrace(); + throw new TeamLeadUpsetException("Team lead is not in good mood"); + } + } + + private static void howIsManager() throws ManagerUpsetException { + try { + howIsGirlFriendOfManager(); + } catch (GirlFriendOfManagerUpsetException e) { + e.printStackTrace(); + throw new ManagerUpsetException("Manager is in bad mood"); + } + } + + private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException { + throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood"); + } +} diff --git a/core-java/src/main/java/com/baeldung/chainedexception/exceptions/GirlFriendOfManagerUpsetException.java b/core-java/src/main/java/com/baeldung/chainedexception/exceptions/GirlFriendOfManagerUpsetException.java new file mode 100644 index 0000000000..e20c58ea5b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/chainedexception/exceptions/GirlFriendOfManagerUpsetException.java @@ -0,0 +1,12 @@ +package com.baeldung.chainedexception.exceptions; + +public class GirlFriendOfManagerUpsetException extends Exception { + + public GirlFriendOfManagerUpsetException(String message, Throwable cause) { + super(message, cause); + } + + public GirlFriendOfManagerUpsetException(String message) { + super(message); + } +} diff --git a/core-java/src/main/java/com/baeldung/chainedexception/exceptions/ManagerUpsetException.java b/core-java/src/main/java/com/baeldung/chainedexception/exceptions/ManagerUpsetException.java new file mode 100644 index 0000000000..e95a3921a4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/chainedexception/exceptions/ManagerUpsetException.java @@ -0,0 +1,12 @@ +package com.baeldung.chainedexception.exceptions; + +public class ManagerUpsetException extends Exception { + + public ManagerUpsetException(String message, Throwable cause) { + super(message, cause); + } + + public ManagerUpsetException(String message) { + super(message); + } +} diff --git a/core-java/src/main/java/com/baeldung/chainedexception/exceptions/NoLeaveGrantedException.java b/core-java/src/main/java/com/baeldung/chainedexception/exceptions/NoLeaveGrantedException.java new file mode 100644 index 0000000000..b9521858b3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/chainedexception/exceptions/NoLeaveGrantedException.java @@ -0,0 +1,12 @@ +package com.baeldung.chainedexception.exceptions; + +public class NoLeaveGrantedException extends Exception { + + public NoLeaveGrantedException(String message, Throwable cause) { + super(message, cause); + } + + public NoLeaveGrantedException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/chainedexception/exceptions/TeamLeadUpsetException.java b/core-java/src/main/java/com/baeldung/chainedexception/exceptions/TeamLeadUpsetException.java new file mode 100644 index 0000000000..f874620f00 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/chainedexception/exceptions/TeamLeadUpsetException.java @@ -0,0 +1,12 @@ +package com.baeldung.chainedexception.exceptions; + +public class TeamLeadUpsetException extends Exception { + + public TeamLeadUpsetException(String message, Throwable cause) { + super(message, cause); + } + + public TeamLeadUpsetException(String message) { + super(message); + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java new file mode 100644 index 0000000000..052136bfe4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java @@ -0,0 +1,24 @@ +package com.baeldung.concurrent.blockingqueue; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +public class BlockingQueueUsage { + public static void main(String[] args) { + int BOUND = 10; + int N_PRODUCERS = 4; + int N_CONSUMERS = Runtime.getRuntime().availableProcessors(); + int poisonPill = Integer.MAX_VALUE; + int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS; + + BlockingQueue queue = new LinkedBlockingQueue<>(BOUND); + + for (int i = 0; i < N_PRODUCERS; i++) { + new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer)).start(); + } + + for (int j = 0; j < N_CONSUMERS; j++) { + new Thread(new NumbersConsumer(queue, poisonPill)).start(); + } + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java new file mode 100644 index 0000000000..13fe0c3126 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java @@ -0,0 +1,28 @@ +package com.baeldung.concurrent.blockingqueue; + +import java.util.concurrent.BlockingQueue; + +public class NumbersConsumer implements Runnable { + private final BlockingQueue queue; + private final int poisonPill; + + public NumbersConsumer(BlockingQueue queue, int poisonPill) { + this.queue = queue; + this.poisonPill = poisonPill; + } + + public void run() { + try { + while (true) { + Integer number = queue.take(); + if (number.equals(poisonPill)) { + return; + } + String result = number.toString(); + System.out.println(Thread.currentThread().getName() + " result: " + result); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java new file mode 100644 index 0000000000..b262097c63 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java @@ -0,0 +1,34 @@ +package com.baeldung.concurrent.blockingqueue; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ThreadLocalRandom; + +public class NumbersProducer implements Runnable { + + private final BlockingQueue numbersQueue; + private final int poisonPill; + private final int poisonPillPerProducer; + + public NumbersProducer(BlockingQueue numbersQueue, int poisonPill, int poisonPillPerProducer) { + this.numbersQueue = numbersQueue; + this.poisonPill = poisonPill; + this.poisonPillPerProducer = poisonPillPerProducer; + } + + public void run() { + try { + generateNumbers(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private void generateNumbers() throws InterruptedException { + for (int i = 0; i < 100; i++) { + numbersQueue.put(ThreadLocalRandom.current().nextInt(100)); + } + for (int j = 0; j < poisonPillPerProducer; j++) { + numbersQueue.put(poisonPill); + } + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java new file mode 100644 index 0000000000..90cd01b69f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.countdownlatch; + +import java.util.List; +import java.util.concurrent.CountDownLatch; + +public class BrokenWorker implements Runnable { + private final List outputScraper; + private final CountDownLatch countDownLatch; + + public BrokenWorker(final List outputScraper, final CountDownLatch countDownLatch) { + this.outputScraper = outputScraper; + this.countDownLatch = countDownLatch; + } + + @Override + public void run() { + if (true) { + throw new RuntimeException("Oh dear"); + } + countDownLatch.countDown(); + outputScraper.add("Counted down"); + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java new file mode 100644 index 0000000000..66be2030e2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java @@ -0,0 +1,34 @@ +package com.baeldung.concurrent.countdownlatch; + +import java.util.List; +import java.util.concurrent.CountDownLatch; + +public class WaitingWorker implements Runnable { + + private final List outputScraper; + private final CountDownLatch readyThreadCounter; + private final CountDownLatch callingThreadBlocker; + private final CountDownLatch completedThreadCounter; + + public WaitingWorker(final List outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) { + + this.outputScraper = outputScraper; + this.readyThreadCounter = readyThreadCounter; + this.callingThreadBlocker = callingThreadBlocker; + this.completedThreadCounter = completedThreadCounter; + } + + @Override + public void run() { + // Mark this thread as read / started + readyThreadCounter.countDown(); + try { + callingThreadBlocker.await(); + outputScraper.add("Counted down"); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + completedThreadCounter.countDown(); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java new file mode 100644 index 0000000000..e712fc18d6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent.countdownlatch; + +import java.util.List; +import java.util.concurrent.CountDownLatch; + +public class Worker implements Runnable { + private final List outputScraper; + private final CountDownLatch countDownLatch; + + public Worker(final List outputScraper, final CountDownLatch countDownLatch) { + this.outputScraper = outputScraper; + this.countDownLatch = countDownLatch; + } + + @Override + public void run() { + // Do some work + System.out.println("Doing some logic"); + outputScraper.add("Counted down"); + countDownLatch.countDown(); + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java b/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java new file mode 100644 index 0000000000..471072b333 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java @@ -0,0 +1,26 @@ +package com.baeldung.concurrent.future; + +import java.util.concurrent.RecursiveTask; + +public class FactorialSquareCalculator extends RecursiveTask { + private static final long serialVersionUID = 1L; + + final private Integer n; + + public FactorialSquareCalculator(Integer n) { + this.n = n; + } + + @Override + protected Integer compute() { + if (n <= 1) { + return n; + } + + FactorialSquareCalculator calculator = new FactorialSquareCalculator(n - 1); + + calculator.fork(); + + return n * n + calculator.join(); + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java new file mode 100644 index 0000000000..bcd559dd3b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java @@ -0,0 +1,20 @@ +package com.baeldung.concurrent.future; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +public class SquareCalculator { + + private final ExecutorService executor; + + public SquareCalculator(ExecutorService executor) { + this.executor = executor; + } + + public Future calculate(Integer input) { + return executor.submit(() -> { + Thread.sleep(1000); + return input * input; + }); + } +} diff --git a/core-java/src/main/java/com/baeldung/graph/Car.java b/core-java/src/main/java/com/baeldung/graph/Car.java new file mode 100644 index 0000000000..1dc65a0d4b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/graph/Car.java @@ -0,0 +1,50 @@ +package com.baeldung.graph; + +import org.neo4j.ogm.annotation.GraphId; +import org.neo4j.ogm.annotation.NodeEntity; +import org.neo4j.ogm.annotation.Relationship; + +/** + * @author Danil Kornishev (danil.kornishev@mastercard.com) + */ +@NodeEntity +public class Car { + @GraphId + private Long id; + + private String make; + + @Relationship(direction = "INCOMING") + private Company company; + + public Car(String make, String model) { + this.make = make; + this.model = model; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getMake() { + return make; + } + + public void setMake(String make) { + this.make = make; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + private String model; +} diff --git a/core-java/src/main/java/com/baeldung/graph/Company.java b/core-java/src/main/java/com/baeldung/graph/Company.java new file mode 100644 index 0000000000..1fe892b331 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/graph/Company.java @@ -0,0 +1,45 @@ +package com.baeldung.graph; + +import org.neo4j.ogm.annotation.NodeEntity; +import org.neo4j.ogm.annotation.Relationship; + +/** + * @author Danil Kornishev (danil.kornishev@mastercard.com) + */ +@NodeEntity +public class Company { + private Long id; + + private String name; + + @Relationship(type="owns") + private Car car; + + public Company(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Car getCar() { + return car; + } + + public void setCar(Car car) { + this.car = car; + } +} diff --git a/core-java/src/main/java/com/baeldung/java/map/MyLinkedHashMap.java b/core-java/src/main/java/com/baeldung/java/map/MyLinkedHashMap.java index e1c0071ed3..1e237580ec 100644 --- a/core-java/src/main/java/com/baeldung/java/map/MyLinkedHashMap.java +++ b/core-java/src/main/java/com/baeldung/java/map/MyLinkedHashMap.java @@ -10,13 +10,11 @@ public class MyLinkedHashMap extends LinkedHashMap { */ private static final long serialVersionUID = 1L; private static final int MAX_ENTRIES = 5; - public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { super(initialCapacity, loadFactor, accessOrder); } - @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_ENTRIES; diff --git a/core-java/src/main/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappers.java b/core-java/src/main/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappers.java new file mode 100644 index 0000000000..64532c8b6f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappers.java @@ -0,0 +1,57 @@ +package com.baeldung.java8.lambda.exceptions; + +import java.util.function.Consumer; + +public class LambdaExceptionWrappers { + + public static Consumer lambdaWrapper(Consumer consumer) { + return i -> { + try { + consumer.accept(i); + } catch (ArithmeticException e) { + System.err.println("Arithmetic Exception occured : " + e.getMessage()); + } + }; + } + + static Consumer consumerWrapper(Consumer consumer, Class clazz) { + return i -> { + try { + consumer.accept(i); + } catch (Exception ex) { + try { + E exCast = clazz.cast(ex); + System.err.println("Exception occured : " + exCast.getMessage()); + } catch (ClassCastException ccEx) { + throw ex; + } + } + }; + } + + public static Consumer throwingConsumerWrapper(ThrowingConsumer throwingConsumer) { + return i -> { + try { + throwingConsumer.accept(i); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + }; + } + + public static Consumer handlingConsumerWrapper(ThrowingConsumer throwingConsumer, Class exceptionClass) { + return i -> { + try { + throwingConsumer.accept(i); + } catch (Exception ex) { + try { + E exCast = exceptionClass.cast(ex); + System.err.println("Exception occured : " + exCast.getMessage()); + } catch (ClassCastException ccEx) { + throw new RuntimeException(ex); + } + } + }; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/java8/lambda/exceptions/ThrowingConsumer.java b/core-java/src/main/java/com/baeldung/java8/lambda/exceptions/ThrowingConsumer.java new file mode 100644 index 0000000000..c5860e7f6b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java8/lambda/exceptions/ThrowingConsumer.java @@ -0,0 +1,8 @@ +package com.baeldung.java8.lambda.exceptions; + +@FunctionalInterface +public interface ThrowingConsumer { + + void accept(T t) throws E; + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java new file mode 100644 index 0000000000..afc05e356a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java @@ -0,0 +1,36 @@ +package com.baeldung.java_8_features.groupingby; + +public class BlogPost { + private String title; + private String author; + private BlogPostType type; + private int likes; + + public BlogPost(String title, String author, BlogPostType type, int likes) { + this.title = title; + this.author = author; + this.type = type; + this.likes = likes; + } + + public String getTitle() { + return title; + } + + public String getAuthor() { + return author; + } + + public BlogPostType getType() { + return type; + } + + public int getLikes() { + return likes; + } + + @Override + public String toString() { + return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}'; + } +} diff --git a/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java new file mode 100644 index 0000000000..2029784e91 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java @@ -0,0 +1,5 @@ +package com.baeldung.java_8_features.groupingby; + +public enum BlogPostType { + NEWS, REVIEW, GUIDE +} diff --git a/core-java/src/main/java/com/baeldung/jmx/Game.java b/core-java/src/main/java/com/baeldung/jmx/Game.java new file mode 100644 index 0000000000..f38db27601 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/jmx/Game.java @@ -0,0 +1,24 @@ +package com.baeldung.jmx; + +public class Game implements GameMBean { + + private String playerName; + + @Override + public void playFootball(String clubName) { + System.out.println(this.playerName + " playing football for " + clubName); + } + + @Override + public String getPlayerName() { + System.out.println("Return playerName " + this.playerName); + return playerName; + } + + @Override + public void setPlayerName(String playerName) { + System.out.println("Set playerName to value " + playerName); + this.playerName = playerName; + } + +} diff --git a/core-java/src/main/java/com/baeldung/jmx/GameMBean.java b/core-java/src/main/java/com/baeldung/jmx/GameMBean.java new file mode 100644 index 0000000000..aa09a966d9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/jmx/GameMBean.java @@ -0,0 +1,11 @@ +package com.baeldung.jmx; + +public interface GameMBean { + + public void playFootball(String clubName); + + public String getPlayerName(); + + public void setPlayerName(String playerName); + +} diff --git a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java new file mode 100644 index 0000000000..6f9c30ab50 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java @@ -0,0 +1,37 @@ +package com.baeldung.jmx; + +import java.lang.management.ManagementFactory; +import javax.management.InstanceAlreadyExistsException; +import javax.management.MBeanRegistrationException; +import javax.management.MBeanServer; +import javax.management.MalformedObjectNameException; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +public class JMXTutorialMainlauncher { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + System.out.println("This is basic JMX tutorial"); + ObjectName objectName = null; + try { + objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); + } catch (MalformedObjectNameException e) { + e.printStackTrace(); + } + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + Game gameObj = new Game(); + try { + server.registerMBean(gameObj, objectName); + } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { + e.printStackTrace(); + } + System.out.println("Registration for Game mbean with the platform server is successfull"); + System.out.println("Please open jconsole to access Game mbean"); + while (true) { + // to ensure application does not terminate + } + } + +} 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/java/com/baeldung/strategy/ChristmasDiscounter.java b/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java new file mode 100644 index 0000000000..a0c36bb63e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java @@ -0,0 +1,11 @@ +package com.baeldung.strategy; + +import java.math.BigDecimal; + +public class ChristmasDiscounter implements Discounter { + + @Override + public BigDecimal apply(BigDecimal amount) { + return amount.multiply(BigDecimal.valueOf(0.9)); + } +} diff --git a/core-java/src/main/java/com/baeldung/strategy/Discounter.java b/core-java/src/main/java/com/baeldung/strategy/Discounter.java new file mode 100644 index 0000000000..00bf4855d1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/strategy/Discounter.java @@ -0,0 +1,23 @@ +package com.baeldung.strategy; + +import java.math.BigDecimal; +import java.util.function.UnaryOperator; + +public interface Discounter extends UnaryOperator { + + default Discounter combine(Discounter after) { + return value -> after.apply(this.apply(value)); + } + + static Discounter christmas() { + return (amount) -> amount.multiply(BigDecimal.valueOf(0.9)); + } + + static Discounter newYear() { + return (amount) -> amount.multiply(BigDecimal.valueOf(0.8)); + } + + static Discounter easter() { + return (amount) -> amount.multiply(BigDecimal.valueOf(0.5)); + } +} diff --git a/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java b/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java new file mode 100644 index 0000000000..990d10073b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java @@ -0,0 +1,11 @@ +package com.baeldung.strategy; + +import java.math.BigDecimal; + +public class EasterDiscounter implements Discounter { + + @Override + public BigDecimal apply(BigDecimal amount) { + return amount.multiply(BigDecimal.valueOf(0.5)); + } +} diff --git a/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java b/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java new file mode 100644 index 0000000000..5183921dea --- /dev/null +++ b/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java @@ -0,0 +1,23 @@ +package com.baeldung.streamApi; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class JoinerSplitter { + + public static String join ( String[] arrayOfString ) { + return Arrays.asList(arrayOfString) + .stream() + .map(x -> x) + .collect(Collectors.joining(",")); + } + + public static List split ( String str ) { + return Stream.of(str.split(",")) + .map (elem -> new String(elem)) + .collect(Collectors.toList()); + } + +} 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/CharArrayToStringUnitTest.java b/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java new file mode 100644 index 0000000000..3488f8b390 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class CharArrayToStringUnitTest { + + @Test + public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; + String result = new String(charArray); + String expectedValue = "character"; + + assertEquals(expectedValue, result); + } + + @Test + public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; + String result = new String(charArray, 4, 3); + String expectedValue = "act"; + + assertEquals(expectedValue, result); + } + + @Test + public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; + String result = String.copyValueOf(charArray); + String expectedValue = "character"; + + assertEquals(expectedValue, result); + } + + @Test + public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; + String result = String.copyValueOf(charArray, 0, 4); + String expectedValue = "char"; + + assertEquals(expectedValue, result); + } + + @Test + public void givenCharArray_whenCallingStringValueOf_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; + String result = String.valueOf(charArray); + String expectedValue = "character"; + + assertEquals(expectedValue, result); + } + + @Test + public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; + String result = String.valueOf(charArray, 3, 4); + String expectedValue = "ract"; + + assertEquals(expectedValue, result); + } +} diff --git a/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java b/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java new file mode 100644 index 0000000000..cd996e58e2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class StringToCharArrayUnitTest { + + @Test + public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() { + String givenString = "characters"; + + char[] result = givenString.toCharArray(); + + char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' }; + + assertArrayEquals(expectedCharArray, result); + } + +} diff --git a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java new file mode 100644 index 0000000000..2e92177c8c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.algorithms; + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; + +public class BinaryGeneticAlgorithmUnitTest { + + @Test + public void testGA() { + SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); + Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); + } + +} diff --git a/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java index dbddbe6c54..bad1c32e4a 100644 --- a/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java @@ -149,7 +149,7 @@ public class Java8CollectorsUnitTest { @Test public void whenSumming_shouldSum() throws Exception { - final Double result = givenList.stream().collect(summingDouble(String::length)); + final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length)); assertThat(result).isEqualTo(8); } diff --git a/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java b/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java new file mode 100644 index 0000000000..7bb2d4bb70 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java @@ -0,0 +1,70 @@ +package com.baeldung.concurrent.countdownlatch; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; + +public class CountdownLatchExampleTest { + @Test + public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException { + // Given + List outputScraper = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch countDownLatch = new CountDownLatch(5); + List workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch))).limit(5).collect(toList()); + + // When + workers.forEach(Thread::start); + countDownLatch.await(); // Block until workers finish + outputScraper.add("Latch released"); + + // Then + outputScraper.forEach(Object::toString); + assertThat(outputScraper).containsExactly("Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Latch released"); + } + + @Test + public void whenFailingToParallelProcess_thenMainThreadShouldTimeout() throws InterruptedException { + // Given + List outputScraper = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch countDownLatch = new CountDownLatch(5); + List workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))).limit(5).collect(toList()); + + // When + workers.forEach(Thread::start); + final boolean result = countDownLatch.await(3L, TimeUnit.SECONDS); + + // Then + assertThat(result).isFalse(); + } + + @Test + public void whenDoingLotsOfThreadsInParallel_thenStartThemAtTheSameTime() throws InterruptedException { + // Given + List outputScraper = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch readyThreadCounter = new CountDownLatch(5); + CountDownLatch callingThreadBlocker = new CountDownLatch(1); + CountDownLatch completedThreadCounter = new CountDownLatch(5); + List workers = Stream.generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter))).limit(5).collect(toList()); + + // When + workers.forEach(Thread::start); + readyThreadCounter.await(); // Block until workers start + outputScraper.add("Workers ready"); + callingThreadBlocker.countDown(); // Start workers + completedThreadCounter.await(); // Block until workers finish + outputScraper.add("Workers complete"); + + // Then + outputScraper.forEach(Object::toString); + assertThat(outputScraper).containsExactly("Workers ready", "Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Workers complete"); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java new file mode 100644 index 0000000000..a47c44506d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent.future; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.ForkJoinPool; + +import org.junit.Test; + +public class FactorialSquareCalculatorUnitTest { + + @Test + public void whenCalculatesFactorialSquare_thenReturnCorrectValue() { + ForkJoinPool forkJoinPool = new ForkJoinPool(); + + FactorialSquareCalculator calculator = new FactorialSquareCalculator(10); + + forkJoinPool.execute(calculator); + + assertEquals("The sum of the squares from 1 to 10 is 385", 385, calculator.join().intValue()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorUnitTest.java new file mode 100644 index 0000000000..69c802feb8 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorUnitTest.java @@ -0,0 +1,94 @@ +package com.baeldung.concurrent.future; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; + +public class SquareCalculatorUnitTest { + + @Rule + public TestName name = new TestName(); + + private long start; + + private SquareCalculator squareCalculator; + + @Test + public void givenExecutorIsSingleThreaded_whenTwoExecutionsAreTriggered_thenRunInSequence() throws InterruptedException, ExecutionException { + squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor()); + + Future result1 = squareCalculator.calculate(4); + Future result2 = squareCalculator.calculate(1000); + + while (!result1.isDone() || !result2.isDone()) { + System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); + + Thread.sleep(300); + } + + assertEquals(16, result1.get().intValue()); + assertEquals(1000000, result2.get().intValue()); + } + + @Test(expected = TimeoutException.class) + public void whenGetWithTimeoutLowerThanExecutionTime_thenThrowException() throws InterruptedException, ExecutionException, TimeoutException { + squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor()); + + Future result = squareCalculator.calculate(4); + + result.get(500, TimeUnit.MILLISECONDS); + } + + @Test + public void givenExecutorIsMultiThreaded_whenTwoExecutionsAreTriggered_thenRunInParallel() throws InterruptedException, ExecutionException { + squareCalculator = new SquareCalculator(Executors.newFixedThreadPool(2)); + + Future result1 = squareCalculator.calculate(4); + Future result2 = squareCalculator.calculate(1000); + + while (!result1.isDone() || !result2.isDone()) { + System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); + + Thread.sleep(300); + } + + assertEquals(16, result1.get().intValue()); + assertEquals(1000000, result2.get().intValue()); + } + + @Test(expected = CancellationException.class) + public void whenCancelFutureAndCallGet_thenThrowException() throws InterruptedException, ExecutionException, TimeoutException { + squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor()); + + Future result = squareCalculator.calculate(4); + + boolean canceled = result.cancel(true); + + assertTrue("Future was canceled", canceled); + assertTrue("Future was canceled", result.isCancelled()); + + result.get(); + } + + @Before + public void start() { + start = System.currentTimeMillis(); + } + + @After + public void end() { + System.out.println(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start)); + } +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java new file mode 100644 index 0000000000..0272726465 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.concurrent.priorityblockingqueue; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.util.Lists.newArrayList; + +public class PriorityBlockingQueueUnitTest { + + @Test + public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException { + PriorityBlockingQueue queue = new PriorityBlockingQueue<>(); + ArrayList polledElements = new ArrayList<>(); + + queue.add(1); + queue.add(5); + queue.add(2); + queue.add(3); + queue.add(4); + + queue.drainTo(polledElements); + + assertThat(polledElements).containsExactly(1, 2, 3, 4, 5); + } + + @Test + public void whenPollingEmptyQueue_thenShouldBlockThread() throws InterruptedException { + PriorityBlockingQueue queue = new PriorityBlockingQueue<>(); + + final Thread thread = new Thread(() -> { + System.out.println("Polling..."); + while (true) { + try { + Integer poll = queue.take(); + System.out.println("Polled: " + poll); + } catch (InterruptedException e) { + } + } + }); + thread.start(); + + Thread.sleep(TimeUnit.SECONDS.toMillis(5)); + System.out.println("Adding to queue"); + + queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7)); + Thread.sleep(TimeUnit.SECONDS.toMillis(1)); + } +} diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java b/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java new file mode 100644 index 0000000000..b41588b71e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java @@ -0,0 +1,60 @@ +package com.baeldung.graph; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; + +import org.junit.Ignore; +import org.junit.Test; +import org.neo4j.driver.v1.AuthTokens; +import org.neo4j.driver.v1.Driver; +import org.neo4j.driver.v1.GraphDatabase; +import org.neo4j.driver.v1.Session; +import org.neo4j.driver.v1.StatementResult; +import org.testng.Assert; + +@Ignore +public class Neo4JServerTest { + + @Test + public void standAloneDriver() { + Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "12345")); + Session session = driver.session(); + + session.run("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + StatementResult result = session.run("MATCH (company:Company)-[:owns]-> (car:Car)" + + "WHERE car.make='tesla' and car.model='modelX'" + + "RETURN company.name"); + + Assert.assertTrue(result.hasNext()); + Assert.assertEquals(result.next().get("company.name").asString(), "Baeldung"); + + session.close(); + driver.close(); + } + + @Test + public void standAloneJdbc() throws Exception { + Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost/?user=neo4j,password=12345,scheme=basic"); + + // Querying + try (Statement stmt = con.createStatement()) { + stmt.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + ResultSet rs = stmt.executeQuery("MATCH (company:Company)-[:owns]-> (car:Car)" + + "WHERE car.make='tesla' and car.model='modelX'" + + "RETURN company.name"); + + while (rs.next()) { + Assert.assertEquals(rs.getString("company.name"), "Baeldung"); + } + } + con.close(); + } +} diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java b/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java new file mode 100644 index 0000000000..00bd47d029 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java @@ -0,0 +1,46 @@ +package com.baeldung.graph; + +import org.junit.Test; +import org.neo4j.ogm.config.Configuration; +import org.neo4j.ogm.model.Result; +import org.neo4j.ogm.session.Session; +import org.neo4j.ogm.session.SessionFactory; +import org.testng.Assert; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Danil Kornishev (danil.kornishev@mastercard.com) + */ +public class Neo4jOgmTest { + + @Test + public void testOgm() { + Configuration conf = new Configuration(); + conf.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); + + SessionFactory factory = new SessionFactory(conf, "com.baeldung.graph"); + Session session = factory.openSession(); + + Car tesla = new Car("tesla", "modelS"); + Company baeldung = new Company("baeldung"); + + baeldung.setCar(tesla); + + session.save(baeldung); + + Map params = new HashMap<>(); + params.put("make", "tesla"); + Result result = session.query("MATCH (car:Car) <-[:owns]- (company:Company)" + + " WHERE car.make=$make" + + " RETURN company", params); + + Map firstResult = result.iterator().next(); + + Assert.assertEquals(firstResult.size(), 1); + + Company actual = (Company) firstResult.get("company"); + Assert.assertEquals(actual.getName(), baeldung.getName()); + } +} diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java b/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java new file mode 100644 index 0000000000..6956c2c39f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java @@ -0,0 +1,167 @@ +package com.baeldung.graph; + + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.neo4j.graphdb.GraphDatabaseService; +import org.neo4j.graphdb.Label; +import org.neo4j.graphdb.Node; +import org.neo4j.graphdb.NotFoundException; +import org.neo4j.graphdb.RelationshipType; +import org.neo4j.graphdb.Result; +import org.neo4j.graphdb.factory.GraphDatabaseFactory; +import org.testng.Assert; + +public class Neo4jTest { + + private static GraphDatabaseService graphDb; + + @Before + public void setUp() { + GraphDatabaseFactory graphDbFactory = new GraphDatabaseFactory(); + graphDb = graphDbFactory.newEmbeddedDatabase(new File("data/cars")); + } + + @After + public void tearDown() { + graphDb.shutdown(); + } + + @Test + public void testPersonCar() { + graphDb.beginTx(); + Node car = graphDb.createNode(Label.label("Car")); + car.setProperty("make", "tesla"); + car.setProperty("model", "model3"); + + Node owner = graphDb.createNode(Label.label("Person")); + owner.setProperty("firstName", "baeldung"); + owner.setProperty("lastName", "baeldung"); + + owner.createRelationshipTo(car, RelationshipType.withName("owner")); + + Result result = graphDb.execute("MATCH (c:Car) <-[owner]- (p:Person) " + + "WHERE c.make = 'tesla'" + + "RETURN p.firstName, p.lastName"); + + Map firstResult = result.next(); + Assert.assertEquals("baeldung", firstResult.get("p.firstName")); + } + + @Test + public void testCreateNode() { + + graphDb.beginTx(); + + Result result = graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"})" + + "RETURN baeldung"); + + Map firstResult = result.next(); + Node firstNode = (Node) firstResult.get("baeldung"); + Assert.assertEquals(firstNode.getProperty("name"), "Baeldung"); + } + + @Test + public void testCreateNodeAndLink() { + graphDb.beginTx(); + + Result result = graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + Map firstResult = result.next(); + Assert.assertTrue(firstResult.containsKey("baeldung")); + Assert.assertTrue(firstResult.containsKey("tesla")); + } + + @Test + public void testFindAndReturn() { + graphDb.beginTx(); + + graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + Result result = graphDb.execute("MATCH (company:Company)-[:owns]-> (car:Car)" + + "WHERE car.make='tesla' and car.model='modelX'" + + "RETURN company.name"); + + Map firstResult = result.next(); + Assert.assertEquals(firstResult.get("company.name"), "Baeldung"); + } + + @Test + public void testUpdate() { + graphDb.beginTx(); + + graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + Result result = graphDb.execute("MATCH (car:Car)" + + "WHERE car.make='tesla'" + + " SET car.milage=120" + + " SET car :Car:Electro" + + " SET car.model=NULL" + + " RETURN car"); + + Map firstResult = result.next(); + Node car = (Node) firstResult.get("car"); + + Assert.assertEquals(car.getProperty("milage"), 120L); + Assert.assertEquals(car.getLabels(), Arrays.asList(Label.label("Car"), Label.label("Electro"))); + + try { + car.getProperty("model"); + Assert.fail(); + } catch (NotFoundException e) { + // expected + } + } + + @Test + public void testDelete() { + graphDb.beginTx(); + + graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + graphDb.execute("MATCH (company:Company)" + + " WHERE company.name='Baeldung'" + + " DELETE company"); + + Result result = graphDb.execute("MATCH (company:Company)" + + " WHERE company.name='Baeldung'" + + " RETURN company"); + + Assert.assertFalse(result.hasNext()); + } + + @Test + public void testBindings() { + graphDb.beginTx(); + + Map params = new HashMap<>(); + params.put("name", "baeldung"); + params.put("make", "tesla"); + params.put("model", "modelS"); + + Result result = graphDb.execute("CREATE (baeldung:Company {name:$name}) " + + "-[:owns]-> (tesla:Car {make: $make, model: $model})" + + "RETURN baeldung, tesla", params); + + Map firstResult = result.next(); + Assert.assertTrue(firstResult.containsKey("baeldung")); + Assert.assertTrue(firstResult.containsKey("tesla")); + + Node car = (Node) firstResult.get("tesla"); + Assert.assertEquals(car.getProperty("model"), "modelS"); + } +} diff --git a/core-java/src/test/java/com/baeldung/guava/GuavaBiMapTest.java b/core-java/src/test/java/com/baeldung/guava/GuavaBiMapTest.java new file mode 100644 index 0000000000..0997c93a72 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/guava/GuavaBiMapTest.java @@ -0,0 +1,120 @@ +package com.baeldung.guava; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import com.google.common.collect.BiMap; +import com.google.common.collect.EnumHashBiMap; +import com.google.common.collect.HashBiMap; +import com.google.common.collect.ImmutableBiMap; + +public class GuavaBiMapTest { + @Test + public void whenQueryByValue_returnsKey() { + final BiMap capitalCountryBiMap = HashBiMap.create(); + capitalCountryBiMap.put("New Delhi", "India"); + capitalCountryBiMap.put("Washingon, D.C.", "USA"); + capitalCountryBiMap.put("Moscow", "Russia"); + + final String countryCapitalName = capitalCountryBiMap.inverse().get("India"); + + assertEquals("New Delhi", countryCapitalName); + } + + @Test + public void whenCreateBiMapFromExistingMap_returnsKey() { + final Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("New Delhi", "India"); + capitalCountryMap.put("Washingon, D.C.", "USA"); + capitalCountryMap.put("Moscow", "Russia"); + final BiMap capitalCountryBiMap = HashBiMap.create(capitalCountryMap); + + final String countryCapitalName = capitalCountryBiMap.inverse().get("India"); + + assertEquals("New Delhi", countryCapitalName); + } + + @Test + public void whenQueryByKey_returnsValue() { + final BiMap capitalCountryBiMap = HashBiMap.create(); + + capitalCountryBiMap.put("New Delhi", "India"); + capitalCountryBiMap.put("Washingon, D.C.", "USA"); + capitalCountryBiMap.put("Moscow", "Russia"); + + assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C.")); + } + + @Test(expected = IllegalArgumentException.class) + public void whenSameValueIsPresent_throwsException() { + final BiMap capitalCountryBiMap = HashBiMap.create(); + + capitalCountryBiMap.put("New Delhi", "India"); + capitalCountryBiMap.put("Washingon, D.C.", "USA"); + capitalCountryBiMap.put("Moscow", "Russia"); + capitalCountryBiMap.put("Trump", "USA"); + } + + @Test + public void givenSameValueIsPresent_whenForcePut_completesSuccessfully() { + final BiMap capitalCountryBiMap = HashBiMap.create(); + + capitalCountryBiMap.put("New Delhi", "India"); + capitalCountryBiMap.put("Washingon, D.C.", "USA"); + capitalCountryBiMap.put("Moscow", "Russia"); + capitalCountryBiMap.forcePut("Trump", "USA"); + + assertEquals("USA", capitalCountryBiMap.get("Trump")); + assertEquals("Trump", capitalCountryBiMap.inverse().get("USA")); + } + + @Test + public void whenSameKeyIsPresent_replacesAlreadyPresent() { + final BiMap capitalCountryBiMap = HashBiMap.create(); + + capitalCountryBiMap.put("New Delhi", "India"); + capitalCountryBiMap.put("Washingon, D.C.", "USA"); + capitalCountryBiMap.put("Moscow", "Russia"); + capitalCountryBiMap.put("Washingon, D.C.", "HongKong"); + + assertEquals("HongKong", capitalCountryBiMap.get("Washingon, D.C.")); + } + + @Test + public void whenUsingImmutableBiMap_allowsPutSuccessfully() { + final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); + + assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C.")); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenUsingImmutableBiMap_doesntAllowRemove() { + final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); + + capitalCountryBiMap.remove("New Delhi"); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenUsingImmutableBiMap_doesntAllowPut() { + final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); + + capitalCountryBiMap.put("New York", "USA"); + } + + private enum Operation { + ADD, SUBTRACT, MULTIPLY, DIVIDE + } + + @Test + public void whenUsingEnumAsKeyInMap_replacesAlreadyPresent() { + final BiMap operationStringBiMap = EnumHashBiMap.create(Operation.class); + + operationStringBiMap.put(Operation.ADD, "Add"); + operationStringBiMap.put(Operation.SUBTRACT, "Subtract"); + operationStringBiMap.put(Operation.MULTIPLY, "Multiply"); + operationStringBiMap.put(Operation.DIVIDE, "Divide"); + + assertEquals("Divide", operationStringBiMap.get(Operation.DIVIDE)); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java new file mode 100644 index 0000000000..ec865f71c4 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java @@ -0,0 +1,76 @@ +package com.baeldung.java.concurrentmap; + +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class ConcurrentMapAggregateStatusManualTest { + + private ExecutorService executorService; + private Map concurrentMap; + private List mapSizes; + private int MAX_SIZE = 100000; + + @Before + public void init() { + executorService = Executors.newFixedThreadPool(2); + concurrentMap = new ConcurrentHashMap<>(); + mapSizes = new ArrayList<>(MAX_SIZE); + } + + @Test + public void givenConcurrentMap_whenSizeWithoutConcurrentUpdates_thenCorrect() throws InterruptedException { + Runnable collectMapSizes = () -> { + for (int i = 0; i < MAX_SIZE; i++) { + concurrentMap.put(String.valueOf(i), i); + mapSizes.add(concurrentMap.size()); + } + }; + Runnable retrieveMapData = () -> { + for (int i = 0; i < MAX_SIZE; i++) { + concurrentMap.get(String.valueOf(i)); + } + }; + executorService.execute(retrieveMapData); + executorService.execute(collectMapSizes); + executorService.shutdown(); + executorService.awaitTermination(1, TimeUnit.MINUTES); + + for (int i = 1; i <= MAX_SIZE; i++) { + assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue()); + } + assertEquals(MAX_SIZE, concurrentMap.size()); + } + + @Test + public void givenConcurrentMap_whenUpdatingAndGetSize_thenError() throws InterruptedException { + Runnable collectMapSizes = () -> { + for (int i = 0; i < MAX_SIZE; i++) { + mapSizes.add(concurrentMap.size()); + } + }; + Runnable updateMapData = () -> { + for (int i = 0; i < MAX_SIZE; i++) { + concurrentMap.put(String.valueOf(i), i); + } + }; + executorService.execute(updateMapData); + executorService.execute(collectMapSizes); + executorService.shutdown(); + executorService.awaitTermination(1, TimeUnit.MINUTES); + + assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue()); + assertEquals(MAX_SIZE, concurrentMap.size()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java new file mode 100644 index 0000000000..33e3326427 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java @@ -0,0 +1,160 @@ +package com.baeldung.java.concurrentmap; + +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import static org.junit.Assert.assertNull; + +public class ConcurrentMapNullKeyValueManualTest { + + ConcurrentMap concurrentMap; + + @Before + public void setup() { + concurrentMap = new ConcurrentHashMap<>(); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenGetWithNullKey_thenThrowsNPE() { + concurrentMap.get(null); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenGetOrDefaultWithNullKey_thenThrowsNPE() { + concurrentMap.getOrDefault(null, new Object()); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenPutWithNullKey_thenThrowsNPE() { + concurrentMap.put(null, new Object()); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenPutNullValue_thenThrowsNPE() { + concurrentMap.put("test", null); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMapAndKeyAbsent_whenPutWithNullKey_thenThrowsNPE() { + concurrentMap.putIfAbsent(null, new Object()); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMapAndMapWithNullKey_whenPutNullKeyMap_thenThrowsNPE() { + Map nullKeyMap = new HashMap<>(); + nullKeyMap.put(null, new Object()); + concurrentMap.putAll(nullKeyMap); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMapAndMapWithNullValue_whenPutNullValueMap_thenThrowsNPE() { + Map nullValueMap = new HashMap<>(); + nullValueMap.put("test", null); + concurrentMap.putAll(nullValueMap); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenReplaceNullKeyWithValues_thenThrowsNPE() { + concurrentMap.replace(null, new Object(), new Object()); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenReplaceWithNullNewValue_thenThrowsNPE() { + Object o = new Object(); + concurrentMap.replace("test", o, null); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenReplaceOldNullValue_thenThrowsNPE() { + Object o = new Object(); + concurrentMap.replace("test", null, o); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenReplaceWithNullValue_thenThrowsNPE() { + concurrentMap.replace("test", null); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenReplaceNullKey_thenThrowsNPE() { + concurrentMap.replace(null, "test"); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenReplaceAllMappingNull_thenThrowsNPE() { + concurrentMap.put("test", new Object()); + concurrentMap.replaceAll((s, o) -> null); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenRemoveNullKey_thenThrowsNPE() { + concurrentMap.remove(null); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenRemoveNullKeyWithValue_thenThrowsNPE() { + concurrentMap.remove(null, new Object()); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenMergeNullKeyWithValue_thenThrowsNPE() { + concurrentMap.merge(null, new Object(), (o, o2) -> o2); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenMergeKeyWithNullValue_thenThrowsNPE() { + concurrentMap.put("test", new Object()); + concurrentMap.merge("test", null, (o, o2) -> o2); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMapAndAssumeKeyAbsent_whenComputeWithNullKey_thenThrowsNPE() { + concurrentMap.computeIfAbsent(null, s -> s); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMapAndAssumeKeyPresent_whenComputeWithNullKey_thenThrowsNPE() { + concurrentMap.computeIfPresent(null, (s, o) -> o); + } + + @Test(expected = NullPointerException.class) + public void givenConcurrentHashMap_whenComputeWithNullKey_thenThrowsNPE() { + concurrentMap.compute(null, (s, o) -> o); + } + + @Test + public void givenConcurrentHashMap_whenMergeKeyRemappingNull_thenRemovesMapping() { + Object oldValue = new Object(); + concurrentMap.put("test", oldValue); + concurrentMap.merge("test", new Object(), (o, o2) -> null); + assertNull(concurrentMap.get("test")); + } + + @Test + public void givenConcurrentHashMapAndKeyAbsent_whenComputeWithKeyRemappingNull_thenRemainsAbsent() { + concurrentMap.computeIfPresent("test", (s, o) -> null); + assertNull(concurrentMap.get("test")); + } + + @Test + public void givenKeyPresent_whenComputeIfPresentRemappingNull_thenMappingRemoved() { + Object oldValue = new Object(); + concurrentMap.put("test", oldValue); + concurrentMap.computeIfPresent("test", (s, o) -> null); + assertNull(concurrentMap.get("test")); + } + + @Test + public void givenKeyPresent_whenComputeRemappingNull_thenMappingRemoved() { + Object oldValue = new Object(); + concurrentMap.put("test", oldValue); + concurrentMap.compute("test", (s, o) -> null); + assertNull(concurrentMap.get("test")); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java new file mode 100644 index 0000000000..5c1612ca60 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java @@ -0,0 +1,95 @@ +package com.baeldung.java.concurrentmap; + +import org.junit.Test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; +import java.util.concurrent.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class ConcurrentMapPerformanceManualTest { + + @Test + public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception { + Map hashtable = new Hashtable<>(); + Map synchronizedHashMap = Collections.synchronizedMap(new HashMap<>()); + Map concurrentHashMap = new ConcurrentHashMap<>(); + + long hashtableAvgRuntime = timeElapseForGetPut(hashtable); + long syncHashMapAvgRuntime = timeElapseForGetPut(synchronizedHashMap); + long concurrentHashMapAvgRuntime = timeElapseForGetPut(concurrentHashMap); + + System.out.println(String.format("Hashtable: %s, syncHashMap: %s, ConcurrentHashMap: %s", hashtableAvgRuntime, syncHashMapAvgRuntime, concurrentHashMapAvgRuntime)); + + assertTrue(hashtableAvgRuntime > concurrentHashMapAvgRuntime); + assertTrue(syncHashMapAvgRuntime > concurrentHashMapAvgRuntime); + + } + + private long timeElapseForGetPut(Map map) throws InterruptedException { + ExecutorService executorService = Executors.newFixedThreadPool(4); + long startTime = System.nanoTime(); + for (int i = 0; i < 4; i++) { + executorService.execute(() -> { + for (int j = 0; j < 500_000; j++) { + int value = ThreadLocalRandom.current().nextInt(10000); + String key = String.valueOf(value); + map.put(key, value); + map.get(key); + } + }); + } + executorService.shutdown(); + executorService.awaitTermination(1, TimeUnit.MINUTES); + return (System.nanoTime() - startTime) / 500_000; + } + + @Test + public void givenConcurrentMap_whenKeyWithSameHashCode_thenPerformanceDegrades() throws InterruptedException { + class SameHash { + @Override + public int hashCode() { + return 1; + } + } + int executeTimes = 5000; + + Map mapOfSameHash = new ConcurrentHashMap<>(); + ExecutorService executorService = Executors.newFixedThreadPool(2); + long sameHashStartTime = System.currentTimeMillis(); + for (int i = 0; i < 2; i++) { + executorService.execute(() -> { + for (int j = 0; j < executeTimes; j++) { + mapOfSameHash.put(new SameHash(), 1); + } + }); + } + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.SECONDS); + + long mapOfSameHashDuration = System.currentTimeMillis() - sameHashStartTime; + Map mapOfDefaultHash = new ConcurrentHashMap<>(); + executorService = Executors.newFixedThreadPool(2); + long defaultHashStartTime = System.currentTimeMillis(); + for (int i = 0; i < 2; i++) { + executorService.execute(() -> { + for (int j = 0; j < executeTimes; j++) { + mapOfDefaultHash.put(new Object(), 1); + } + }); + } + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.SECONDS); + + long mapOfDefaultHashDuration = System.currentTimeMillis() - defaultHashStartTime; + assertEquals(executeTimes * 2, mapOfDefaultHash.size()); + assertEquals(executeTimes * 2, mapOfSameHash.size()); + System.out.println(String.format("same-hash: %s, default-hash: %s", mapOfSameHashDuration, mapOfDefaultHashDuration)); + assertTrue("same hashCode() should greatly degrade performance", mapOfSameHashDuration > mapOfDefaultHashDuration * 10); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java new file mode 100644 index 0000000000..d102680aa4 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java @@ -0,0 +1,77 @@ +package com.baeldung.java.concurrentmap; + +import org.junit.Test; + +import java.util.Iterator; +import java.util.NavigableMap; +import java.util.TreeMap; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.testng.Assert.*; + +public class ConcurrentNavigableMapManualTests { + + @Test + public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException { + NavigableMap skipListMap = new ConcurrentSkipListMap<>(); + + updateMapConcurrently(skipListMap, 4); + + Iterator skipListIter = skipListMap.keySet().iterator(); + int previous = skipListIter.next(); + while (skipListIter.hasNext()) { + int current = skipListIter.next(); + assertTrue(previous < current); + } + } + + private void updateMapConcurrently(NavigableMap navigableMap, int concurrencyLevel) throws InterruptedException { + ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel); + for (int i = 0; i < concurrencyLevel; i++) { + executorService.execute(() -> { + ThreadLocalRandom random = ThreadLocalRandom.current(); + for (int j = 0; j < 10000; j++) { + navigableMap.put(random.nextInt(), "test"); + } + }); + } + executorService.shutdown(); + executorService.awaitTermination(1, TimeUnit.MINUTES); + } + + @Test + public void givenSkipListMap_whenNavConcurrently_thenCountCorrect() throws InterruptedException { + NavigableMap skipListMap = new ConcurrentSkipListMap<>(); + int count = countMapElementByPollingFirstEntry(skipListMap, 10000, 4); + assertEquals(10000 * 4, count); + } + + @Test + public void givenTreeMap_whenNavConcurrently_thenCountError() throws InterruptedException { + NavigableMap treeMap = new TreeMap<>(); + int count = countMapElementByPollingFirstEntry(treeMap, 10000, 4); + assertNotEquals(10000 * 4, count); + } + + private int countMapElementByPollingFirstEntry(NavigableMap navigableMap, int elementCount, int concurrencyLevel) throws InterruptedException { + for (int i = 0; i < elementCount * concurrencyLevel; i++) { + navigableMap.put(i, i); + } + AtomicInteger counter = new AtomicInteger(0); + ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel); + for (int j = 0; j < concurrencyLevel; j++) { + executorService.execute(() -> { + for (int i = 0; i < elementCount; i++) { + if (navigableMap.pollFirstEntry() != null) { + counter.incrementAndGet(); + } + } + }); + } + executorService.shutdown(); + executorService.awaitTermination(1, TimeUnit.MINUTES); + return counter.get(); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java new file mode 100644 index 0000000000..43cbb2d293 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java @@ -0,0 +1,60 @@ +package com.baeldung.java.concurrentmap; + +import org.junit.Test; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +public class ConcurretMapMemoryConsistencyManualTest { + + @Test + public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception { + Map map = new ConcurrentHashMap<>(); + List sumList = parallelSum100(map, 1000); + assertEquals(1, sumList.stream().distinct().count()); + long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertEquals(0, wrongResultCount); + } + + @Test + public void givenHashtable_whenSumParallel_thenCorrect() throws Exception { + Map map = new Hashtable<>(); + List sumList = parallelSum100(map, 1000); + assertEquals(1, sumList.stream().distinct().count()); + long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertEquals(0, wrongResultCount); + } + + @Test + public void givenHashMap_whenSumParallel_thenError() throws Exception { + Map map = new HashMap<>(); + List sumList = parallelSum100(map, 100); + assertNotEquals(1, sumList.stream().distinct().count()); + long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertTrue(wrongResultCount > 0); + } + + private List parallelSum100(Map map, int executionTimes) throws InterruptedException { + List sumList = new ArrayList<>(1000); + for (int i = 0; i < executionTimes; i++) { + map.put("test", 0); + ExecutorService executorService = Executors.newFixedThreadPool(4); + for (int j = 0; j < 10; j++) { + executorService.execute(() -> { + for (int k = 0; k < 10; k++) + map.computeIfPresent("test", (key, value) -> value + 1); + }); + } + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.SECONDS); + sumList.add(map.get("test")); + } + return sumList; + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java new file mode 100644 index 0000000000..f7a7bd5fe0 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.java.concurrentmodification; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.List; + +import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.util.Lists.newArrayList; + +public class ConcurrentModificationUnitTest { + @Test(expected = ConcurrentModificationException.class) + public void givenIterating_whenRemoving_thenThrowException() throws InterruptedException { + + List integers = newArrayList(1, 2, 3); + + for (Integer integer : integers) { + integers.remove(1); + } + } + + @Test + public void givenIterating_whenUsingIteratorRemove_thenNoError() throws InterruptedException { + + List integers = newArrayList(1, 2, 3); + + for (Iterator iterator = integers.iterator(); iterator.hasNext();) { + Integer integer = iterator.next(); + if(integer == 2) { + iterator.remove(); + } + } + + assertThat(integers).containsExactly(1, 3); + } + + @Test + public void givenIterating_whenUsingRemovalList_thenNoError() throws InterruptedException { + + List integers = newArrayList(1, 2, 3); + List toRemove = newArrayList(); + + for (Integer integer : integers) { + if(integer == 2) { + toRemove.add(integer); + } + } + integers.removeAll(toRemove); + + assertThat(integers).containsExactly(1, 3); + } + + @Test + public void whenUsingRemoveIf_thenRemoveElements() throws InterruptedException { + + Collection integers = newArrayList(1, 2, 3); + + integers.removeIf(i -> i == 2); + + assertThat(integers).containsExactly(1, 3); + } + + @Test + public void whenUsingStream_thenRemoveElements() { + Collection integers = newArrayList(1, 2, 3); + + List collected = integers + .stream() + .filter(i -> i != 2) + .map(Object::toString) + .collect(toList()); + + assertThat(collected).containsExactly("1", "3"); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/conversion/IterableStreamConversionTest.java b/core-java/src/test/java/com/baeldung/java/conversion/IterableStreamConversionTest.java new file mode 100644 index 0000000000..e2f6c6a500 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/conversion/IterableStreamConversionTest.java @@ -0,0 +1,31 @@ +package com.baeldung.java.conversion; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; + +public class IterableStreamConversionTest { + + @Test + public void givenIterable_whenConvertedToStream_thenNotNull() { + Iterable iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream"); + + Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), false)); + } + + @Test + public void whenConvertedToList_thenCorrect() { + Iterable iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream"); + + List result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList()); + + assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM")); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/map/MapTest.java b/core-java/src/test/java/com/baeldung/java/map/MapTest.java index a348869a5c..ce2710e176 100644 --- a/core-java/src/test/java/com/baeldung/java/map/MapTest.java +++ b/core-java/src/test/java/com/baeldung/java/map/MapTest.java @@ -201,8 +201,6 @@ public class MapTest { assertEquals("val1", rtnVal); } - - @Test public void whenCallsEqualsOnCollision_thenCorrect() { HashMap map = new HashMap<>(); @@ -311,13 +309,7 @@ public class MapTest { @Test public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() { - TreeMap map = new TreeMap<>(new Comparator() { - - @Override - public int compare(Integer o1, Integer o2) { - return o2 - o1; - } - }); + TreeMap map = new TreeMap<>(Comparator.reverseOrder()); map.put(3, "val"); map.put(2, "val"); map.put(1, "val"); @@ -335,7 +327,7 @@ public class MapTest { map.put(1, "val"); map.put(5, "val"); map.put(4, "val"); - + Integer highestKey = map.lastKey(); Integer lowestKey = map.firstKey(); Set keysLessThan3 = map.headMap(3).keySet(); 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/Java8FindAnyFindFirstTest.java b/core-java/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstTest.java new file mode 100644 index 0000000000..87f7eb1018 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstTest.java @@ -0,0 +1,46 @@ +package com.baeldung.java8; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class Java8FindAnyFindFirstTest { + + @Test + public void createStream_whenFindAnyResultIsPresent_thenCorrect() { + + List list = Arrays.asList("A", "B", "C", "D"); + + Optional result = list.stream().findAny(); + + assertTrue(result.isPresent()); + assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D"))); + } + + @Test + public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception { + List list = Arrays.asList(1, 2, 3, 4, 5); + Optional result = list.stream().parallel().filter(num -> num < 4).findAny(); + + assertTrue(result.isPresent()); + assertThat(result.get(), anyOf(is(1), is(2), is(3))); + } + + @Test + public void createStream_whenFindFirstResultIsPresent_thenCorrect() { + + List list = Arrays.asList("A", "B", "C", "D"); + + Optional result = list.stream().findFirst(); + + assertTrue(result.isPresent()); + assertThat(result.get(), is("A")); + } +} diff --git a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java new file mode 100644 index 0000000000..4452b4db9a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java @@ -0,0 +1,231 @@ +package com.baeldung.java8; + +import com.baeldung.java_8_features.groupingby.BlogPost; +import com.baeldung.java_8_features.groupingby.BlogPostType; +import org.junit.Test; + +import java.util.*; +import java.util.concurrent.ConcurrentMap; + +import static java.util.Comparator.comparingInt; +import static java.util.stream.Collectors.*; +import static org.junit.Assert.*; + +public class Java8GroupingByCollectorUnitTest { + + private static final List posts = Arrays.asList( + new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), + new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), + new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), + new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), + new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); + + @Test + public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() { + Map> postsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType)); + + assertEquals(2, postsPerType + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType + .get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType + .get(BlogPostType.REVIEW) + .size()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() { + Map postsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); + + assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS)); + assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE)); + assertEquals("Post titles: [Tech review 1, Tech review 2]", postsPerType.get(BlogPostType.REVIEW)); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() { + Map likesPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); + + assertEquals(50, likesPerType + .get(BlogPostType.NEWS) + .intValue()); + assertEquals(20, likesPerType + .get(BlogPostType.REVIEW) + .intValue()); + assertEquals(20, likesPerType + .get(BlogPostType.GUIDE) + .intValue()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() { + EnumMap> postsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); + + assertEquals(2, postsPerType + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType + .get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType + .get(BlogPostType.REVIEW) + .size()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() { + Map> postsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, toSet())); + + assertEquals(2, postsPerType + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType + .get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType + .get(BlogPostType.REVIEW) + .size()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() { + ConcurrentMap> postsPerType = posts + .parallelStream() + .collect(groupingByConcurrent(BlogPost::getType)); + + assertEquals(2, postsPerType + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType + .get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType + .get(BlogPostType.REVIEW) + .size()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() { + Map averageLikesPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); + + assertEquals(25, averageLikesPerType + .get(BlogPostType.NEWS) + .intValue()); + assertEquals(20, averageLikesPerType + .get(BlogPostType.GUIDE) + .intValue()); + assertEquals(10, averageLikesPerType + .get(BlogPostType.REVIEW) + .intValue()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() { + Map numberOfPostsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, counting())); + + assertEquals(2, numberOfPostsPerType + .get(BlogPostType.NEWS) + .intValue()); + assertEquals(1, numberOfPostsPerType + .get(BlogPostType.GUIDE) + .intValue()); + assertEquals(2, numberOfPostsPerType + .get(BlogPostType.REVIEW) + .intValue()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() { + Map> maxLikesPerPostType = posts + .stream() + .collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); + + assertTrue(maxLikesPerPostType + .get(BlogPostType.NEWS) + .isPresent()); + assertEquals(35, maxLikesPerPostType + .get(BlogPostType.NEWS) + .get() + .getLikes()); + + assertTrue(maxLikesPerPostType + .get(BlogPostType.GUIDE) + .isPresent()); + assertEquals(20, maxLikesPerPostType + .get(BlogPostType.GUIDE) + .get() + .getLikes()); + + assertTrue(maxLikesPerPostType + .get(BlogPostType.REVIEW) + .isPresent()); + assertEquals(15, maxLikesPerPostType + .get(BlogPostType.REVIEW) + .get() + .getLikes()); + } + + @Test + public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() { + Map>> map = posts + .stream() + .collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); + + assertEquals(1, map + .get("Author 1") + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, map + .get("Author 1") + .get(BlogPostType.GUIDE) + .size()); + assertEquals(1, map + .get("Author 1") + .get(BlogPostType.REVIEW) + .size()); + + assertEquals(1, map + .get("Author 2") + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, map + .get("Author 2") + .get(BlogPostType.REVIEW) + .size()); + assertNull(map + .get("Author 2") + .get(BlogPostType.GUIDE)); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() { + Map likeStatisticsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); + + IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS); + + assertEquals(2, newsLikeStatistics.getCount()); + assertEquals(50, newsLikeStatistics.getSum()); + assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001); + assertEquals(35, newsLikeStatistics.getMax()); + assertEquals(15, newsLikeStatistics.getMin()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersTest.java b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersTest.java new file mode 100644 index 0000000000..05e84e2dab --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersTest.java @@ -0,0 +1,46 @@ +package com.baeldung.java8.lambda.exceptions; + +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*; + +public class LambdaExceptionWrappersTest { + + private List integers; + + @Before + public void init() { + integers = Arrays.asList(3, 9, 7, 0, 10, 20); + } + + @Test + public void whenNoExceptionFromLambdaWrapper_thenSuccess() { + integers.forEach(lambdaWrapper(i -> System.out.println(50 / i))); + } + + @Test + public void whenNoExceptionFromConsumerWrapper_thenSuccess() { + integers.forEach(consumerWrapper(i -> System.out.println(50 / i), ArithmeticException.class)); + } + + @Test(expected = RuntimeException.class) + public void whenExceptionFromThrowingConsumerWrapper_thenSuccess() { + integers.forEach(throwingConsumerWrapper(i -> writeToFile(i))); + } + + @Test + public void whenNoExceptionFromHandlingConsumerWrapper_thenSuccess() { + integers.forEach(handlingConsumerWrapper(i -> writeToFile(i), IOException.class)); + } + + private void writeToFile(Integer i) throws IOException { + if (i == 0) { + throw new IOException(); // mock IOException + } + } +} 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..9b6f61361a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/scripting/NashornTest.java @@ -0,0 +1,109 @@ +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/com/baeldung/strategy/StrategyDesignPatternUnitTest.java b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java new file mode 100644 index 0000000000..7ca1d000be --- /dev/null +++ b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.strategy; + +import org.junit.Test; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; + +import static com.baeldung.strategy.Discounter.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class StrategyDesignPatternUnitTest { + @Test + public void shouldDivideByTwo_WhenApplyingStaffDiscounter() { + Discounter staffDiscounter = new EasterDiscounter(); + + final BigDecimal discountedValue = staffDiscounter + .apply(BigDecimal.valueOf(100)); + + assertThat(discountedValue) + .isEqualByComparingTo(BigDecimal.valueOf(50)); + } + + @Test + public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() { + Discounter staffDiscounter = new Discounter() { + @Override + public BigDecimal apply( BigDecimal amount) { + return amount.multiply(BigDecimal.valueOf(0.5)); + } + }; + + final BigDecimal discountedValue = staffDiscounter + .apply(BigDecimal.valueOf(100)); + + assertThat(discountedValue) + .isEqualByComparingTo(BigDecimal.valueOf(50)); + } + + @Test + public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithLamda() { + Discounter staffDiscounter = amount -> amount.multiply(BigDecimal.valueOf(0.5)); + + final BigDecimal discountedValue = staffDiscounter + .apply(BigDecimal.valueOf(100)); + + assertThat(discountedValue) + .isEqualByComparingTo(BigDecimal.valueOf(50)); + } + + @Test + public void shouldApplyAllDiscounts() { + List discounters = Arrays.asList(christmas(), newYear(), easter()); + + BigDecimal amount = BigDecimal.valueOf(100); + + final Discounter combinedDiscounter = discounters + .stream() + .reduce(v -> v, Discounter::combine); + + combinedDiscounter.apply(amount); + } + + @Test + public void shouldChainDiscounters() { + final Function combinedDiscounters = Discounter + .christmas() + .andThen(newYear()); + + combinedDiscounters.apply(BigDecimal.valueOf(100)); + } +} diff --git a/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java b/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java new file mode 100644 index 0000000000..19d945f836 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java @@ -0,0 +1,38 @@ +package com.baeldung.stream; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.baeldung.streamApi.JoinerSplitter; + +public class JoinerSplitterTest { + + @Test + public void provided_array_convert_to_stream_and_convert_to_string() { + String[] programming_languages = {"java", "python", "nodejs", "ruby"}; + String expectation = "java,python,nodejs,ruby"; + + String result = JoinerSplitter.join(programming_languages); + assertEquals(result, expectation); + } + + @Test + public void provided_list_convert_to_stream_and_convert_to_list() { + String programming_languages = "java,python,nodejs,ruby"; + + List expectation = new ArrayList(); + expectation.add("java"); + expectation.add("python"); + expectation.add("nodejs"); + expectation.add("ruby"); + + List result = JoinerSplitter.split(programming_languages); + + assertEquals(result, expectation); + } + +} diff --git a/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java b/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java new file mode 100644 index 0000000000..1c5a261eea --- /dev/null +++ b/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java @@ -0,0 +1,72 @@ +package com.baeldung.weakhashmap; + + +import org.junit.Test; + +import java.util.WeakHashMap; +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; +import static org.junit.Assert.assertTrue; + +public class WeakHashMapTest { + + @Test + public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() { + //given + WeakHashMap map = new WeakHashMap<>(); + BigImage bigImage = new BigImage("image_id"); + UniqueImageName imageName = new UniqueImageName("name_of_big_image"); + + map.put(imageName, bigImage); + assertTrue(map.containsKey(imageName)); + + //when big image key is not reference anywhere + imageName = null; + System.gc(); + + //then GC will finally reclaim that object + await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty); + } + + @Test + public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() { + //given + WeakHashMap map = new WeakHashMap<>(); + BigImage bigImageFirst = new BigImage("foo"); + UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image"); + + BigImage bigImageSecond = new BigImage("foo_2"); + UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2"); + + map.put(imageNameFirst, bigImageFirst); + map.put(imageNameSecond, bigImageSecond); + assertTrue(map.containsKey(imageNameFirst)); + assertTrue(map.containsKey(imageNameSecond)); + + //when + imageNameFirst = null; + System.gc(); + + //then + await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1); + await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond)); + } + + + class BigImage { + public final String imageId; + + BigImage(String imageId) { + this.imageId = imageId; + } + } + + class UniqueImageName { + public final String imageName; + + UniqueImageName(String imageName) { + this.imageName = imageName; + } + } +} diff --git a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java index 4febe7c9fc..08f98025c3 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java @@ -1,12 +1,12 @@ package org.baeldung.java; -import java.nio.charset.Charset; -import java.util.Random; - import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.math3.random.RandomDataGenerator; import org.junit.Test; +import java.nio.charset.Charset; +import java.util.Random; + public class JavaRandomUnitTest { // tests - random long @@ -164,7 +164,7 @@ public class JavaRandomUnitTest { final int targetStringLength = 10; final StringBuilder buffer = new StringBuilder(targetStringLength); for (int i = 0; i < targetStringLength; i++) { - final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); + final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1)); buffer.append((char) randomLimitedInt); } final String generatedString = buffer.toString(); 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..317d81fae7 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/collections/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split) +- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) diff --git a/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/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java new file mode 100644 index 0000000000..c2eb1cff5d --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java @@ -0,0 +1,38 @@ +package org.baeldung.java.streams; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ForkJoinPool; +import java.util.stream.Collectors; +import java.util.stream.LongStream; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class ThreadPoolInParallelStreamTest { + + @Test + public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException { + long firstNum = 1; + long lastNum = 1_000_000; + + List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList()); + + ForkJoinPool customThreadPool = new ForkJoinPool(4); + long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get(); + + assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); + } + + @Test + public void givenList_whenCallingParallelStream_shouldBeParallelStream() { + List aList = new ArrayList<>(); + Stream parallelStream = aList.parallelStream(); + + assertTrue(parallelStream.isParallel()); + } +} 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/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java index 16e1876719..8f459e364f 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java @@ -3,7 +3,7 @@ package com.baeldung.couchbase.async; public interface CouchbaseEntity { String getId(); - + void setId(String id); - + } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java index 32ed2ebbe4..f1135a32a2 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java @@ -8,26 +8,27 @@ public class Person implements CouchbaseEntity { private String type; private String name; private String homeTown; - - Person() {} - + + Person() { + } + public Person(Builder b) { this.id = b.id; this.type = b.type; this.name = b.name; this.homeTown = b.homeTown; } - + @Override public String getId() { return id; } - + @Override public void setId(String id) { this.id = id; } - + public String getType() { return type; } @@ -39,19 +40,19 @@ public class Person implements CouchbaseEntity { public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public String getHomeTown() { return homeTown; } - + public void setHomeTown(String homeTown) { this.homeTown = homeTown; } - + public static class Builder { private String id; private String type; @@ -61,16 +62,16 @@ public class Person implements CouchbaseEntity { public static Builder newInstance() { return new Builder(); } - + public Person build() { return new Person(this); } - + public Builder id(String id) { this.id = id; return this; } - + public Builder type(String type) { this.type = type; return this; diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java index b2ef985725..407bc7ee1c 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java @@ -13,9 +13,7 @@ import com.baeldung.couchbase.async.service.BucketService; public class PersonCrudService extends AbstractCrudService { @Autowired - public PersonCrudService( - @Qualifier("TutorialBucketService") BucketService bucketService, - PersonDocumentConverter converter) { + public PersonCrudService(@Qualifier("TutorialBucketService") BucketService bucketService, PersonDocumentConverter converter) { super(bucketService, converter); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java index 8646cf247a..0f08679ace 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java @@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter { @Override public JsonDocument toDocument(Person p) { - JsonObject content = JsonObject.empty() - .put("type", "Person") - .put("name", p.getName()) - .put("homeTown", p.getHomeTown()); + JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown()); return JsonDocument.create(p.getId(), content); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java index 926cd7f4e8..7cbc3625db 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java @@ -10,19 +10,18 @@ public class RegistrationService { @Autowired private PersonCrudService crud; - + public void registerNewPerson(String name, String homeTown) { Person person = new Person(); person.setName(name); person.setHomeTown(homeTown); crud.create(person); } - + public Person findRegistrant(String id) { - try{ + try { return crud.read(id); - } - catch(CouchbaseException e) { + } catch (CouchbaseException e) { return crud.readFromReplica(id); } } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java index cbc03cbcda..1180ea00a6 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java @@ -11,9 +11,9 @@ public abstract class AbstractBucketService implements BucketService { protected void openBucket() { bucket = clusterService.openBucket(getBucketName(), getBucketPassword()); } - + protected abstract String getBucketName(); - + protected abstract String getBucketPassword(); public AbstractBucketService(ClusterService clusterService) { @@ -24,4 +24,4 @@ public abstract class AbstractBucketService implements BucketService { public Bucket getBucket() { return bucket; } - } +} diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java index 861e2404e5..089cc55d5d 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java @@ -40,7 +40,7 @@ public abstract class AbstractCrudService implements @Override public void create(T t) { - if(t.getId() == null) { + if (t.getId() == null) { t.setId(UUID.randomUUID().toString()); } JsonDocument doc = converter.toDocument(t); @@ -73,18 +73,15 @@ public abstract class AbstractCrudService implements @Override public List readBulk(Iterable ids) { final AsyncBucket asyncBucket = bucket.async(); - Observable asyncOperation = Observable - .from(ids) - .flatMap(new Func1>() { - public Observable call(String key) { - return asyncBucket.get(key); - } - }); + Observable asyncOperation = Observable.from(ids).flatMap(new Func1>() { + public Observable call(String key) { + return asyncBucket.get(key); + } + }); final List items = new ArrayList(); try { - asyncOperation.toBlocking() - .forEach(new Action1() { + asyncOperation.toBlocking().forEach(new Action1() { public void call(JsonDocument doc) { T item = converter.fromDocument(doc); items.add(item); @@ -100,72 +97,42 @@ public abstract class AbstractCrudService implements @Override public void createBulk(Iterable items) { final AsyncBucket asyncBucket = bucket.async(); - Observable - .from(items) - .flatMap(new Func1>() { + Observable.from(items).flatMap(new Func1>() { @SuppressWarnings("unchecked") @Override public Observable call(final T t) { - if(t.getId() == null) { + if (t.getId() == null) { t.setId(UUID.randomUUID().toString()); } JsonDocument doc = converter.toDocument(t); - return asyncBucket.insert(doc) - .retryWhen(RetryBuilder - .anyOf(BackpressureException.class) - .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) - .max(10) - .build()); + return asyncBucket.insert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build()); } - }) - .last() - .toBlocking() - .single(); + }).last().toBlocking().single(); } @Override public void updateBulk(Iterable items) { final AsyncBucket asyncBucket = bucket.async(); - Observable - .from(items) - .flatMap(new Func1>() { + Observable.from(items).flatMap(new Func1>() { @SuppressWarnings("unchecked") @Override public Observable call(final T t) { JsonDocument doc = converter.toDocument(t); - return asyncBucket.upsert(doc) - .retryWhen(RetryBuilder - .anyOf(BackpressureException.class) - .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) - .max(10) - .build()); + return asyncBucket.upsert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build()); } - }) - .last() - .toBlocking() - .single(); + }).last().toBlocking().single(); } @Override public void deleteBulk(Iterable ids) { final AsyncBucket asyncBucket = bucket.async(); - Observable - .from(ids) - .flatMap(new Func1>() { + Observable.from(ids).flatMap(new Func1>() { @SuppressWarnings("unchecked") @Override public Observable call(String key) { - return asyncBucket.remove(key) - .retryWhen(RetryBuilder - .anyOf(BackpressureException.class) - .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) - .max(10) - .build()); + return asyncBucket.remove(key).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build()); } - }) - .last() - .toBlocking() - .single(); + }).last().toBlocking().single(); } @Override diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java index ee67405b12..7bf891244f 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java @@ -3,6 +3,6 @@ package com.baeldung.couchbase.async.service; import com.couchbase.client.java.Bucket; public interface ClusterService { - + Bucket openBucket(String name, String password); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java index 7ce75d21f5..e708922988 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java @@ -18,7 +18,7 @@ public class ClusterServiceImpl implements ClusterService { private Cluster cluster; private Map buckets = new ConcurrentHashMap<>(); - + @PostConstruct private void init() { CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create(); @@ -27,7 +27,7 @@ public class ClusterServiceImpl implements ClusterService { @Override synchronized public Bucket openBucket(String name, String password) { - if(!buckets.containsKey(name)) { + if (!buckets.containsKey(name)) { Bucket bucket = cluster.openBucket(name, password); buckets.put(name, bucket); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java index 85e14a87ce..193e91016a 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java @@ -5,6 +5,6 @@ import com.couchbase.client.java.document.JsonDocument; public interface JsonDocumentConverter { JsonDocument toDocument(T t); - + T fromDocument(JsonDocument doc); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java index 2cb9e1f4f7..e7bddc6442 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java @@ -14,40 +14,32 @@ import com.couchbase.client.java.env.CouchbaseEnvironment; import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; public class CodeSnippets { - + static Cluster loadClusterWithDefaultEnvironment() { return CouchbaseCluster.create("localhost"); } static Cluster loadClusterWithCustomEnvironment() { - CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder() - .connectTimeout(10000) - .kvTimeout(3000) - .build(); + CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(10000).kvTimeout(3000).build(); return CouchbaseCluster.create(env, "localhost"); } - + static Bucket loadDefaultBucketWithBlankPassword(Cluster cluster) { return cluster.openBucket(); } - + static Bucket loadBaeldungBucket(Cluster cluster) { return cluster.openBucket("baeldung", ""); } static JsonDocument insertExample(Bucket bucket) { - JsonObject content = JsonObject.empty() - .put("name", "John Doe") - .put("type", "Person") - .put("email", "john.doe@mydomain.com") - .put("homeTown", "Chicago") - ; + JsonObject content = JsonObject.empty().put("name", "John Doe").put("type", "Person").put("email", "john.doe@mydomain.com").put("homeTown", "Chicago"); String id = UUID.randomUUID().toString(); JsonDocument document = JsonDocument.create(id, content); JsonDocument inserted = bucket.insert(document); return inserted; } - + static JsonDocument retrieveAndUpsertExample(Bucket bucket, String id) { JsonDocument document = bucket.get(id); JsonObject content = document.content(); @@ -55,7 +47,7 @@ public class CodeSnippets { JsonDocument upserted = bucket.upsert(document); return upserted; } - + static JsonDocument replaceExample(Bucket bucket, String id) { JsonDocument document = bucket.get(id); JsonObject content = document.content(); @@ -63,30 +55,29 @@ public class CodeSnippets { JsonDocument replaced = bucket.replace(document); return replaced; } - + static JsonDocument removeExample(Bucket bucket, String id) { JsonDocument removed = bucket.remove(id); return removed; } - + static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) { - try{ + try { return bucket.get(id); - } - catch(CouchbaseException e) { + } catch (CouchbaseException e) { List list = bucket.getFromReplica(id, ReplicaMode.FIRST); - if(!list.isEmpty()) { + if (!list.isEmpty()) { return list.get(0); } } return null; } - + static JsonDocument getLatestReplicaVersion(Bucket bucket, String id) { long maxCasValue = -1; JsonDocument latest = null; - for(JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) { - if(replica.cas() > maxCasValue) { + for (JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) { + if (replica.cas() > maxCasValue) { latest = replica; maxCasValue = replica.cas(); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java index 0348ba1e5f..403b7c8d3b 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java @@ -6,24 +6,25 @@ public class Person { private String type; private String name; private String homeTown; - - Person() {} - + + Person() { + } + public Person(Builder b) { this.id = b.id; this.type = b.type; this.name = b.name; this.homeTown = b.homeTown; } - + public String getId() { return id; } - + public void setId(String id) { this.id = id; } - + public String getType() { return type; } @@ -35,19 +36,19 @@ public class Person { public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public String getHomeTown() { return homeTown; } - + public void setHomeTown(String homeTown) { this.homeTown = homeTown; } - + public static class Builder { private String id; private String type; @@ -57,16 +58,16 @@ public class Person { public static Builder newInstance() { return new Builder(); } - + public Person build() { return new Person(this); } - + public Builder id(String id) { this.id = id; return this; } - + public Builder type(String type) { this.type = type; return this; diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java index de035f1d2c..163f6417ca 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java @@ -16,15 +16,15 @@ import com.couchbase.client.java.document.JsonDocument; @Service public class PersonCrudService implements CrudService { - + @Autowired private TutorialBucketService bucketService; - + @Autowired private PersonDocumentConverter converter; - + private Bucket bucket; - + @PostConstruct private void init() { bucket = bucketService.getBucket(); @@ -32,7 +32,7 @@ public class PersonCrudService implements CrudService { @Override public void create(Person person) { - if(person.getId() == null) { + if (person.getId() == null) { person.setId(UUID.randomUUID().toString()); } JsonDocument document = converter.toDocument(person); diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java index 030c9fde27..71108d16dd 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java @@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter { @Override public JsonDocument toDocument(Person p) { - JsonObject content = JsonObject.empty() - .put("type", "Person") - .put("name", p.getName()) - .put("homeTown", p.getHomeTown()); + JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown()); return JsonDocument.create(p.getId(), content); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java index 5ffe7acf24..cad3bdd5a5 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java @@ -10,19 +10,18 @@ public class RegistrationService { @Autowired private PersonCrudService crud; - + public void registerNewPerson(String name, String homeTown) { Person person = new Person(); person.setName(name); person.setHomeTown(homeTown); crud.create(person); } - + public Person findRegistrant(String id) { - try{ + try { return crud.read(id); - } - catch(CouchbaseException e) { + } catch (CouchbaseException e) { return crud.readFromReplica(id); } } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java index 97ff1e4fd5..1ea9c72114 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java @@ -5,5 +5,5 @@ import com.couchbase.client.java.Bucket; public interface BucketService { Bucket getBucket(); - + } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java index a8543fbd91..da7a10141f 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java @@ -7,11 +7,11 @@ import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; public interface ClusterService { - + Bucket openBucket(String name, String password); - + List getDocuments(Bucket bucket, Iterable keys); - + List getDocumentsAsync(AsyncBucket bucket, Iterable keys); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java index 3499fa956e..1cceb11ccc 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java @@ -29,7 +29,7 @@ public class ClusterServiceImpl implements ClusterService { private Cluster cluster; private Map buckets = new ConcurrentHashMap<>(); - + @PostConstruct private void init() { CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create(); @@ -38,7 +38,7 @@ public class ClusterServiceImpl implements ClusterService { @Override synchronized public Bucket openBucket(String name, String password) { - if(!buckets.containsKey(name)) { + if (!buckets.containsKey(name)) { Bucket bucket = cluster.openBucket(name, password); buckets.put(name, bucket); } @@ -48,9 +48,9 @@ public class ClusterServiceImpl implements ClusterService { @Override public List getDocuments(Bucket bucket, Iterable keys) { List docs = new ArrayList<>(); - for(String key : keys) { + for (String key : keys) { JsonDocument doc = bucket.get(key); - if(doc != null) { + if (doc != null) { docs.add(doc); } } @@ -59,18 +59,15 @@ public class ClusterServiceImpl implements ClusterService { @Override public List getDocumentsAsync(final AsyncBucket asyncBucket, Iterable keys) { - Observable asyncBulkGet = Observable - .from(keys) - .flatMap(new Func1>() { - public Observable call(String key) { - return asyncBucket.get(key); - } - }); + Observable asyncBulkGet = Observable.from(keys).flatMap(new Func1>() { + public Observable call(String key) { + return asyncBucket.get(key); + } + }); final List docs = new ArrayList<>(); try { - asyncBulkGet.toBlocking() - .forEach(new Action1() { + asyncBulkGet.toBlocking().forEach(new Action1() { public void call(JsonDocument doc) { docs.add(doc); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java index f683b9f562..5b12af7003 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java @@ -3,14 +3,14 @@ package com.baeldung.couchbase.spring.service; public interface CrudService { void create(T t); - + T read(String id); - + T readFromReplica(String id); - + void update(T t); - + void delete(String id); - + boolean exists(String id); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java index cf4861fbeb..f63bb8691b 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java @@ -5,6 +5,6 @@ import com.couchbase.client.java.document.JsonDocument; public interface JsonDocumentConverter { JsonDocument toDocument(T t); - + T fromDocument(JsonDocument doc); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java index 8a28deb1d6..b91c131912 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java @@ -14,15 +14,15 @@ public class TutorialBucketService implements BucketService { @Autowired private ClusterService couchbase; - + private Bucket bucket; - + @PostConstruct private void init() { bucket = couchbase.openBucket("baeldung-tutorial", ""); } - @Override + @Override public Bucket getBucket() { return bucket; } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java index 6afdfe04bd..efc3e9957f 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java @@ -4,6 +4,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackages={"com.baeldung.couchbase.async"}) +@ComponentScan(basePackages = { "com.baeldung.couchbase.async" }) public class AsyncIntegrationTestConfig { } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java index 5907a4cc63..565aaed5da 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java @@ -29,10 +29,10 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { @Autowired @Qualifier("TutorialBucketService") private BucketService bucketService; - + @Autowired private PersonDocumentConverter converter; - + private Bucket bucket; @PostConstruct @@ -42,182 +42,175 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { @Test public final void givenRandomPerson_whenCreate_thenPersonPersisted() { - //create person + // create person Person person = randomPerson(); personService.create(person); - - //check results + + // check results assertNotNull(person.getId()); assertNotNull(bucket.get(person.getId())); - - //cleanup + + // cleanup bucket.remove(person.getId()); } @Test public final void givenId_whenRead_thenReturnsPerson() { - //create and insert person document + // create and insert person document String id = insertRandomPersonDocument().id(); - //read person and check results + // read person and check results assertNotNull(personService.read(id)); - - //cleanup + + // cleanup bucket.remove(id); } @Test public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() { - //create and insert person document + // create and insert person document JsonDocument doc = insertRandomPersonDocument(); - - //update person + + // update person Person expected = converter.fromDocument(doc); String updatedHomeTown = RandomStringUtils.randomAlphabetic(12); expected.setHomeTown(updatedHomeTown); personService.update(expected); - - //check results + + // check results JsonDocument actual = bucket.get(expected.getId()); assertNotNull(actual); assertNotNull(actual.content()); assertEquals(expected.getHomeTown(), actual.content().getString("homeTown")); - - //cleanup + + // cleanup bucket.remove(expected.getId()); } @Test public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() { - //create and insert person document + // create and insert person document String id = insertRandomPersonDocument().id(); - //delete person and check results + // delete person and check results personService.delete(id); assertNull(bucket.get(id)); } - + @Test public final void givenIds_whenReadBulk_thenReturnsOnlyPersonsWithMatchingIds() { List ids = new ArrayList<>(); - - //add some person documents - for(int i=0; i<5; i++) { + + // add some person documents + for (int i = 0; i < 5; i++) { ids.add(insertRandomPersonDocument().id()); } - - //perform bulk read + + // perform bulk read List persons = personService.readBulk(ids); - - //check results - for(Person person : persons) { + + // check results + for (Person person : persons) { assertTrue(ids.contains(person.getId())); } - - //cleanup - for(String id : ids) { + + // cleanup + for (String id : ids) { bucket.remove(id); - } + } } - + @Test public final void givenPersons_whenInsertBulk_thenPersonsAreInserted() { - - //create some persons + + // create some persons List persons = new ArrayList<>(); - for(int i=0; i<5; i++) { + for (int i = 0; i < 5; i++) { persons.add(randomPerson()); } - //perform bulk insert + // perform bulk insert personService.createBulk(persons); - - //check results - for(Person person : persons) { + + // check results + for (Person person : persons) { assertNotNull(bucket.get(person.getId())); } - - //cleanup - for(Person person : persons) { + + // cleanup + for (Person person : persons) { bucket.remove(person.getId()); - } + } } @Test public final void givenPersons_whenUpdateBulk_thenPersonsAreUpdated() { - + List ids = new ArrayList<>(); - - //add some person documents - for(int i=0; i<5; i++) { + + // add some person documents + for (int i = 0; i < 5; i++) { ids.add(insertRandomPersonDocument().id()); } - //load persons from Couchbase + // load persons from Couchbase List persons = new ArrayList<>(); - for(String id : ids) { + for (String id : ids) { persons.add(converter.fromDocument(bucket.get(id))); } - //modify persons - for(Person person : persons) { + // modify persons + for (Person person : persons) { person.setHomeTown(RandomStringUtils.randomAlphabetic(10)); } - - //perform bulk update + + // perform bulk update personService.updateBulk(persons); - - //check results - for(Person person : persons) { + + // check results + for (Person person : persons) { JsonDocument doc = bucket.get(person.getId()); assertEquals(person.getName(), doc.content().getString("name")); assertEquals(person.getHomeTown(), doc.content().getString("homeTown")); } - - //cleanup - for(String id : ids) { + + // cleanup + for (String id : ids) { bucket.remove(id); - } + } } - + @Test public void givenIds_whenDeleteBulk_thenPersonsAreDeleted() { - + List ids = new ArrayList<>(); - - //add some person documents - for(int i=0; i<5; i++) { + + // add some person documents + for (int i = 0; i < 5; i++) { ids.add(insertRandomPersonDocument().id()); } - - //perform bulk delete + + // perform bulk delete personService.deleteBulk(ids); - - //check results - for(String id : ids) { + + // check results + for (String id : ids) { assertNull(bucket.get(id)); - } + } } - + private JsonDocument insertRandomPersonDocument() { Person expected = randomPersonWithId(); JsonDocument doc = converter.toDocument(expected); - return bucket.insert(doc); + return bucket.insert(doc); } private Person randomPerson() { - return Person.Builder.newInstance() - .name(RandomStringUtils.randomAlphabetic(10)) - .homeTown(RandomStringUtils.randomAlphabetic(10)) - .build(); + return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); } private Person randomPersonWithId() { - return Person.Builder.newInstance() - .id(UUID.randomUUID().toString()) - .name(RandomStringUtils.randomAlphabetic(10)) - .homeTown(RandomStringUtils.randomAlphabetic(10)) - .build(); + return Person.Builder.newInstance().id(UUID.randomUUID().toString()).name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); } } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java index 08e3728c77..d0db5d37a3 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java @@ -22,9 +22,9 @@ public class ClusterServiceIntegrationTest extends AsyncIntegrationTest { @Autowired private ClusterService couchbaseService; - + private Bucket defaultBucket; - + @Test public void whenOpenBucket_thenBucketIsNotNull() throws Exception { defaultBucket = couchbaseService.openBucket("default", ""); diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java index ac71911b9b..d814b31a07 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java @@ -4,6 +4,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackages={"com.baeldung.couchbase.spring"}) +@ComponentScan(basePackages = { "com.baeldung.couchbase.spring" }) public class IntegrationTestConfig { } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java index b3fadae6ca..ec15be1acc 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java @@ -24,7 +24,7 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest { @PostConstruct private void init() { clarkKent = personService.read(CLARK_KENT_ID); - if(clarkKent == null) { + if (clarkKent == null) { clarkKent = buildClarkKent(); personService.create(clarkKent); } @@ -50,7 +50,7 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest { personService.create(expected); String updatedHomeTown = RandomStringUtils.randomAlphabetic(12); expected.setHomeTown(updatedHomeTown); - personService.update(expected); + personService.update(expected); Person actual = personService.read(expected.getId()); assertNotNull(actual); assertEquals(expected.getHomeTown(), actual.getHomeTown()); @@ -66,17 +66,10 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest { } private Person buildClarkKent() { - return Person.Builder.newInstance() - .id(CLARK_KENT_ID) - .name(CLARK_KENT) - .homeTown(SMALLVILLE) - .build(); + return Person.Builder.newInstance().id(CLARK_KENT_ID).name(CLARK_KENT).homeTown(SMALLVILLE).build(); } private Person randomPerson() { - return Person.Builder.newInstance() - .name(RandomStringUtils.randomAlphabetic(10)) - .homeTown(RandomStringUtils.randomAlphabetic(10)) - .build(); + return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); } } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java index f3ee4585a3..ead247dfbc 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java @@ -21,9 +21,9 @@ public class ClusterServiceIntegrationTest extends IntegrationTest { @Autowired private ClusterService couchbaseService; - + private Bucket defaultBucket; - + @Test public void whenOpenBucket_thenBucketIsNotNull() throws Exception { defaultBucket = couchbaseService.openBucket("default", ""); 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/deltaspike/src/main/java/baeldung/data/MemberRepository.java b/deltaspike/src/main/java/baeldung/data/MemberRepository.java index 56a4a4e634..220388bcf0 100644 --- a/deltaspike/src/main/java/baeldung/data/MemberRepository.java +++ b/deltaspike/src/main/java/baeldung/data/MemberRepository.java @@ -35,9 +35,6 @@ public abstract class MemberRepository extends AbstractEntityRepository findAllOrderedByNameWithQueryDSL() { final QMember member = QMember.member; - return jpaQuery() - .from(member) - .orderBy(member.email.asc()) - .list(member); + return jpaQuery().from(member).orderBy(member.email.asc()).list(member); } } diff --git a/deltaspike/src/main/java/baeldung/service/MemberRegistration.java b/deltaspike/src/main/java/baeldung/service/MemberRegistration.java index ec65471622..9396e550d5 100644 --- a/deltaspike/src/main/java/baeldung/service/MemberRegistration.java +++ b/deltaspike/src/main/java/baeldung/service/MemberRegistration.java @@ -64,7 +64,6 @@ public class MemberRegistration { } } - public void register(Member member) throws Exception { log.info("Registering " + member.getName()); validateMember(member); diff --git a/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java b/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java index 0270d2d164..7014d066d2 100644 --- a/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java +++ b/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java @@ -41,27 +41,13 @@ import org.junit.runner.RunWith; public class MemberRegistrationTest { @Deployment public static Archive createTestArchive() { - File[] files = Maven.resolver().loadPomFromFile("pom.xml") - .importRuntimeDependencies().resolve().withTransitivity().asFile(); + File[] files = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile(); return ShrinkWrap.create(WebArchive.class, "test.war") - .addClasses( - EntityManagerProducer.class, - Member.class, - MemberRegistration.class, - MemberRepository.class, - Resources.class, - QueryDslRepositoryExtension.class, - QueryDslSupport.class, - SecondaryPersistenceUnit.class, - SecondaryEntityManagerProducer.class, - SecondaryEntityManagerResolver.class) - .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml") - .addAsResource("META-INF/apache-deltaspike.properties") - .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") - .addAsWebInfResource("test-ds.xml") - .addAsWebInfResource("test-secondary-ds.xml") - .addAsLibraries(files); + .addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class, + SecondaryEntityManagerProducer.class, SecondaryEntityManagerResolver.class) + .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml").addAsResource("META-INF/apache-deltaspike.properties").addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml").addAsWebInfResource("test-ds.xml") + .addAsWebInfResource("test-secondary-ds.xml").addAsLibraries(files); } @Inject diff --git a/disruptor/README.md b/disruptor/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/disruptor/pom.xml b/disruptor/pom.xml new file mode 100644 index 0000000000..7f2c78c9b0 --- /dev/null +++ b/disruptor/pom.xml @@ -0,0 +1,251 @@ + + 4.0.0 + com.baeldung + disruptor + 0.1.0-SNAPSHOT + jar + + disruptor + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + com.lmax + disruptor + ${disruptor.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} + + + + + + org.hamcrest + hamcrest-all + 1.3 + test + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + + + disruptor + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + libs/ + org.baeldung.executable.ExecutableMavenJar + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + + + org.baeldung.executable.ExecutableMavenJar + + + + jar-with-dependencies + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + shade + + + true + + + org.baeldung.executable.ExecutableMavenJar + + + + + + + + + com.jolira + onejar-maven-plugin + + + + org.baeldung.executable.ExecutableMavenJar + true + ${project.build.finalName}-onejar.${project.packaging} + + + one-jar + + + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + + + json + + + + + + + + + + + 1.7.21 + 1.1.7 + + + 3.5 + 3.3.6 + + + 1.3 + 4.12 + 1.10.19 + 6.10 + 3.6.1 + + + 3.6.0 + 2.19.1 + + + + \ No newline at end of file diff --git a/disruptor/src/main/java/com/baeldung/disruptor/DelayedMultiEventProducer.java b/disruptor/src/main/java/com/baeldung/disruptor/DelayedMultiEventProducer.java new file mode 100644 index 0000000000..bb9f91b99f --- /dev/null +++ b/disruptor/src/main/java/com/baeldung/disruptor/DelayedMultiEventProducer.java @@ -0,0 +1,34 @@ +package com.baeldung.disruptor; + +import com.lmax.disruptor.RingBuffer; + +public class DelayedMultiEventProducer implements EventProducer { + + @Override + public void startProducing(final RingBuffer ringBuffer, final int count) { + final Runnable simpleProducer = () -> produce(ringBuffer, count, false); + final Runnable delayedProducer = () -> produce(ringBuffer, count, true); + new Thread(simpleProducer).start(); + new Thread(delayedProducer).start(); + } + + private void produce(final RingBuffer ringBuffer, final int count, final boolean addDelay) { + for (int i = 0; i < count; i++) { + final long seq = ringBuffer.next(); + final ValueEvent valueEvent = ringBuffer.get(seq); + valueEvent.setValue(i); + ringBuffer.publish(seq); + if (addDelay) { + addDelay(); + } + } + } + + private void addDelay() { + try { + Thread.sleep(1000); + } catch (InterruptedException interruptedException) { + // No-Op lets swallow it + } + } +} diff --git a/disruptor/src/main/java/com/baeldung/disruptor/EventConsumer.java b/disruptor/src/main/java/com/baeldung/disruptor/EventConsumer.java new file mode 100644 index 0000000000..20d72ff9be --- /dev/null +++ b/disruptor/src/main/java/com/baeldung/disruptor/EventConsumer.java @@ -0,0 +1,13 @@ +package com.baeldung.disruptor; + +import com.lmax.disruptor.EventHandler; + +/** + * Consumer that consumes event from ring buffer. + */ +public interface EventConsumer { + /** + * One or more event handler to handle event from ring buffer. + */ + public EventHandler[] getEventHandler(); +} diff --git a/disruptor/src/main/java/com/baeldung/disruptor/EventProducer.java b/disruptor/src/main/java/com/baeldung/disruptor/EventProducer.java new file mode 100644 index 0000000000..ede1aef8bf --- /dev/null +++ b/disruptor/src/main/java/com/baeldung/disruptor/EventProducer.java @@ -0,0 +1,15 @@ +package com.baeldung.disruptor; + +import com.lmax.disruptor.RingBuffer; + +/** + * Producer that produces event for ring buffer. + */ +public interface EventProducer { + /** + * Start the producer that would start producing the values. + * @param ringBuffer + * @param count + */ + public void startProducing(final RingBuffer ringBuffer, final int count); +} diff --git a/disruptor/src/main/java/com/baeldung/disruptor/MultiEventPrintConsumer.java b/disruptor/src/main/java/com/baeldung/disruptor/MultiEventPrintConsumer.java new file mode 100644 index 0000000000..f75063adcd --- /dev/null +++ b/disruptor/src/main/java/com/baeldung/disruptor/MultiEventPrintConsumer.java @@ -0,0 +1,23 @@ +package com.baeldung.disruptor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.lmax.disruptor.EventHandler; + +public class MultiEventPrintConsumer implements EventConsumer { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + @SuppressWarnings("unchecked") + public EventHandler[] getEventHandler() { + final EventHandler eventHandler = (event, sequence, endOfBatch) -> print(event.getValue(), sequence); + final EventHandler otherEventHandler = (event, sequence, endOfBatch) -> print(event.getValue(), sequence); + return new EventHandler[] { eventHandler, otherEventHandler }; + } + + private void print(final int id, final long sequenceId) { + logger.info("Id is " + id + " sequence id that was used is " + sequenceId); + } +} diff --git a/disruptor/src/main/java/com/baeldung/disruptor/SingleEventPrintConsumer.java b/disruptor/src/main/java/com/baeldung/disruptor/SingleEventPrintConsumer.java new file mode 100644 index 0000000000..254efa9a0b --- /dev/null +++ b/disruptor/src/main/java/com/baeldung/disruptor/SingleEventPrintConsumer.java @@ -0,0 +1,22 @@ +package com.baeldung.disruptor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.lmax.disruptor.EventHandler; + +public class SingleEventPrintConsumer implements EventConsumer { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + @SuppressWarnings("unchecked") + public EventHandler[] getEventHandler() { + final EventHandler eventHandler = (event, sequence, endOfBatch) -> print(event.getValue(), sequence); + return new EventHandler[] { eventHandler }; + } + + private void print(final int id, final long sequenceId) { + logger.info("Id is " + id + " sequence id that was used is " + sequenceId); + } +} diff --git a/disruptor/src/main/java/com/baeldung/disruptor/SingleEventProducer.java b/disruptor/src/main/java/com/baeldung/disruptor/SingleEventProducer.java new file mode 100644 index 0000000000..771d1ab90d --- /dev/null +++ b/disruptor/src/main/java/com/baeldung/disruptor/SingleEventProducer.java @@ -0,0 +1,22 @@ +package com.baeldung.disruptor; + +import com.lmax.disruptor.RingBuffer; + +public class SingleEventProducer implements EventProducer { + + @Override + public void startProducing(RingBuffer ringBuffer, int count) { + final Runnable producer = () -> produce(ringBuffer, count); + new Thread(producer).start(); + } + + private void produce(final RingBuffer ringBuffer, final int count) { + for (int i = 0; i < count; i++) { + final long seq = ringBuffer.next(); + final ValueEvent valueEvent = ringBuffer.get(seq); + valueEvent.setValue(i); + ringBuffer.publish(seq); + } + } + +} diff --git a/disruptor/src/main/java/com/baeldung/disruptor/ValueEvent.java b/disruptor/src/main/java/com/baeldung/disruptor/ValueEvent.java new file mode 100644 index 0000000000..ad466b6a31 --- /dev/null +++ b/disruptor/src/main/java/com/baeldung/disruptor/ValueEvent.java @@ -0,0 +1,25 @@ +package com.baeldung.disruptor; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +import com.lmax.disruptor.EventFactory; + +public final class ValueEvent { + + private int value; + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public final static EventFactory EVENT_FACTORY = () -> new ValueEvent(); + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java b/disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java new file mode 100644 index 0000000000..28a5ff72ce --- /dev/null +++ b/disruptor/src/test/java/com/baeldung/disruptor/DisruptorTest.java @@ -0,0 +1,83 @@ +package com.baeldung.disruptor; + +import java.util.concurrent.ThreadFactory; +import org.junit.Before; +import org.junit.Test; +import com.lmax.disruptor.BusySpinWaitStrategy; +import com.lmax.disruptor.RingBuffer; +import com.lmax.disruptor.WaitStrategy; +import com.lmax.disruptor.dsl.Disruptor; +import com.lmax.disruptor.dsl.ProducerType; +import com.lmax.disruptor.util.DaemonThreadFactory; + +public class DisruptorTest { + private Disruptor disruptor; + private WaitStrategy waitStrategy; + + @Before + public void setUp() throws Exception { + waitStrategy = new BusySpinWaitStrategy(); + } + + private void createDisruptor(final ProducerType producerType, final EventConsumer eventConsumer) { + final ThreadFactory threadFactory = DaemonThreadFactory.INSTANCE; + disruptor = new Disruptor(ValueEvent.EVENT_FACTORY, 16, threadFactory, producerType, waitStrategy); + disruptor.handleEventsWith(eventConsumer.getEventHandler()); + } + + private void startProducing(final RingBuffer ringBuffer, final int count, final EventProducer eventProducer) { + eventProducer.startProducing(ringBuffer, count); + } + + @Test + public void whenMultipleProducerSingleConsumer_thenOutputInFifoOrder() { + final EventConsumer eventConsumer = new SingleEventPrintConsumer(); + final EventProducer eventProducer = new DelayedMultiEventProducer(); + createDisruptor(ProducerType.MULTI, eventConsumer); + final RingBuffer ringBuffer = disruptor.start(); + + startProducing(ringBuffer, 32, eventProducer); + + disruptor.halt(); + disruptor.shutdown(); + } + + @Test + public void whenSingleProducerSingleConsumer_thenOutputInFifoOrder() { + final EventConsumer eventConsumer = new SingleEventConsumer(); + final EventProducer eventProducer = new SingleEventProducer(); + createDisruptor(ProducerType.SINGLE, eventConsumer); + final RingBuffer ringBuffer = disruptor.start(); + + startProducing(ringBuffer, 32, eventProducer); + + disruptor.halt(); + disruptor.shutdown(); + } + + @Test + public void whenSingleProducerMultipleConsumer_thenOutputInFifoOrder() { + final EventConsumer eventConsumer = new MultiEventConsumer(); + final EventProducer eventProducer = new SingleEventProducer(); + createDisruptor(ProducerType.SINGLE, eventConsumer); + final RingBuffer ringBuffer = disruptor.start(); + + startProducing(ringBuffer, 32, eventProducer); + + disruptor.halt(); + disruptor.shutdown(); + } + + @Test + public void whenMultipleProducerMultipleConsumer_thenOutputInFifoOrder() { + final EventConsumer eventConsumer = new MultiEventPrintConsumer(); + final EventProducer eventProducer = new DelayedMultiEventProducer(); + createDisruptor(ProducerType.MULTI, eventConsumer); + final RingBuffer ringBuffer = disruptor.start(); + + startProducing(ringBuffer, 32, eventProducer); + + disruptor.halt(); + disruptor.shutdown(); + } +} diff --git a/disruptor/src/test/java/com/baeldung/disruptor/MultiEventConsumer.java b/disruptor/src/test/java/com/baeldung/disruptor/MultiEventConsumer.java new file mode 100644 index 0000000000..304f62c2ee --- /dev/null +++ b/disruptor/src/test/java/com/baeldung/disruptor/MultiEventConsumer.java @@ -0,0 +1,27 @@ +package com.baeldung.disruptor; + +import static org.junit.Assert.assertEquals; + +import com.lmax.disruptor.EventHandler; + +public class MultiEventConsumer implements EventConsumer { + + private int expectedValue = -1; + private int otherExpectedValue = -1; + + @Override + @SuppressWarnings("unchecked") + public EventHandler[] getEventHandler() { + final EventHandler eventHandler = (event, sequence, endOfBatch) -> assertExpectedValue(event.getValue()); + final EventHandler otherEventHandler = (event, sequence, endOfBatch) -> assertOtherExpectedValue(event.getValue()); + return new EventHandler[] { eventHandler, otherEventHandler }; + } + + private void assertExpectedValue(final int id) { + assertEquals(++expectedValue, id); + } + + private void assertOtherExpectedValue(final int id) { + assertEquals(++otherExpectedValue, id); + } +} diff --git a/disruptor/src/test/java/com/baeldung/disruptor/SingleEventConsumer.java b/disruptor/src/test/java/com/baeldung/disruptor/SingleEventConsumer.java new file mode 100644 index 0000000000..efc7432b5a --- /dev/null +++ b/disruptor/src/test/java/com/baeldung/disruptor/SingleEventConsumer.java @@ -0,0 +1,21 @@ +package com.baeldung.disruptor; + +import static org.junit.Assert.assertEquals; + +import com.lmax.disruptor.EventHandler; + +public class SingleEventConsumer implements EventConsumer { + + private int expectedValue = -1; + + @Override + @SuppressWarnings("unchecked") + public EventHandler[] getEventHandler() { + final EventHandler eventHandler = (event, sequence, endOfBatch) -> assertExpectedValue(event.getValue()); + return new EventHandler[] { eventHandler }; + } + + private void assertExpectedValue(final int id) { + assertEquals(++expectedValue, id); + } +} 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/eclipse/formatter.xml b/eclipse/formatter.xml index f9bccca6f6..808f65cda9 100644 --- a/eclipse/formatter.xml +++ b/eclipse/formatter.xml @@ -1,291 +1,587 @@ - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + - + + + + + + + + + - - - - - - - + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java index 9c0c359d88..56cf4071b4 100644 --- a/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java +++ b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java @@ -11,16 +11,9 @@ import lombok.Getter; @Getter public class BookControllerFeignClientBuilder { - private BookClient bookClient = createClient(BookClient.class, - "http://localhost:8081/api/books"); + private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books"); private static T createClient(Class type, String uri) { - return Feign.builder() - .client(new OkHttpClient()) - .encoder(new GsonEncoder()) - .decoder(new GsonDecoder()) - .logger(new Slf4jLogger(type)) - .logLevel(Logger.Level.FULL) - .target(type, uri); + return Feign.builder().client(new OkHttpClient()).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger(type)).logLevel(Logger.Level.FULL).target(type, uri); } } diff --git a/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java b/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java index e7e058a336..d7e65a0f4c 100644 --- a/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java +++ b/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java @@ -31,9 +31,7 @@ public class BookClientTest { @Test public void givenBookClient_shouldRunSuccessfully() throws Exception { - List books = bookClient.findAll().stream() - .map(BookResource::getBook) - .collect(Collectors.toList()); + List books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList()); assertTrue(books.size() > 2); log.info("{}", books); } 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..0edbb90efd 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -57,6 +57,38 @@ test + + + + 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.assertj + assertj-core + ${assertj.version} + test + @@ -92,7 +124,7 @@ - 19.0 + 21.0 3.5 4.1 @@ -100,11 +132,15 @@ 1.3 4.12 1.10.19 + 3.6.1 3.6.0 2.19.1 + + 1.7.21 + 1.1.7 \ No newline at end of file diff --git a/guava/src/main/java/org/baeldung/guava/CustomEvent.java b/guava/src/main/java/org/baeldung/guava/CustomEvent.java new file mode 100644 index 0000000000..2d5c3382d4 --- /dev/null +++ b/guava/src/main/java/org/baeldung/guava/CustomEvent.java @@ -0,0 +1,17 @@ +package org.baeldung.guava; + +public class CustomEvent { + private String action; + + public CustomEvent(String action) { + this.action = action; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } +} diff --git a/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java b/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java new file mode 100644 index 0000000000..243bc9e6ea --- /dev/null +++ b/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java @@ -0,0 +1,21 @@ +package org.baeldung.guava; + +import com.google.common.eventbus.EventBus; + +class EventBusWrapper { + + private static EventBus eventBus = new EventBus(); + + static void register(Object object) { + eventBus.register(object); + } + + static void unregister(Object object) { + eventBus.unregister(object); + } + + static void post(Object object) { + eventBus.post(object); + } + +} diff --git a/guava/src/main/java/org/baeldung/guava/EventListener.java b/guava/src/main/java/org/baeldung/guava/EventListener.java new file mode 100644 index 0000000000..02f22ce6b9 --- /dev/null +++ b/guava/src/main/java/org/baeldung/guava/EventListener.java @@ -0,0 +1,31 @@ +package org.baeldung.guava; + +import com.google.common.eventbus.Subscribe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EventListener { + + private static int eventsHandled; + private static final Logger LOG = LoggerFactory.getLogger(EventListener.class); + + @Subscribe + public void stringEvent(String event) { + LOG.info("do event [" + event + "]"); + eventsHandled++; + } + + @Subscribe + public void someCustomEvent(CustomEvent customEvent) { + LOG.info("do event [" + customEvent.getAction() + "]"); + eventsHandled++; + } + + public int getEventsHandled() { + return eventsHandled; + } + + public void resetEventsHandled() { + eventsHandled = 0; + } +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java new file mode 100644 index 0000000000..1db361d22c --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java @@ -0,0 +1,42 @@ +package org.baeldung.guava; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class GuavaEventBusTest { + + private EventListener listener; + + @Before + public void setUp() { + listener = new EventListener(); + EventBusWrapper.register(listener); + } + + @After + public void tearDown() { + EventBusWrapper.unregister(listener); + } + + @Test + public void givenStringEvent_whenEventHandled_thenSuccess() { + listener.resetEventsHandled(); + + EventBusWrapper.post("String Event"); + assertEquals(1, listener.getEventsHandled()); + + } + + @Test + public void givenCustomEvent_whenEventHandled_thenSuccess() { + listener.resetEventsHandled(); + + CustomEvent customEvent = new CustomEvent("Custom Event"); + EventBusWrapper.post(customEvent); + + assertEquals(1, listener.getEventsHandled()); + } +} 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/GuavaOrderingTest.java b/guava/src/test/java/org/baeldung/guava/GuavaOrderingTest.java new file mode 100644 index 0000000000..5ecf4f048d --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaOrderingTest.java @@ -0,0 +1,91 @@ +package org.baeldung.guava; + +import com.google.common.base.Function; +import com.google.common.collect.Ordering; +import com.google.common.primitives.Ints; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class GuavaOrderingTest { + @Test + public void givenListOfIntegers_whenCreateNaturalOrderOrdering_shouldSortProperly() { + //given + List integers = Arrays.asList(3, 2, 1); + + //when + integers.sort(Ordering.natural()); + + //then + assertEquals(Arrays.asList(1, 2, 3), integers); + } + + @Test + public void givenListOfPersonObject_whenSortedUsingCustomOrdering_shouldSortProperly() { + //given + List persons = Arrays.asList(new Person("Michael", 10), new Person("Alice", 3)); + Ordering orderingByAge = new Ordering() { + @Override + public int compare(Person p1, Person p2) { + return Ints.compare(p1.age, p2.age); + } + }; + + //when + persons.sort(orderingByAge); + + //then + assertEquals(Arrays.asList(new Person("Alice", 3), new Person("Michael", 10)), persons); + } + + @Test + public void givenListOfPersonObject_whenSortedUsingChainedOrdering_shouldSortPropely() { + //given + List persons = Arrays.asList(new Person("Michael", 10), new Person("Alice", 3), new Person("Thomas", null)); + Ordering ordering = Ordering.natural().nullsFirst().onResultOf(new Function() { + @Override + public Comparable apply(Person person) { + return person.age; + } + }); + + //when + persons.sort(ordering); + + //then + assertEquals(Arrays.asList(new Person("Thomas", null), new Person("Alice", 3), new Person("Michael", 10)), persons); + } + + + class Person { + private final String name; + private final Integer age; + + private Person(String name, Integer age) { + this.name = name; + this.age = age; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Person person = (Person) o; + + if (name != null ? !name.equals(person.name) : person.name != null) return false; + return age != null ? age.equals(person.age) : person.age == null; + + } + + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (age != null ? age.hashCode() : 0); + return result; + } + } +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java b/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java new file mode 100644 index 0000000000..2d98418d48 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java @@ -0,0 +1,104 @@ +package org.baeldung.guava; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.Arrays; +import org.junit.Test; +import com.google.common.base.*; + +public class GuavaPreConditionsTest { + + @Test + public void whenCheckArgumentEvaluatesFalse_throwsException() { + int age = -18; + + assertThatThrownBy(() -> Preconditions.checkArgument(age > 0)).isInstanceOf(IllegalArgumentException.class).hasMessage(null).hasNoCause(); + } + + @Test + public void givenErrorMessage_whenCheckArgumentEvaluatesFalse_throwsException() { + final int age = -18; + final String message = "Age can't be zero or less than zero"; + + assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message)).isInstanceOf(IllegalArgumentException.class).hasMessage(message).hasNoCause(); + } + + @Test + public void givenTemplatedErrorMessage_whenCheckArgumentEvaluatesFalse_throwsException() { + final int age = -18; + final String message = "Age can't be zero or less than zero, you supplied %s."; + + assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message, age)).isInstanceOf(IllegalArgumentException.class).hasMessage(message, age).hasNoCause(); + } + + @Test + public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() { + final int[] numbers = { 1, 2, 3, 4, 5 }; + + assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause(); + } + + @Test + public void givenArrayOfIntegersAndMessage_whenCheckElementIndexEvaluatesFalse_throwsException() { + final int[] numbers = { 1, 2, 3, 4, 5 }; + final String message = "Please check the bound of an array and retry"; + + assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause(); + } + + @Test + public void givenNullString_whenCheckNotNullCalledWithMessage_throwsException() { + final String nullObject = null; + final String message = "Please check the Object supplied, its null!"; + + assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message)).isInstanceOf(NullPointerException.class).hasMessage(message).hasNoCause(); + } + + @Test + public void givenNullString_whenCheckNotNullCalledWithTemplatedMessage_throwsException() { + final String nullObject = null; + final String message = "Please check the Object supplied, its %s!"; + + assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message, new Object[] { null })).isInstanceOf(NullPointerException.class).hasMessage(message, nullObject).hasNoCause(); + } + + @Test + public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() { + final int[] numbers = { 1, 2, 3, 4, 5 }; + + assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause(); + } + + @Test + public void givenArrayOfIntegersAndMessage_whenCheckPositionIndexEvaluatesFalse_throwsException() { + final int[] numbers = { 1, 2, 3, 4, 5 }; + final String message = "Please check the bound of an array and retry"; + + assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause(); + } + + @Test + public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() { + final int[] numbers = { 1, 2, 3, 4, 5 }; + + assertThatThrownBy(() -> Preconditions.checkPositionIndexes(6, 0, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause(); + } + + @Test + public void givenValidStatesAndMessage_whenCheckStateEvaluatesFalse_throwsException() { + final int[] validStates = { -1, 0, 1 }; + final int givenState = 10; + final String message = "You have entered an invalid state"; + + assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message)).isInstanceOf(IllegalStateException.class).hasMessageStartingWith(message).hasNoCause(); + } + + @Test + public void givenValidStatesAndTemplatedMessage_whenCheckStateEvaluatesFalse_throwsException() { + final int[] validStates = { -1, 0, 1 }; + final int givenState = 10; + final String message = "State can't be %s, It can be one of %s."; + + assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates))).isInstanceOf(IllegalStateException.class) + .hasMessage(message, givenState, Arrays.toString(validStates)).hasNoCause(); + } +} \ No newline at end of file diff --git a/guava/src/test/java/org/baeldung/guava/GuavaRangeMapTest.java b/guava/src/test/java/org/baeldung/guava/GuavaRangeMapTest.java new file mode 100644 index 0000000000..b68dca97c6 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaRangeMapTest.java @@ -0,0 +1,128 @@ +package org.baeldung.guava; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import java.util.Map; +import org.junit.Test; +import com.google.common.collect.ImmutableRangeMap; +import com.google.common.collect.Range; +import com.google.common.collect.RangeMap; +import com.google.common.collect.TreeRangeMap; + +public class GuavaRangeMapTest { + + @Test + public void givenRangeMap_whenQueryWithinRange_returnsSucessfully() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director"); + + assertEquals("Vice President", experienceRangeDesignationMap.get(6)); + assertEquals("Executive Director", experienceRangeDesignationMap.get(15)); + } + + @Test + public void givenRangeMap_whenQueryOutsideRange_returnsNull() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director"); + + assertNull(experienceRangeDesignationMap.get(31)); + } + + @Test + public void givenRangeMap_whenRemoveRangeIsCalled_removesSucessfully() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director"); + experienceRangeDesignationMap.remove(Range.closed(8, 15)); + experienceRangeDesignationMap.remove(Range.closed(20, 26)); + + assertNull(experienceRangeDesignationMap.get(9)); + assertEquals("Managing Director", experienceRangeDesignationMap.get(16)); + assertEquals("Managing Director", experienceRangeDesignationMap.get(30)); + assertNull(experienceRangeDesignationMap.get(25)); + } + + @Test + public void givenRangeMap_whenSpanIsCalled_returnsSucessfully() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director"); + final Range experienceSpan = experienceRangeDesignationMap.span(); + + assertEquals(0, experienceSpan.lowerEndpoint().intValue()); + assertEquals(30, experienceSpan.upperEndpoint().intValue()); + } + + @Test + public void givenRangeMap_whenGetEntryIsCalled_returnsEntrySucessfully() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(20, 30), "Managing Director"); + final Map.Entry, String> experiencEntry = experienceRangeDesignationMap.getEntry(10); + + assertEquals(Range.closed(9, 15), experiencEntry.getKey()); + assertEquals("Executive Director", experiencEntry.getValue()); + } + + @Test + public void givenRangeMap_whenSubRangeMapIsCalled_returnsSubRangeSucessfully() { + final RangeMap experienceRangeDesignationMap = TreeRangeMap.create(); + + experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate"); + experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate"); + experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President"); + experienceRangeDesignationMap.put(Range.closed(8, 15), "Executive Director"); + experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director"); + final RangeMap experiencedSubRangeDesignationMap = experienceRangeDesignationMap.subRangeMap(Range.closed(4, 14)); + + assertNull(experiencedSubRangeDesignationMap.get(3)); + assertEquals("Executive Director", experiencedSubRangeDesignationMap.get(14)); + assertEquals("Vice President", experiencedSubRangeDesignationMap.get(7)); + } + + @Test + public void givenImmutableRangeMap_whenQueryWithinRange_returnsSucessfully() { + final RangeMap experienceRangeDesignationMap = ImmutableRangeMap. builder() + .put(Range.closed(0, 2), "Associate") + .put(Range.closed(3, 5), "Senior Associate") + .put(Range.closed(6, 8), "Vice President") + .put(Range.closed(9, 15), "Executive Director") + .put(Range.closed(16, 30), "Managing Director").build(); + + assertEquals("Vice President", experienceRangeDesignationMap.get(6)); + assertEquals("Executive Director", experienceRangeDesignationMap.get(15)); + } + + @Test(expected = IllegalArgumentException.class) + public void givenImmutableRangeMap_whenRangeOverlaps_ThrowsException() { + ImmutableRangeMap. builder() + .put(Range.closed(0, 2), "Associate") + .put(Range.closed(3, 5), "Senior Associate") + .put(Range.closed(6, 8), "Vice President") + .put(Range.closed(8, 15), "Executive Director") + .put(Range.closed(16, 30), "Managing Director").build(); + + } +} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaRangeSetTest.java b/guava/src/test/java/org/baeldung/guava/GuavaRangeSetTest.java new file mode 100644 index 0000000000..002e1a61e9 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaRangeSetTest.java @@ -0,0 +1,127 @@ +package org.baeldung.guava; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import org.junit.Test; +import com.google.common.collect.ImmutableRangeSet; +import com.google.common.collect.Range; +import com.google.common.collect.RangeSet; +import com.google.common.collect.TreeRangeSet; + +public class GuavaRangeSetTest { + + @Test + public void givenRangeSet_whenQueryWithinRange_returnsSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 5)); + numberRangeSet.add(Range.closed(6, 8)); + + assertTrue(numberRangeSet.contains(1)); + assertFalse(numberRangeSet.contains(9)); + } + + @Test + public void givenRangeSet_whenEnclosesWithinRange_returnsSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 10)); + numberRangeSet.add(Range.closed(15, 18)); + + assertTrue(numberRangeSet.encloses(Range.closed(4, 5))); + assertFalse(numberRangeSet.encloses(Range.closed(4, 11))); + } + + @Test + public void givenRangeSet_whenComplementIsCalled_returnsSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 5)); + numberRangeSet.add(Range.closed(6, 8)); + final RangeSet numberRangeComplementSet = numberRangeSet.complement(); + + assertTrue(numberRangeComplementSet.contains(-1000)); + assertFalse(numberRangeComplementSet.contains(2)); + assertFalse(numberRangeComplementSet.contains(3)); + assertTrue(numberRangeComplementSet.contains(1000)); + } + + @Test + public void givenRangeSet_whenIntersectsWithinRange_returnsSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 10)); + numberRangeSet.add(Range.closed(15, 18)); + + assertTrue(numberRangeSet.intersects(Range.closed(4, 17))); + assertFalse(numberRangeSet.intersects(Range.closed(19, 200))); + } + + @Test + public void givenRangeSet_whenRemoveRangeIsCalled_removesSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 5)); + numberRangeSet.add(Range.closed(6, 8)); + numberRangeSet.add(Range.closed(9, 15)); + numberRangeSet.remove(Range.closed(3, 5)); + numberRangeSet.remove(Range.closed(7, 10)); + + assertTrue(numberRangeSet.contains(1)); + assertFalse(numberRangeSet.contains(9)); + assertTrue(numberRangeSet.contains(12)); + } + + @Test + public void givenRangeSet_whenSpanIsCalled_returnsSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 5)); + numberRangeSet.add(Range.closed(6, 8)); + final Range experienceSpan = numberRangeSet.span(); + + assertEquals(0, experienceSpan.lowerEndpoint().intValue()); + assertEquals(8, experienceSpan.upperEndpoint().intValue()); + } + + @Test + public void givenRangeSet_whenSubRangeSetIsCalled_returnsSubRangeSucessfully() { + final RangeSet numberRangeSet = TreeRangeSet.create(); + + numberRangeSet.add(Range.closed(0, 2)); + numberRangeSet.add(Range.closed(3, 5)); + numberRangeSet.add(Range.closed(6, 8)); + final RangeSet numberSubRangeSet = numberRangeSet.subRangeSet(Range.closed(4, 14)); + + assertFalse(numberSubRangeSet.contains(3)); + assertFalse(numberSubRangeSet.contains(14)); + assertTrue(numberSubRangeSet.contains(7)); + } + + @Test + public void givenImmutableRangeSet_whenQueryWithinRange_returnsSucessfully() { + final RangeSet numberRangeSet = ImmutableRangeSet. builder() + .add(Range.closed(0, 2)) + .add(Range.closed(3, 5)) + .add(Range.closed(6, 8)).build(); + + assertTrue(numberRangeSet.contains(6)); + assertFalse(numberRangeSet.contains(15)); + } + + @Test(expected = IllegalArgumentException.class) + public void givenImmutableRangeMap_whenRangeOverlaps_ThrowsException() { + ImmutableRangeSet. builder() + .add(Range.closed(0, 2)) + .add(Range.closed(3, 5)) + .add(Range.closed(5, 8)).build(); + + } +} 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/guava/src/test/java/org/baeldung/guava/GuavaTableTest.java b/guava/src/test/java/org/baeldung/guava/GuavaTableTest.java new file mode 100644 index 0000000000..6992752cd8 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaTableTest.java @@ -0,0 +1,178 @@ +package org.baeldung.guava; + +import static org.assertj.core.api.Assertions.*; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.Test; +import com.google.common.collect.ArrayTable; +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.ImmutableTable; +import com.google.common.collect.Lists; +import com.google.common.collect.Table; +import com.google.common.collect.TreeBasedTable; + +public class GuavaTableTest { + + @Test + public void givenTable_whenGet_returnsSuccessfully() { + final Table universityCourseSeatTable = HashBasedTable.create(); + universityCourseSeatTable.put("Mumbai", "Chemical", 120); + universityCourseSeatTable.put("Mumbai", "IT", 60); + universityCourseSeatTable.put("Harvard", "Electrical", 60); + universityCourseSeatTable.put("Harvard", "IT", 120); + + final int seatCount = universityCourseSeatTable.get("Mumbai", "IT"); + final Integer seatCountForNoEntry = universityCourseSeatTable.get("Oxford", "IT"); + + assertThat(seatCount).isEqualTo(60); + assertThat(seatCountForNoEntry).isEqualTo(null); + } + + @Test + public void givenTable_whenContains_returnsSuccessfully() { + final Table universityCourseSeatTable = HashBasedTable.create(); + universityCourseSeatTable.put("Mumbai", "Chemical", 120); + universityCourseSeatTable.put("Mumbai", "IT", 60); + universityCourseSeatTable.put("Harvard", "Electrical", 60); + universityCourseSeatTable.put("Harvard", "IT", 120); + + final boolean entryIsPresent = universityCourseSeatTable.contains("Mumbai", "IT"); + final boolean entryIsAbsent = universityCourseSeatTable.contains("Oxford", "IT"); + final boolean courseIsPresent = universityCourseSeatTable.containsColumn("IT"); + final boolean universityIsPresent = universityCourseSeatTable.containsRow("Mumbai"); + final boolean seatCountIsPresent = universityCourseSeatTable.containsValue(60); + + assertThat(entryIsPresent).isEqualTo(true); + assertThat(entryIsAbsent).isEqualTo(false); + assertThat(courseIsPresent).isEqualTo(true); + assertThat(universityIsPresent).isEqualTo(true); + assertThat(seatCountIsPresent).isEqualTo(true); + } + + @Test + public void givenTable_whenRemove_returnsSuccessfully() { + final Table universityCourseSeatTable = HashBasedTable.create(); + universityCourseSeatTable.put("Mumbai", "Chemical", 120); + universityCourseSeatTable.put("Mumbai", "IT", 60); + + final int seatCount = universityCourseSeatTable.remove("Mumbai", "IT"); + + assertThat(seatCount).isEqualTo(60); + assertThat(universityCourseSeatTable.remove("Mumbai", "IT")).isEqualTo(null); + } + + @Test + public void givenTable_whenColumn_returnsSuccessfully() { + final Table universityCourseSeatTable = HashBasedTable.create(); + universityCourseSeatTable.put("Mumbai", "Chemical", 120); + universityCourseSeatTable.put("Mumbai", "IT", 60); + universityCourseSeatTable.put("Harvard", "Electrical", 60); + universityCourseSeatTable.put("Harvard", "IT", 120); + + final Map universitySeatMap = universityCourseSeatTable.column("IT"); + + assertThat(universitySeatMap).hasSize(2); + assertThat(universitySeatMap.get("Mumbai")).isEqualTo(60); + assertThat(universitySeatMap.get("Harvard")).isEqualTo(120); + } + + @Test + public void givenTable_whenColumnMap_returnsSuccessfully() { + final Table universityCourseSeatTable = HashBasedTable.create(); + universityCourseSeatTable.put("Mumbai", "Chemical", 120); + universityCourseSeatTable.put("Mumbai", "IT", 60); + universityCourseSeatTable.put("Harvard", "Electrical", 60); + universityCourseSeatTable.put("Harvard", "IT", 120); + + final Map> courseKeyUniversitySeatMap = universityCourseSeatTable.columnMap(); + + assertThat(courseKeyUniversitySeatMap).hasSize(3); + assertThat(courseKeyUniversitySeatMap.get("IT")).hasSize(2); + assertThat(courseKeyUniversitySeatMap.get("Electrical")).hasSize(1); + assertThat(courseKeyUniversitySeatMap.get("Chemical")).hasSize(1); + } + + @Test + public void givenTable_whenRow_returnsSuccessfully() { + final Table universityCourseSeatTable = HashBasedTable.create(); + universityCourseSeatTable.put("Mumbai", "Chemical", 120); + universityCourseSeatTable.put("Mumbai", "IT", 60); + universityCourseSeatTable.put("Harvard", "Electrical", 60); + universityCourseSeatTable.put("Harvard", "IT", 120); + + final Map courseSeatMap = universityCourseSeatTable.row("Mumbai"); + + assertThat(courseSeatMap).hasSize(2); + assertThat(courseSeatMap.get("IT")).isEqualTo(60); + assertThat(courseSeatMap.get("Chemical")).isEqualTo(120); + } + + @Test + public void givenTable_whenRowKeySet_returnsSuccessfully() { + final Table universityCourseSeatTable = HashBasedTable.create(); + universityCourseSeatTable.put("Mumbai", "Chemical", 120); + universityCourseSeatTable.put("Mumbai", "IT", 60); + universityCourseSeatTable.put("Harvard", "Electrical", 60); + universityCourseSeatTable.put("Harvard", "IT", 120); + + final Set universitySet = universityCourseSeatTable.rowKeySet(); + + assertThat(universitySet).hasSize(2); + } + + @Test + public void givenTable_whenColKeySet_returnsSuccessfully() { + final Table universityCourseSeatTable = HashBasedTable.create(); + universityCourseSeatTable.put("Mumbai", "Chemical", 120); + universityCourseSeatTable.put("Mumbai", "IT", 60); + universityCourseSeatTable.put("Harvard", "Electrical", 60); + universityCourseSeatTable.put("Harvard", "IT", 120); + + final Set courseSet = universityCourseSeatTable.columnKeySet(); + + assertThat(courseSet).hasSize(3); + } + + @Test + public void givenTreeTable_whenGet_returnsSuccessfully() { + final Table universityCourseSeatTable = TreeBasedTable.create(); + universityCourseSeatTable.put("Mumbai", "Chemical", 120); + universityCourseSeatTable.put("Mumbai", "IT", 60); + universityCourseSeatTable.put("Harvard", "Electrical", 60); + universityCourseSeatTable.put("Harvard", "IT", 120); + + final int seatCount = universityCourseSeatTable.get("Mumbai", "IT"); + + assertThat(seatCount).isEqualTo(60); + } + + @Test + public void givenImmutableTable_whenGet_returnsSuccessfully() { + final Table universityCourseSeatTable = ImmutableTable. builder() + .put("Mumbai", "Chemical", 120) + .put("Mumbai", "IT", 60) + .put("Harvard", "Electrical", 60) + .put("Harvard", "IT", 120) + .build(); + + final int seatCount = universityCourseSeatTable.get("Mumbai", "IT"); + + assertThat(seatCount).isEqualTo(60); + } + + @Test + public void givenArrayTable_whenGet_returnsSuccessfully() { + final List universityRowTable = Lists.newArrayList("Mumbai", "Harvard"); + final List courseColumnTables = Lists.newArrayList("Chemical", "IT", "Electrical"); + final Table universityCourseSeatTable = ArrayTable.create(universityRowTable, courseColumnTables); + universityCourseSeatTable.put("Mumbai", "Chemical", 120); + universityCourseSeatTable.put("Mumbai", "IT", 60); + universityCourseSeatTable.put("Harvard", "Electrical", 60); + universityCourseSeatTable.put("Harvard", "IT", 120); + + final int seatCount = universityCourseSeatTable.get("Mumbai", "IT"); + + assertThat(seatCount).isEqualTo(60); + } +} 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/intelliJ/intelliJ-formatter.xml b/intelliJ/intelliJ-formatter.xml index 8c072cd161..6dd1ae67f3 100644 --- a/intelliJ/intelliJ-formatter.xml +++ b/intelliJ/intelliJ-formatter.xml @@ -1,4 +1,4 @@ - +