diff --git a/.gitignore b/.gitignore
index e841cc4bf5..1352c943be 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,3 +27,4 @@ target/
spring-openid/src/main/resources/application.properties
.recommenders/
+/spring-hibernate4/nbproject/
\ 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
+
+
+
+
+
\ 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
+
+
+
+ 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 extends Element> 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
-
-
+
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ 1.7
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
**/*IntegrationTest.java
**/*LiveTest.java
-
-
-
+
+
+
-
+
-
+
@@ -170,7 +171,7 @@
**/*IntegrationTest.java
- **/*LiveTest.java
+ **/*LiveTest.java
@@ -185,25 +186,25 @@
-
-
- 1.1
- 4.3
- 8.0.2
- r938
-
- 1.7.21
- 1.1.7
-
- 1.3
- 4.12
- 1.10.19
+
+ 1.1
+ 4.3
+ 8.0.2
+ r938
+
+ 1.7.21
+ 1.1.7
-
- 3.6.0
- 2.19.1
+
+ 1.3
+ 4.12
+ 1.10.19
-
+
+ 3.6.0
+ 2.19.1
+
+
\ No newline at end of file
diff --git a/apache-poi/README.md b/apache-poi/README.md
new file mode 100644
index 0000000000..cef6810c97
--- /dev/null
+++ b/apache-poi/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)
diff --git a/aspectj/README.md b/aspectj/README.md
new file mode 100644
index 0000000000..71724e76b6
--- /dev/null
+++ b/aspectj/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+- [Intro to AspectJ](http://www.baeldung.com/aspectj)
+- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging)
diff --git a/aspectj/pom.xml b/aspectj/pom.xml
index 2fca4031fb..90b527c14f 100644
--- a/aspectj/pom.xml
+++ b/aspectj/pom.xml
@@ -12,39 +12,69 @@
aspectjrt
${aspectj.version}
-
+
org.aspectj
aspectjweaver
${aspectj.version}
-
+
org.slf4j
slf4j-api
${org.slf4j.version}
-
+
ch.qos.logback
logback-classic
${logback.version}
-
+
ch.qos.logback
logback-core
${logback.version}
-
+
junit
junit
${junit.version}
-
+
+
+ org.springframework
+ spring-context
+ 4.3.4.RELEASE
+
+
+ org.springframework
+ spring-beans
+ 4.3.4.RELEASE
+
+
+ org.springframework
+ spring-core
+ 4.3.4.RELEASE
+
+
+ cglib
+ cglib
+ 3.2.4
+
+
+ org.springframework
+ spring-aop
+ 4.3.4.RELEASE
+
+
+ log4j
+ log4j
+ 1.2.17
+
@@ -65,9 +95,9 @@
${source.version}
-
+
-
+
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-lambda/pom.xml b/aws/pom.xml
similarity index 94%
rename from aws-lambda/pom.xml
rename to aws/pom.xml
index c02d9d59dd..f3ae672a2f 100644
--- a/aws-lambda/pom.xml
+++ b/aws/pom.xml
@@ -2,10 +2,10 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
- aws-lambda
+ aws
0.1.0-SNAPSHOT
jar
- aws-lambda
+ aws
diff --git a/aws-lambda/src/main/java/com/baeldung/LambdaMethodHandler.java b/aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java
similarity index 89%
rename from aws-lambda/src/main/java/com/baeldung/LambdaMethodHandler.java
rename to aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java
index 6cce694912..dc21476290 100644
--- a/aws-lambda/src/main/java/com/baeldung/LambdaMethodHandler.java
+++ b/aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java
@@ -1,4 +1,4 @@
-package com.baeldung;
+package com.baeldung.lambda;
import com.amazonaws.services.lambda.runtime.Context;
diff --git a/aws-lambda/src/main/java/com/baeldung/LambdaRequestHandler.java b/aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java
similarity index 92%
rename from aws-lambda/src/main/java/com/baeldung/LambdaRequestHandler.java
rename to aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java
index 37f114db25..85385555d2 100644
--- a/aws-lambda/src/main/java/com/baeldung/LambdaRequestHandler.java
+++ b/aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java
@@ -1,4 +1,4 @@
-package com.baeldung;
+package com.baeldung.lambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
diff --git a/aws-lambda/src/main/java/com/baeldung/LambdaRequestStreamHandler.java b/aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java
similarity index 87%
rename from aws-lambda/src/main/java/com/baeldung/LambdaRequestStreamHandler.java
rename to aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java
index aba65628ad..6e8a33c42d 100644
--- a/aws-lambda/src/main/java/com/baeldung/LambdaRequestStreamHandler.java
+++ b/aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java
@@ -1,7 +1,6 @@
-package com.baeldung;
+package com.baeldung.lambda;
import com.amazonaws.services.lambda.runtime.Context;
-import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import org.apache.commons.io.IOUtils;
diff --git a/cdi/pom.xml b/cdi/pom.xml
index 231390ea5c..e5aaeb2c7b 100644
--- a/cdi/pom.xml
+++ b/cdi/pom.xml
@@ -45,7 +45,7 @@
-
+
@@ -61,7 +61,7 @@
-
+
integration
@@ -101,7 +101,7 @@
1.8.9
2.4.1.Final
4.12
- 2.19.1
+ 2.19.1
\ No newline at end of file
diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml
index bf9325c935..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
+
+
-
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- 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..85afee2968 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -63,6 +63,7 @@
grep4j
${grep4j.version}
+
@@ -352,7 +353,7 @@
1.1.7
- 19.0
+ 21.0
3.5
1.55
1.10
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..113ac1cc53 100644
--- a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
+++ b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
@@ -7,25 +7,24 @@ import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- System.out.println("Run algorithm:");
- System.out.println("1 - Simulated Annealing");
- System.out.println("2 - Slope One");
- int decision = in.nextInt();
- switch (decision) {
- case 1:
- System.out.println(
- "Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
- break;
- case 2:
- SlopeOne.slopeOne(3);
- break;
- default:
- System.out.println("Unknown option");
- break;
- }
- in.close();
- }
+ public static void main(String[] args) {
+ Scanner in = new Scanner(System.in);
+ System.out.println("Run algorithm:");
+ System.out.println("1 - Simulated Annealing");
+ System.out.println("2 - Slope One");
+ int decision = in.nextInt();
+ switch (decision) {
+ case 1:
+ System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
+ break;
+ case 2:
+ SlopeOne.slopeOne(3);
+ break;
+ default:
+ System.out.println("Unknown option");
+ break;
+ }
+ in.close();
+ }
}
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/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..e53a2413d1
--- /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/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/scripting/Nashorn.java b/core-java/src/main/java/com/baeldung/scripting/Nashorn.java
deleted file mode 100644
index ba9b778de5..0000000000
--- a/core-java/src/main/java/com/baeldung/scripting/Nashorn.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package com.baeldung.scripting;
-
-import javax.script.Bindings;
-import javax.script.Invocable;
-import javax.script.ScriptEngine;
-import javax.script.ScriptEngineManager;
-import javax.script.ScriptException;
-
-public class Nashorn {
- public static void main(String[] args) throws ScriptException, NoSuchMethodException {
- ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
-
- Object result = engine.eval(
- "var greeting='hello world';" +
- "print(greeting);" +
- "greeting");
-
- System.out.println(result);
-
- Bindings bindings = engine.createBindings();
- bindings.put("count", 3);
- bindings.put("name", "baeldung");
-
- String script = "var greeting='Hello ';" +
- "for(var i=count;i>0;i--) { " +
- "greeting+=name + ' '" +
- "}" +
- "greeting";
-
- Object bindingsResult = engine.eval(script, bindings);
- System.out.println(bindingsResult);
-
- engine.eval("function composeGreeting(name) {" +
- "return 'Hello ' + name" +
- "}");
- Invocable invocable = (Invocable) engine;
-
- Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung");
- System.out.println(funcResult);
-
- Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" +
- "var map = new HashMap();" +
- "map.put('hello', 'world');" +
- "map");
-
- System.out.println(map);
- }
-}
diff --git a/core-java/src/main/resources/js/bind.js b/core-java/src/main/resources/js/bind.js
new file mode 100644
index 0000000000..652e646d0d
--- /dev/null
+++ b/core-java/src/main/resources/js/bind.js
@@ -0,0 +1,15 @@
+var first = {
+ name: "Whiskey",
+ age: 5
+};
+
+var second = {
+ volume: 100
+};
+
+Object.bindProperties(first, second);
+
+print(first.volume);
+
+second.volume = 1000;
+print(first.volume);
diff --git a/core-java/src/main/resources/js/locations.js b/core-java/src/main/resources/js/locations.js
new file mode 100644
index 0000000000..abfc944639
--- /dev/null
+++ b/core-java/src/main/resources/js/locations.js
@@ -0,0 +1 @@
+print(__FILE__, __LINE__, __DIR__);
diff --git a/core-java/src/main/resources/js/math_module.js b/core-java/src/main/resources/js/math_module.js
new file mode 100644
index 0000000000..267a100f36
--- /dev/null
+++ b/core-java/src/main/resources/js/math_module.js
@@ -0,0 +1,19 @@
+var math = {
+ increment: function (num) {
+ return ++num;
+ },
+
+ failFunc: function () {
+ try {
+ throw "BOOM";
+ } catch (e if typeof e === 'string') {
+ print("String thrown: " + e);
+ }
+ catch (e) {
+ print("this shouldn't happen!");
+ }
+ }
+};
+
+
+math;
diff --git a/core-java/src/main/resources/js/no_such.js b/core-java/src/main/resources/js/no_such.js
new file mode 100644
index 0000000000..43b50c5cad
--- /dev/null
+++ b/core-java/src/main/resources/js/no_such.js
@@ -0,0 +1,11 @@
+var demo = {
+ __noSuchProperty__: function (propName) {
+ print("Accessed non-existing property: " + propName);
+ },
+
+ __noSuchMethod__: function (methodName) {
+ print("Invoked non-existing method: " + methodName);
+ }
+};
+
+demo;
diff --git a/core-java/src/main/resources/js/script.js b/core-java/src/main/resources/js/script.js
new file mode 100644
index 0000000000..6f701ed59d
--- /dev/null
+++ b/core-java/src/main/resources/js/script.js
@@ -0,0 +1 @@
+function increment(num) ++num;
diff --git a/core-java/src/main/resources/js/trim.js b/core-java/src/main/resources/js/trim.js
new file mode 100644
index 0000000000..81be009978
--- /dev/null
+++ b/core-java/src/main/resources/js/trim.js
@@ -0,0 +1,2 @@
+print(" hello world".trimLeft());
+print("hello world ".trimRight());
diff --git a/core-java/src/main/resources/js/typed_arrays.js b/core-java/src/main/resources/js/typed_arrays.js
new file mode 100644
index 0000000000..6899b29373
--- /dev/null
+++ b/core-java/src/main/resources/js/typed_arrays.js
@@ -0,0 +1,9 @@
+function arrays(arr) {
+
+ var javaIntArray = Java.to(arr, "int[]");
+ print(javaIntArray[0]);
+ print(javaIntArray[1]);
+ print(javaIntArray[2]);
+}
+
+arrays([100, "1654", true]);
diff --git a/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java b/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java
new file mode 100644
index 0000000000..2f7830bbf4
--- /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..2e7dc24a17
--- /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/collectors/Java8CollectorsUnitTest.java b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java
index 923924cfc2..bad1c32e4a 100644
--- a/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java
@@ -42,136 +42,96 @@ public class Java8CollectorsUnitTest {
@Test
public void whenCollectingToList_shouldCollectToList() throws Exception {
- final List result = givenList
- .stream()
- .collect(toList());
+ final List result = givenList.stream().collect(toList());
assertThat(result).containsAll(givenList);
}
@Test
public void whenCollectingToList_shouldCollectToSet() throws Exception {
- final Set result = givenList
- .stream()
- .collect(toSet());
+ final Set result = givenList.stream().collect(toSet());
assertThat(result).containsAll(givenList);
}
@Test
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
- final List result = givenList
- .stream()
- .collect(toCollection(LinkedList::new));
+ final List result = givenList.stream().collect(toCollection(LinkedList::new));
- assertThat(result)
- .containsAll(givenList)
- .isInstanceOf(LinkedList.class);
+ assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
}
@Test
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
assertThatThrownBy(() -> {
- givenList
- .stream()
- .collect(toCollection(ImmutableList::of));
+ givenList.stream().collect(toCollection(ImmutableList::of));
}).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
- final Map result = givenList
- .stream()
- .collect(toMap(Function.identity(), String::length));
+ final Map result = givenList.stream().collect(toMap(Function.identity(), String::length));
- assertThat(result)
- .containsEntry("a", 1)
- .containsEntry("bb", 2)
- .containsEntry("ccc", 3)
- .containsEntry("dd", 2);
+ assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
}
@Test
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
- final Map result = givenList
- .stream()
- .collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
+ final Map result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
- assertThat(result)
- .containsEntry("a", 1)
- .containsEntry("bb", 2)
- .containsEntry("ccc", 3)
- .containsEntry("dd", 2);
+ assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
}
@Test
public void whenCollectingAndThen_shouldCollect() throws Exception {
- final List result = givenList
- .stream()
- .collect(collectingAndThen(toList(), ImmutableList::copyOf));
+ final List result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
- assertThat(result)
- .containsAll(givenList)
- .isInstanceOf(ImmutableList.class);
+ assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
}
@Test
public void whenJoining_shouldJoin() throws Exception {
- final String result = givenList
- .stream()
- .collect(joining());
+ final String result = givenList.stream().collect(joining());
assertThat(result).isEqualTo("abbcccdd");
}
@Test
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
- final String result = givenList
- .stream()
- .collect(joining(" "));
+ final String result = givenList.stream().collect(joining(" "));
assertThat(result).isEqualTo("a bb ccc dd");
}
@Test
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
- final String result = givenList
- .stream()
- .collect(joining(" ", "PRE-", "-POST"));
+ final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
}
@Test
public void whenPartitioningBy_shouldPartition() throws Exception {
- final Map> result = givenList
- .stream()
- .collect(partitioningBy(s -> s.length() > 2));
+ final Map> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
- assertThat(result)
- .containsKeys(true, false)
- .satisfies(booleanListMap -> {
- assertThat(booleanListMap.get(true)).contains("ccc");
+ assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
+ assertThat(booleanListMap.get(true)).contains("ccc");
- assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
- });
+ assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
+ });
}
@Test
public void whenCounting_shouldCount() throws Exception {
- final Long result = givenList
- .stream()
- .collect(counting());
+ final Long result = givenList.stream().collect(counting());
assertThat(result).isEqualTo(4);
}
@Test
public void whenSummarizing_shouldSummarize() throws Exception {
- final DoubleSummaryStatistics result = givenList
- .stream()
- .collect(summarizingDouble(String::length));
+ final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
assertThat(result.getAverage()).isEqualTo(2);
assertThat(result.getCount()).isEqualTo(4);
@@ -182,55 +142,37 @@ public class Java8CollectorsUnitTest {
@Test
public void whenAveraging_shouldAverage() throws Exception {
- final Double result = givenList
- .stream()
- .collect(averagingDouble(String::length));
+ final Double result = givenList.stream().collect(averagingDouble(String::length));
assertThat(result).isEqualTo(2);
}
@Test
public void whenSumming_shouldSum() throws Exception {
- final Double result = givenList
- .stream()
- .filter(i -> true)
- .collect(summingDouble(String::length));
+ final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
assertThat(result).isEqualTo(8);
}
@Test
public void whenMaxingBy_shouldMaxBy() throws Exception {
- final Optional result = givenList
- .stream()
- .collect(maxBy(Comparator.naturalOrder()));
+ final Optional result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
- assertThat(result)
- .isPresent()
- .hasValue("dd");
+ assertThat(result).isPresent().hasValue("dd");
}
@Test
public void whenGroupingBy_shouldGroupBy() throws Exception {
- final Map> result = givenList
- .stream()
- .collect(groupingBy(String::length, toSet()));
+ final Map> result = givenList.stream().collect(groupingBy(String::length, toSet()));
- assertThat(result)
- .containsEntry(1, newHashSet("a"))
- .containsEntry(2, newHashSet("bb", "dd"))
- .containsEntry(3, newHashSet("ccc"));
+ assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
}
@Test
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
- final ImmutableSet result = givenList
- .stream()
- .collect(toImmutableSet());
+ final ImmutableSet result = givenList.stream().collect(toImmutableSet());
- assertThat(result)
- .isInstanceOf(ImmutableSet.class)
- .contains("a", "bb", "ccc", "dd");
+ assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
}
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/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/ConcurrentMapAggregateStatusTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java
new file mode 100644
index 0000000000..73a4cdc0cd
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.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 ConcurrentMapAggregateStatusTest {
+
+ 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/ConcurrentMapNullKeyValueTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueTest.java
new file mode 100644
index 0000000000..62a3d10add
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueTest.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 ConcurrentMapNullKeyValueTest {
+
+ 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/ConcurrentMapPerformanceTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java
new file mode 100644
index 0000000000..a0efa89351
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.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 ConcurrentMapPerformanceTest {
+
+ @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