Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
2ca092923c
|
@ -27,3 +27,4 @@ target/
|
||||||
|
|
||||||
spring-openid/src/main/resources/application.properties
|
spring-openid/src/main/resources/application.properties
|
||||||
.recommenders/
|
.recommenders/
|
||||||
|
/spring-hibernate4/nbproject/
|
|
@ -0,0 +1,63 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>JGitSnippets</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<url>http://maven.apache.org</url>
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
|
</properties>
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>jgit-repository</id>
|
||||||
|
<url>https://repo.eclipse.org/content/groups/releases/</url>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
|
|
||||||
|
<!-- Core Library -->
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.eclipse.jgit</groupId>
|
||||||
|
<artifactId>org.eclipse.jgit</artifactId>
|
||||||
|
<version>4.5.0.201609210915-r</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.eclipse.jgit</groupId>
|
||||||
|
<artifactId>org.eclipse.jgit.archive</artifactId>
|
||||||
|
<version>4.5.0.201609210915-r</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-io</groupId>
|
||||||
|
<artifactId>commons-io</artifactId>
|
||||||
|
<version>2.5</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-simple</artifactId>
|
||||||
|
<version>1.7.21</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.2</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.7</source>
|
||||||
|
<target>1.7</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<RevCommit> 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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -18,9 +18,7 @@ public class Dijkstra {
|
||||||
while (unsettledNodes.size() != 0) {
|
while (unsettledNodes.size() != 0) {
|
||||||
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
||||||
unsettledNodes.remove(currentNode);
|
unsettledNodes.remove(currentNode);
|
||||||
for (Entry<Node, Integer> adjacencyPair : currentNode
|
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
|
||||||
.getAdjacentNodes()
|
|
||||||
.entrySet()) {
|
|
||||||
Node adjacentNode = adjacencyPair.getKey();
|
Node adjacentNode = adjacencyPair.getKey();
|
||||||
Integer edgeWeigh = adjacencyPair.getValue();
|
Integer edgeWeigh = adjacencyPair.getValue();
|
||||||
|
|
||||||
|
|
|
@ -55,29 +55,19 @@ public class DijkstraAlgorithmTest {
|
||||||
for (Node node : graph.getNodes()) {
|
for (Node node : graph.getNodes()) {
|
||||||
switch (node.getName()) {
|
switch (node.getName()) {
|
||||||
case "B":
|
case "B":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeB));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeB));
|
|
||||||
break;
|
break;
|
||||||
case "C":
|
case "C":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeC));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeC));
|
|
||||||
break;
|
break;
|
||||||
case "D":
|
case "D":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeD));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeD));
|
|
||||||
break;
|
break;
|
||||||
case "E":
|
case "E":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeE));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeE));
|
|
||||||
break;
|
break;
|
||||||
case "F":
|
case "F":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeF));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeF));
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,17 +27,12 @@ public class BuilderProcessor extends AbstractProcessor {
|
||||||
|
|
||||||
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
|
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
|
||||||
|
|
||||||
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream()
|
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set")));
|
||||||
.collect(Collectors.partitioningBy(element ->
|
|
||||||
((ExecutableType) element.asType()).getParameterTypes().size() == 1
|
|
||||||
&& element.getSimpleName().toString().startsWith("set")));
|
|
||||||
|
|
||||||
List<Element> setters = annotatedMethods.get(true);
|
List<Element> setters = annotatedMethods.get(true);
|
||||||
List<Element> otherMethods = annotatedMethods.get(false);
|
List<Element> otherMethods = annotatedMethods.get(false);
|
||||||
|
|
||||||
otherMethods.forEach(element ->
|
otherMethods.forEach(element -> processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
||||||
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
|
|
||||||
"@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
|
||||||
|
|
||||||
if (setters.isEmpty()) {
|
if (setters.isEmpty()) {
|
||||||
continue;
|
continue;
|
||||||
|
@ -45,11 +40,7 @@ public class BuilderProcessor extends AbstractProcessor {
|
||||||
|
|
||||||
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
|
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
|
||||||
|
|
||||||
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(
|
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString()));
|
||||||
setter -> setter.getSimpleName().toString(),
|
|
||||||
setter -> ((ExecutableType) setter.asType())
|
|
||||||
.getParameterTypes().get(0).toString()
|
|
||||||
));
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeBuilderFile(className, setterMap);
|
writeBuilderFile(className, setterMap);
|
||||||
|
|
|
@ -9,10 +9,7 @@ public class PersonBuilderTest {
|
||||||
@Test
|
@Test
|
||||||
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
||||||
|
|
||||||
Person person = new PersonBuilder()
|
Person person = new PersonBuilder().setAge(25).setName("John").build();
|
||||||
.setAge(25)
|
|
||||||
.setName("John")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
assertEquals(25, person.getAge());
|
assertEquals(25, person.getAge());
|
||||||
assertEquals("John", person.getName());
|
assertEquals("John", person.getName());
|
||||||
|
|
|
@ -8,7 +8,7 @@ public class Server {
|
||||||
String address = "http://localhost:8080/baeldung";
|
String address = "http://localhost:8080/baeldung";
|
||||||
Endpoint.publish(address, implementor);
|
Endpoint.publish(address, implementor);
|
||||||
System.out.println("Server ready...");
|
System.out.println("Server ready...");
|
||||||
Thread.sleep(60 * 1000);
|
Thread.sleep(60 * 1000);
|
||||||
System.out.println("Server exiting");
|
System.out.println("Server exiting");
|
||||||
System.exit(0);
|
System.exit(0);
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,7 +11,7 @@ public class RestfulServer {
|
||||||
factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository()));
|
factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository()));
|
||||||
factoryBean.setAddress("http://localhost:8080/");
|
factoryBean.setAddress("http://localhost:8080/");
|
||||||
Server server = factoryBean.create();
|
Server server = factoryBean.create();
|
||||||
|
|
||||||
System.out.println("Server ready...");
|
System.out.println("Server ready...");
|
||||||
Thread.sleep(60 * 1000);
|
Thread.sleep(60 * 1000);
|
||||||
System.out.println("Server exiting");
|
System.out.println("Server exiting");
|
||||||
|
|
|
@ -38,8 +38,7 @@ public class AssertJCoreTest {
|
||||||
public void whenCheckingForElement_thenContains() throws Exception {
|
public void whenCheckingForElement_thenContains() throws Exception {
|
||||||
List<String> list = Arrays.asList("1", "2", "3");
|
List<String> list = Arrays.asList("1", "2", "3");
|
||||||
|
|
||||||
assertThat(list)
|
assertThat(list).contains("1");
|
||||||
.contains("1");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -50,12 +49,7 @@ public class AssertJCoreTest {
|
||||||
assertThat(list).startsWith("1");
|
assertThat(list).startsWith("1");
|
||||||
assertThat(list).doesNotContainNull();
|
assertThat(list).doesNotContainNull();
|
||||||
|
|
||||||
assertThat(list)
|
assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3");
|
||||||
.isNotEmpty()
|
|
||||||
.contains("1")
|
|
||||||
.startsWith("1")
|
|
||||||
.doesNotContainNull()
|
|
||||||
.containsSequence("2", "3");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -67,11 +61,7 @@ public class AssertJCoreTest {
|
||||||
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
|
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
|
||||||
char someCharacter = 'c';
|
char someCharacter = 'c';
|
||||||
|
|
||||||
assertThat(someCharacter)
|
assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase();
|
||||||
.isNotEqualTo('a')
|
|
||||||
.inUnicode()
|
|
||||||
.isGreaterThanOrEqualTo('b')
|
|
||||||
.isLowerCase();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -94,11 +84,7 @@ public class AssertJCoreTest {
|
||||||
final File someFile = File.createTempFile("aaa", "bbb");
|
final File someFile = File.createTempFile("aaa", "bbb");
|
||||||
someFile.deleteOnExit();
|
someFile.deleteOnExit();
|
||||||
|
|
||||||
assertThat(someFile)
|
assertThat(someFile).exists().isFile().canRead().canWrite();
|
||||||
.exists()
|
|
||||||
.isFile()
|
|
||||||
.canRead()
|
|
||||||
.canWrite();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -113,20 +99,14 @@ public class AssertJCoreTest {
|
||||||
public void whenGivenMap_then() throws Exception {
|
public void whenGivenMap_then() throws Exception {
|
||||||
Map<Integer, String> map = Maps.newHashMap(2, "a");
|
Map<Integer, String> map = Maps.newHashMap(2, "a");
|
||||||
|
|
||||||
assertThat(map)
|
assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a"));
|
||||||
.isNotEmpty()
|
|
||||||
.containsKey(2)
|
|
||||||
.doesNotContainKeys(10)
|
|
||||||
.contains(entry(2, "a"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGivenException_then() throws Exception {
|
public void whenGivenException_then() throws Exception {
|
||||||
Exception ex = new Exception("abc");
|
Exception ex = new Exception("abc");
|
||||||
|
|
||||||
assertThat(ex)
|
assertThat(ex).hasNoCause().hasMessageEndingWith("c");
|
||||||
.hasNoCause()
|
|
||||||
.hasMessageEndingWith("c");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
|
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
|
||||||
|
@ -134,8 +114,6 @@ public class AssertJCoreTest {
|
||||||
public void whenRunningAssertion_thenDescribed() throws Exception {
|
public void whenRunningAssertion_thenDescribed() throws Exception {
|
||||||
Person person = new Person("Alex", 34);
|
Person person = new Person("Alex", 34);
|
||||||
|
|
||||||
assertThat(person.getAge())
|
assertThat(person.getAge()).as("%s's age should be equal to 100").isEqualTo(100);
|
||||||
.as("%s's age should be equal to 100")
|
|
||||||
.isEqualTo(100);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,9 +26,7 @@ public class AssertJGuavaTest {
|
||||||
final File temp1 = File.createTempFile("bael", "dung1");
|
final File temp1 = File.createTempFile("bael", "dung1");
|
||||||
final File temp2 = File.createTempFile("bael", "dung2");
|
final File temp2 = File.createTempFile("bael", "dung2");
|
||||||
|
|
||||||
assertThat(Files.asByteSource(temp1))
|
assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2));
|
||||||
.hasSize(0)
|
|
||||||
.hasSameContentAs(Files.asByteSource(temp2));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -37,11 +35,7 @@ public class AssertJGuavaTest {
|
||||||
mmap.put(1, "one");
|
mmap.put(1, "one");
|
||||||
mmap.put(1, "1");
|
mmap.put(1, "1");
|
||||||
|
|
||||||
assertThat(mmap)
|
assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1"));
|
||||||
.hasSize(2)
|
|
||||||
.containsKeys(1)
|
|
||||||
.contains(entry(1, "one"))
|
|
||||||
.contains(entry(1, "1"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -62,31 +56,21 @@ public class AssertJGuavaTest {
|
||||||
mmap2.put(1, "one");
|
mmap2.put(1, "one");
|
||||||
mmap2.put(1, "1");
|
mmap2.put(1, "1");
|
||||||
|
|
||||||
assertThat(mmap1)
|
assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone);
|
||||||
.containsAllEntriesOf(mmap2)
|
|
||||||
.containsAllEntriesOf(mmap1_clone)
|
|
||||||
.hasSameEntriesAs(mmap1_clone);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
||||||
final Optional<String> something = Optional.of("something");
|
final Optional<String> something = Optional.of("something");
|
||||||
|
|
||||||
assertThat(something)
|
assertThat(something).isPresent().extractingValue().isEqualTo("something");
|
||||||
.isPresent()
|
|
||||||
.extractingValue()
|
|
||||||
.isEqualTo("something");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||||
final Range<String> range = Range.openClosed("a", "g");
|
final Range<String> range = Range.openClosed("a", "g");
|
||||||
|
|
||||||
assertThat(range)
|
assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b");
|
||||||
.hasOpenedLowerBound()
|
|
||||||
.isNotEmpty()
|
|
||||||
.hasClosedUpperBound()
|
|
||||||
.contains("b");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -96,10 +80,7 @@ public class AssertJGuavaTest {
|
||||||
map.put(Range.closed(0, 60), "F");
|
map.put(Range.closed(0, 60), "F");
|
||||||
map.put(Range.closed(61, 70), "D");
|
map.put(Range.closed(61, 70), "D");
|
||||||
|
|
||||||
assertThat(map)
|
assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F"));
|
||||||
.isNotEmpty()
|
|
||||||
.containsKeys(0)
|
|
||||||
.contains(MapEntry.entry(34, "F"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -109,13 +90,7 @@ public class AssertJGuavaTest {
|
||||||
table.put(1, "A", "PRESENT");
|
table.put(1, "A", "PRESENT");
|
||||||
table.put(1, "B", "ABSENT");
|
table.put(1, "B", "ABSENT");
|
||||||
|
|
||||||
assertThat(table)
|
assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT");
|
||||||
.hasRowCount(1)
|
|
||||||
.containsValues("ABSENT")
|
|
||||||
.containsCell(1, "B", "ABSENT");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,20 +20,14 @@ public class AssertJJava8Test {
|
||||||
public void givenOptional_shouldAssert() throws Exception {
|
public void givenOptional_shouldAssert() throws Exception {
|
||||||
final Optional<String> givenOptional = Optional.of("something");
|
final Optional<String> givenOptional = Optional.of("something");
|
||||||
|
|
||||||
assertThat(givenOptional)
|
assertThat(givenOptional).isPresent().hasValue("something");
|
||||||
.isPresent()
|
|
||||||
.hasValue("something");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPredicate_shouldAssert() throws Exception {
|
public void givenPredicate_shouldAssert() throws Exception {
|
||||||
final Predicate<String> predicate = s -> s.length() > 4;
|
final Predicate<String> predicate = s -> s.length() > 4;
|
||||||
|
|
||||||
assertThat(predicate)
|
assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b"));
|
||||||
.accepts("aaaaa", "bbbbb")
|
|
||||||
.rejects("a", "b")
|
|
||||||
.acceptsAll(asList("aaaaa", "bbbbb"))
|
|
||||||
.rejectsAll(asList("a", "b"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -41,92 +35,74 @@ public class AssertJJava8Test {
|
||||||
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
||||||
final LocalDate todayDate = LocalDate.now();
|
final LocalDate todayDate = LocalDate.now();
|
||||||
|
|
||||||
assertThat(givenLocalDate)
|
assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||||
.isBefore(LocalDate.of(2020, 7, 8))
|
|
||||||
.isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
|
||||||
|
|
||||||
assertThat(todayDate)
|
assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday();
|
||||||
.isAfter(LocalDate.of(1989, 7, 8))
|
|
||||||
.isToday();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenLocalDateTime_shouldAssert() throws Exception {
|
public void givenLocalDateTime_shouldAssert() throws Exception {
|
||||||
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
||||||
|
|
||||||
assertThat(givenLocalDate)
|
assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||||
.isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenLocalTime_shouldAssert() throws Exception {
|
public void givenLocalTime_shouldAssert() throws Exception {
|
||||||
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
||||||
|
|
||||||
assertThat(givenLocalTime)
|
assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0));
|
||||||
.isAfter(LocalTime.of(1, 0))
|
|
||||||
.hasSameHourAs(LocalTime.of(12, 0));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015);
|
||||||
.flatExtracting(LocalDate::getYear)
|
|
||||||
.contains(2015);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true);
|
||||||
.flatExtracting(LocalDate::isLeapYear)
|
|
||||||
.contains(true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class);
|
||||||
.flatExtracting(Object::getClass)
|
|
||||||
.contains(LocalDate.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6);
|
||||||
.flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
|
|
||||||
.contains(2015, 6);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_shouldSatisfy() throws Exception {
|
public void givenString_shouldSatisfy() throws Exception {
|
||||||
final String givenString = "someString";
|
final String givenString = "someString";
|
||||||
|
|
||||||
assertThat(givenString)
|
assertThat(givenString).satisfies(s -> {
|
||||||
.satisfies(s -> {
|
assertThat(s).isNotEmpty();
|
||||||
assertThat(s).isNotEmpty();
|
assertThat(s).hasSize(10);
|
||||||
assertThat(s).hasSize(10);
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_shouldMatch() throws Exception {
|
public void givenString_shouldMatch() throws Exception {
|
||||||
final String emptyString = "";
|
final String emptyString = "";
|
||||||
|
|
||||||
assertThat(emptyString)
|
assertThat(emptyString).matches(String::isEmpty);
|
||||||
.matches(String::isEmpty);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
||||||
final List<String> givenList = Arrays.asList("");
|
final List<String> givenList = Arrays.asList("");
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||||
.hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,12 +4,12 @@ import com.google.auto.value.AutoValue;
|
||||||
|
|
||||||
@AutoValue
|
@AutoValue
|
||||||
public abstract class AutoValueMoney {
|
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) {
|
public static AutoValueMoney create(String currency, long amount) {
|
||||||
return new AutoValue_AutoValueMoney(currency, amount);
|
return new AutoValue_AutoValueMoney(currency, amount);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,20 +4,20 @@ import com.google.auto.value.AutoValue;
|
||||||
|
|
||||||
@AutoValue
|
@AutoValue
|
||||||
public abstract class AutoValueMoneyWithBuilder {
|
public abstract class AutoValueMoneyWithBuilder {
|
||||||
public abstract String getCurrency();
|
public abstract String getCurrency();
|
||||||
|
|
||||||
public abstract long getAmount();
|
public abstract long getAmount();
|
||||||
|
|
||||||
static Builder builder() {
|
static Builder builder() {
|
||||||
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
||||||
}
|
}
|
||||||
|
|
||||||
@AutoValue.Builder
|
@AutoValue.Builder
|
||||||
abstract static class Builder {
|
abstract static class Builder {
|
||||||
abstract Builder setCurrency(String currency);
|
abstract Builder setCurrency(String currency);
|
||||||
|
|
||||||
abstract Builder setAmount(long amount);
|
abstract Builder setAmount(long amount);
|
||||||
|
|
||||||
abstract AutoValueMoneyWithBuilder build();
|
abstract AutoValueMoneyWithBuilder build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,49 +3,49 @@ package com.baeldung.autovalue;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
public final class Foo {
|
public final class Foo {
|
||||||
private final String text;
|
private final String text;
|
||||||
private final int number;
|
private final int number;
|
||||||
|
|
||||||
public Foo(String text, int number) {
|
public Foo(String text, int number) {
|
||||||
this.text = text;
|
this.text = text;
|
||||||
this.number = number;
|
this.number = number;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getText() {
|
public String getText() {
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getNumber() {
|
public int getNumber() {
|
||||||
return number;
|
return number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return Objects.hash(text, number);
|
return Objects.hash(text, number);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Foo [text=" + text + ", number=" + number + "]";
|
return "Foo [text=" + text + ", number=" + number + "]";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if (this == obj)
|
if (this == obj)
|
||||||
return true;
|
return true;
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
return false;
|
return false;
|
||||||
if (getClass() != obj.getClass())
|
if (getClass() != obj.getClass())
|
||||||
return false;
|
return false;
|
||||||
Foo other = (Foo) obj;
|
Foo other = (Foo) obj;
|
||||||
if (number != other.number)
|
if (number != other.number)
|
||||||
return false;
|
return false;
|
||||||
if (text == null) {
|
if (text == null) {
|
||||||
if (other.text != null)
|
if (other.text != null)
|
||||||
return false;
|
return false;
|
||||||
} else if (!text.equals(other.text))
|
} else if (!text.equals(other.text))
|
||||||
return false;
|
return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,52 +1,53 @@
|
||||||
package com.baeldung.autovalue;
|
package com.baeldung.autovalue;
|
||||||
|
|
||||||
public final class ImmutableMoney {
|
public final class ImmutableMoney {
|
||||||
private final long amount;
|
private final long amount;
|
||||||
private final String currency;
|
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
public ImmutableMoney(long amount, String currency) {
|
||||||
public boolean equals(Object obj) {
|
this.amount = amount;
|
||||||
if (this == obj)
|
this.currency = currency;
|
||||||
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 long getAmount() {
|
@Override
|
||||||
return amount;
|
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() {
|
@Override
|
||||||
return currency;
|
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 long getAmount() {
|
||||||
public String toString() {
|
return amount;
|
||||||
return "ImmutableMoney [amount=" + amount + ", currency=" + currency
|
}
|
||||||
+ "]";
|
|
||||||
}
|
public String getCurrency() {
|
||||||
|
return currency;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,35 +1,34 @@
|
||||||
package com.baeldung.autovalue;
|
package com.baeldung.autovalue;
|
||||||
|
|
||||||
public class MutableMoney {
|
public class MutableMoney {
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "MutableMoney [amount=" + amount + ", currency=" + currency
|
return "MutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||||
+ "]";
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public long getAmount() {
|
public long getAmount() {
|
||||||
return amount;
|
return amount;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setAmount(long amount) {
|
public void setAmount(long amount) {
|
||||||
this.amount = amount;
|
this.amount = amount;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getCurrency() {
|
public String getCurrency() {
|
||||||
return currency;
|
return currency;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCurrency(String currency) {
|
public void setCurrency(String currency) {
|
||||||
this.currency = currency;
|
this.currency = currency;
|
||||||
}
|
}
|
||||||
|
|
||||||
private long amount;
|
private long amount;
|
||||||
private String currency;
|
private String currency;
|
||||||
|
|
||||||
public MutableMoney(long amount, String currency) {
|
public MutableMoney(long amount, String currency) {
|
||||||
super();
|
super();
|
||||||
this.amount = amount;
|
this.amount = amount;
|
||||||
this.currency = currency;
|
this.currency = currency;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,55 +5,59 @@ import static org.junit.Assert.*;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class MoneyUnitTest {
|
public class MoneyUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
MutableMoney m1 = new MutableMoney(10000, "USD");
|
||||||
MutableMoney m2 = new MutableMoney(10000, "USD");
|
MutableMoney m2 = new MutableMoney(10000, "USD");
|
||||||
assertFalse(m1.equals(m2));
|
assertFalse(m1.equals(m2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
||||||
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
||||||
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
||||||
assertTrue(m1.equals(m2));
|
assertTrue(m1.equals(m2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
||||||
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
||||||
assertEquals(m.getAmount(), 10000);
|
assertEquals(m.getAmount(), 10000);
|
||||||
assertEquals(m.getCurrency(), "USD");
|
assertEquals(m.getCurrency(), "USD");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
||||||
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
||||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||||
assertTrue(m1.equals(m2));
|
assertTrue(m1.equals(m2));
|
||||||
}
|
}
|
||||||
@Test
|
|
||||||
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
@Test
|
||||||
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
||||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
||||||
assertFalse(m1.equals(m2));
|
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();
|
@Test
|
||||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
||||||
assertTrue(m1.equals(m2));
|
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
}
|
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
@Test
|
assertTrue(m1.equals(m2));
|
||||||
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
}
|
||||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
|
||||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
@Test
|
||||||
assertFalse(m1.equals(m2));
|
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
||||||
}
|
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
@Test
|
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
||||||
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
assertFalse(m1.equals(m2));
|
||||||
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
}
|
||||||
assertEquals(m.getAmount(), 5000);
|
|
||||||
assertEquals(m.getCurrency(), "USD");
|
@Test
|
||||||
}
|
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
||||||
|
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
|
assertEquals(m.getAmount(), 5000);
|
||||||
|
assertEquals(m.getCurrency(), "USD");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,16 +1,16 @@
|
||||||
package com.baeldung.java9.language;
|
package com.baeldung.java9.language;
|
||||||
|
|
||||||
public interface PrivateInterface {
|
public interface PrivateInterface {
|
||||||
|
|
||||||
private static String staticPrivate() {
|
private static String staticPrivate() {
|
||||||
return "static private";
|
return "static private";
|
||||||
}
|
}
|
||||||
|
|
||||||
private String instancePrivate() {
|
private String instancePrivate() {
|
||||||
return "instance private";
|
return "instance private";
|
||||||
}
|
}
|
||||||
|
|
||||||
public default void check(){
|
public default void check() {
|
||||||
String result = staticPrivate();
|
String result = staticPrivate();
|
||||||
if (!result.equals("static private"))
|
if (!result.equals("static private"))
|
||||||
throw new AssertionError("Incorrect result for static private interface method");
|
throw new AssertionError("Incorrect result for static private interface method");
|
||||||
|
|
|
@ -8,37 +8,36 @@ import java.time.Duration;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
|
||||||
public class ProcessUtils {
|
public class ProcessUtils {
|
||||||
|
|
||||||
public static String getClassPath(){
|
public static String getClassPath() {
|
||||||
String cp = System.getProperty("java.class.path");
|
String cp = System.getProperty("java.class.path");
|
||||||
System.out.println("ClassPath is "+cp);
|
System.out.println("ClassPath is " + cp);
|
||||||
return cp;
|
return cp;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static File getJavaCmd() throws IOException{
|
public static File getJavaCmd() throws IOException {
|
||||||
String javaHome = System.getProperty("java.home");
|
String javaHome = System.getProperty("java.home");
|
||||||
File javaCmd;
|
File javaCmd;
|
||||||
if(System.getProperty("os.name").startsWith("Win")){
|
if (System.getProperty("os.name").startsWith("Win")) {
|
||||||
javaCmd = new File(javaHome, "bin/java.exe");
|
javaCmd = new File(javaHome, "bin/java.exe");
|
||||||
}else{
|
} else {
|
||||||
javaCmd = new File(javaHome, "bin/java");
|
javaCmd = new File(javaHome, "bin/java");
|
||||||
}
|
}
|
||||||
if(javaCmd.canExecute()){
|
if (javaCmd.canExecute()) {
|
||||||
return javaCmd;
|
return javaCmd;
|
||||||
}else{
|
} else {
|
||||||
throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable");
|
throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getMainClass(){
|
public static String getMainClass() {
|
||||||
return System.getProperty("sun.java.command");
|
return System.getProperty("sun.java.command");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getSystemProperties(){
|
public static String getSystemProperties() {
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) );
|
System.getProperties().forEach((s1, s2) -> sb.append(s1 + " - " + s2));
|
||||||
return sb.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,7 +8,6 @@ public class ServiceMain {
|
||||||
ProcessHandle thisProcess = ProcessHandle.current();
|
ProcessHandle thisProcess = ProcessHandle.current();
|
||||||
long pid = thisProcess.getPid();
|
long pid = thisProcess.getPid();
|
||||||
|
|
||||||
|
|
||||||
Optional<String[]> opArgs = Optional.ofNullable(args);
|
Optional<String[]> opArgs = Optional.ofNullable(args);
|
||||||
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));
|
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));
|
||||||
|
|
||||||
|
|
|
@ -19,10 +19,7 @@ public class Java9OptionalsStreamTest {
|
||||||
public void filterOutPresentOptionalsWithFilter() {
|
public void filterOutPresentOptionalsWithFilter() {
|
||||||
assertEquals(4, listOfOptionals.size());
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
List<String> filteredList = listOfOptionals.stream()
|
List<String> filteredList = listOfOptionals.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
|
||||||
.filter(Optional::isPresent)
|
|
||||||
.map(Optional::get)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(2, filteredList.size());
|
assertEquals(2, filteredList.size());
|
||||||
assertEquals("foo", filteredList.get(0));
|
assertEquals("foo", filteredList.get(0));
|
||||||
|
@ -33,9 +30,7 @@ public class Java9OptionalsStreamTest {
|
||||||
public void filterOutPresentOptionalsWithFlatMap() {
|
public void filterOutPresentOptionalsWithFlatMap() {
|
||||||
assertEquals(4, listOfOptionals.size());
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
List<String> filteredList = listOfOptionals.stream()
|
List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList());
|
||||||
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
assertEquals(2, filteredList.size());
|
assertEquals(2, filteredList.size());
|
||||||
|
|
||||||
assertEquals("foo", filteredList.get(0));
|
assertEquals("foo", filteredList.get(0));
|
||||||
|
@ -46,9 +41,7 @@ public class Java9OptionalsStreamTest {
|
||||||
public void filterOutPresentOptionalsWithFlatMap2() {
|
public void filterOutPresentOptionalsWithFlatMap2() {
|
||||||
assertEquals(4, listOfOptionals.size());
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
List<String> filteredList = listOfOptionals.stream()
|
List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList());
|
||||||
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
assertEquals(2, filteredList.size());
|
assertEquals(2, filteredList.size());
|
||||||
|
|
||||||
assertEquals("foo", filteredList.get(0));
|
assertEquals("foo", filteredList.get(0));
|
||||||
|
@ -59,9 +52,7 @@ public class Java9OptionalsStreamTest {
|
||||||
public void filterOutPresentOptionalsWithJava9() {
|
public void filterOutPresentOptionalsWithJava9() {
|
||||||
assertEquals(4, listOfOptionals.size());
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
List<String> filteredList = listOfOptionals.stream()
|
List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
|
||||||
.flatMap(Optional::stream)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(2, filteredList.size());
|
assertEquals(2, filteredList.size());
|
||||||
assertEquals("foo", filteredList.get(0));
|
assertEquals("foo", filteredList.get(0));
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
package com.baeldung.java9;
|
package com.baeldung.java9;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertSame;
|
import static org.junit.Assert.assertSame;
|
||||||
|
|
||||||
|
@ -13,7 +13,6 @@ import org.junit.Test;
|
||||||
|
|
||||||
public class MultiResultionImageTest {
|
public class MultiResultionImageTest {
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void baseMultiResImageTest() {
|
public void baseMultiResImageTest() {
|
||||||
int baseIndex = 1;
|
int baseIndex = 1;
|
||||||
|
@ -38,10 +37,8 @@ public class MultiResultionImageTest {
|
||||||
return 8 * (i + 1);
|
return 8 * (i + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private static BufferedImage createImage(int i) {
|
private static BufferedImage createImage(int i) {
|
||||||
return new BufferedImage(getSize(i), getSize(i),
|
return new BufferedImage(getSize(i), getSize(i), BufferedImage.TYPE_INT_RGB);
|
||||||
BufferedImage.TYPE_INT_RGB);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,4 @@
|
||||||
package com.baeldung.java9.httpclient;
|
package com.baeldung.java9.httpclient;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
import static java.net.HttpURLConnection.HTTP_OK;
|
import static java.net.HttpURLConnection.HTTP_OK;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
@ -28,8 +26,8 @@ import org.junit.Test;
|
||||||
|
|
||||||
public class SimpleHttpRequestsTest {
|
public class SimpleHttpRequestsTest {
|
||||||
|
|
||||||
private URI httpURI;
|
private URI httpURI;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void init() throws URISyntaxException {
|
public void init() throws URISyntaxException {
|
||||||
httpURI = new URI("http://www.baeldung.com/");
|
httpURI = new URI("http://www.baeldung.com/");
|
||||||
|
@ -37,26 +35,26 @@ public class SimpleHttpRequestsTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void quickGet() throws IOException, InterruptedException, URISyntaxException {
|
public void quickGet() throws IOException, InterruptedException, URISyntaxException {
|
||||||
HttpRequest request = HttpRequest.create( httpURI ).GET();
|
HttpRequest request = HttpRequest.create(httpURI).GET();
|
||||||
HttpResponse response = request.response();
|
HttpResponse response = request.response();
|
||||||
int responseStatusCode = response.statusCode();
|
int responseStatusCode = response.statusCode();
|
||||||
String responseBody = response.body(HttpResponse.asString());
|
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
|
@Test
|
||||||
public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{
|
public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException {
|
||||||
HttpRequest request = HttpRequest.create(httpURI).GET();
|
HttpRequest request = HttpRequest.create(httpURI).GET();
|
||||||
long before = System.currentTimeMillis();
|
long before = System.currentTimeMillis();
|
||||||
CompletableFuture<HttpResponse> futureResponse = request.responseAsync();
|
CompletableFuture<HttpResponse> futureResponse = request.responseAsync();
|
||||||
futureResponse.thenAccept( response -> {
|
futureResponse.thenAccept(response -> {
|
||||||
String responseBody = response.body(HttpResponse.asString());
|
String responseBody = response.body(HttpResponse.asString());
|
||||||
});
|
});
|
||||||
HttpResponse resp = futureResponse.get();
|
HttpResponse resp = futureResponse.get();
|
||||||
HttpHeaders hs = resp.headers();
|
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
|
@Test
|
||||||
public void postMehtod() throws URISyntaxException, IOException, InterruptedException {
|
public void postMehtod() throws URISyntaxException, IOException, InterruptedException {
|
||||||
HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI);
|
HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI);
|
||||||
|
@ -66,61 +64,63 @@ public class SimpleHttpRequestsTest {
|
||||||
int statusCode = response.statusCode();
|
int statusCode = response.statusCode();
|
||||||
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{
|
public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException {
|
||||||
CookieManager cManager = new CookieManager();
|
CookieManager cManager = new CookieManager();
|
||||||
cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
|
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();
|
HttpClient.Builder hcBuilder = HttpClient.create();
|
||||||
hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam);
|
hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam);
|
||||||
HttpClient httpClient = hcBuilder.build();
|
HttpClient httpClient = hcBuilder.build();
|
||||||
HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com"));
|
HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com"));
|
||||||
|
|
||||||
HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET();
|
HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET();
|
||||||
HttpResponse response = request.response();
|
HttpResponse response = request.response();
|
||||||
int statusCode = response.statusCode();
|
int statusCode = response.statusCode();
|
||||||
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{
|
SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException {
|
||||||
SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters();
|
SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters();
|
||||||
String [] proto = sslP1.getApplicationProtocols();
|
String[] proto = sslP1.getApplicationProtocols();
|
||||||
String [] cifers = sslP1.getCipherSuites();
|
String[] cifers = sslP1.getCipherSuites();
|
||||||
System.out.println(printStringArr(proto));
|
System.out.println(printStringArr(proto));
|
||||||
System.out.println(printStringArr(cifers));
|
System.out.println(printStringArr(cifers));
|
||||||
return sslP1;
|
return sslP1;
|
||||||
}
|
}
|
||||||
|
|
||||||
String printStringArr(String ... args ){
|
String printStringArr(String... args) {
|
||||||
if(args == null){
|
if (args == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
for (String s : args){
|
for (String s : args) {
|
||||||
sb.append(s);
|
sb.append(s);
|
||||||
sb.append("\n");
|
sb.append("\n");
|
||||||
}
|
}
|
||||||
return sb.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
String printHeaders(HttpHeaders h){
|
String printHeaders(HttpHeaders h) {
|
||||||
if(h == null){
|
if (h == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
Map<String, List<String>> hMap = h.map();
|
Map<String, List<String>> hMap = h.map();
|
||||||
for(String k : hMap.keySet()){
|
for (String k : hMap.keySet()) {
|
||||||
sb.append(k).append(":");
|
sb.append(k).append(":");
|
||||||
List<String> l = hMap.get(k);
|
List<String> l = hMap.get(k);
|
||||||
if( l != null ){
|
if (l != null) {
|
||||||
l.forEach( s -> { sb.append(s).append(","); } );
|
l.forEach(s -> {
|
||||||
}
|
sb.append(s).append(",");
|
||||||
sb.append("\n");
|
});
|
||||||
}
|
}
|
||||||
return sb.toString();
|
sb.append("\n");
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,7 +7,7 @@ public class TryWithResourcesTest {
|
||||||
|
|
||||||
static int closeCount = 0;
|
static int closeCount = 0;
|
||||||
|
|
||||||
static class MyAutoCloseable implements AutoCloseable{
|
static class MyAutoCloseable implements AutoCloseable {
|
||||||
final FinalWrapper finalWrapper = new FinalWrapper();
|
final FinalWrapper finalWrapper = new FinalWrapper();
|
||||||
|
|
||||||
public void close() {
|
public void close() {
|
||||||
|
@ -57,7 +57,6 @@ public class TryWithResourcesTest {
|
||||||
assertEquals("Expected and Actual does not match", 5, closeCount);
|
assertEquals("Expected and Actual does not match", 5, closeCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static class CloseableException extends Exception implements AutoCloseable {
|
static class CloseableException extends Exception implements AutoCloseable {
|
||||||
@Override
|
@Override
|
||||||
public void close() {
|
public void close() {
|
||||||
|
@ -66,5 +65,3 @@ public class TryWithResourcesTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -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<Integer> numbers = List.of(1, 2, 3, 5, 5);
|
||||||
|
|
||||||
|
Map<Integer, Long> 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<Blog> blogs = List.of(blog1, blog2);
|
||||||
|
|
||||||
|
Map<String, List<List<String>>> 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<String, List<String>> 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<String> comments;
|
||||||
|
|
||||||
|
public Blog(String authorName, String... comments) {
|
||||||
|
this.authorName = authorName;
|
||||||
|
this.comments = List.of(comments);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthorName() {
|
||||||
|
return this.authorName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getComments() {
|
||||||
|
return this.comments;
|
||||||
|
}
|
||||||
|
}
|
|
@ -17,16 +17,11 @@ public class StreamFeaturesTest {
|
||||||
public static class TakeAndDropWhileTest {
|
public static class TakeAndDropWhileTest {
|
||||||
|
|
||||||
public Stream<String> getStreamAfterTakeWhileOperation() {
|
public Stream<String> getStreamAfterTakeWhileOperation() {
|
||||||
return Stream
|
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10);
|
||||||
.iterate("", s -> s + "s")
|
|
||||||
.takeWhile(s -> s.length() < 10);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Stream<String> getStreamAfterDropWhileOperation() {
|
public Stream<String> getStreamAfterDropWhileOperation() {
|
||||||
return Stream
|
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10).dropWhile(s -> !s.contains("sssss"));
|
||||||
.iterate("", s -> s + "s")
|
|
||||||
.takeWhile(s -> s.length() < 10)
|
|
||||||
.dropWhile(s -> !s.contains("sssss"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -72,25 +67,25 @@ public class StreamFeaturesTest {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class OfNullableTest {
|
public static class OfNullableTest {
|
||||||
|
|
||||||
private List<String> collection = Arrays.asList("A", "B", "C");
|
private List<String> collection = Arrays.asList("A", "B", "C");
|
||||||
private Map<String, Integer> map = new HashMap<>() {{
|
private Map<String, Integer> map = new HashMap<>() {
|
||||||
put("A", 10);
|
{
|
||||||
put("C", 30);
|
put("A", 10);
|
||||||
}};
|
put("C", 30);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
private Stream<Integer> getStreamWithOfNullable() {
|
private Stream<Integer> getStreamWithOfNullable() {
|
||||||
return collection.stream()
|
return collection.stream().flatMap(s -> Stream.ofNullable(map.get(s)));
|
||||||
.flatMap(s -> Stream.ofNullable(map.get(s)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Stream<Integer> getStream() {
|
private Stream<Integer> getStream() {
|
||||||
return collection.stream()
|
return collection.stream().flatMap(s -> {
|
||||||
.flatMap(s -> {
|
Integer temp = map.get(s);
|
||||||
Integer temp = map.get(s);
|
return temp != null ? Stream.of(temp) : Stream.empty();
|
||||||
return temp != null ? Stream.of(temp) : Stream.empty();
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Integer> testOfNullableFrom(Stream<Integer> stream) {
|
private List<Integer> testOfNullableFrom(Stream<Integer> stream) {
|
||||||
|
@ -107,10 +102,7 @@ public class StreamFeaturesTest {
|
||||||
@Test
|
@Test
|
||||||
public void testOfNullable() {
|
public void testOfNullable() {
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(testOfNullableFrom(getStream()), testOfNullableFrom(getStreamWithOfNullable()));
|
||||||
testOfNullableFrom(getStream()),
|
|
||||||
testOfNullableFrom(getStreamWithOfNullable())
|
|
||||||
);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -22,90 +22,89 @@ import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class ProcessApi {
|
public class ProcessApi {
|
||||||
|
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void init() {
|
public void init() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void processInfoExample()throws NoSuchAlgorithmException{
|
public void processInfoExample() throws NoSuchAlgorithmException {
|
||||||
ProcessHandle self = ProcessHandle.current();
|
ProcessHandle self = ProcessHandle.current();
|
||||||
long PID = self.getPid();
|
long PID = self.getPid();
|
||||||
ProcessHandle.Info procInfo = self.info();
|
ProcessHandle.Info procInfo = self.info();
|
||||||
Optional<String[]> args = procInfo.arguments();
|
Optional<String[]> args = procInfo.arguments();
|
||||||
Optional<String> cmd = procInfo.commandLine();
|
Optional<String> cmd = procInfo.commandLine();
|
||||||
Optional<Instant> startTime = procInfo.startInstant();
|
Optional<Instant> startTime = procInfo.startInstant();
|
||||||
Optional<Duration> cpuUsage = procInfo.totalCpuDuration();
|
Optional<Duration> cpuUsage = procInfo.totalCpuDuration();
|
||||||
|
|
||||||
waistCPU();
|
waistCPU();
|
||||||
System.out.println("Args "+ args);
|
System.out.println("Args " + args);
|
||||||
System.out.println("Command " +cmd.orElse("EmptyCmd"));
|
System.out.println("Command " + cmd.orElse("EmptyCmd"));
|
||||||
System.out.println("Start time: "+ startTime.get().toString());
|
System.out.println("Start time: " + startTime.get().toString());
|
||||||
System.out.println(cpuUsage.get().toMillis());
|
System.out.println(cpuUsage.get().toMillis());
|
||||||
|
|
||||||
Stream<ProcessHandle> allProc = ProcessHandle.current().children();
|
Stream<ProcessHandle> allProc = ProcessHandle.current().children();
|
||||||
allProc.forEach(p -> {
|
allProc.forEach(p -> {
|
||||||
System.out.println("Proc "+ p.getPid());
|
System.out.println("Proc " + p.getPid());
|
||||||
});
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void createAndDestroyProcess() throws IOException, InterruptedException{
|
public void createAndDestroyProcess() throws IOException, InterruptedException {
|
||||||
int numberOfChildProcesses = 5;
|
int numberOfChildProcesses = 5;
|
||||||
for(int i=0; i < numberOfChildProcesses; i++){
|
for (int i = 0; i < numberOfChildProcesses; i++) {
|
||||||
createNewJVM(ServiceMain.class, i).getPid();
|
createNewJVM(ServiceMain.class, i).getPid();
|
||||||
}
|
}
|
||||||
|
|
||||||
Stream<ProcessHandle> childProc = ProcessHandle.current().children();
|
Stream<ProcessHandle> childProc = ProcessHandle.current().children();
|
||||||
assertEquals( childProc.count(), numberOfChildProcesses);
|
assertEquals(childProc.count(), numberOfChildProcesses);
|
||||||
|
|
||||||
childProc = ProcessHandle.current().children();
|
childProc = ProcessHandle.current().children();
|
||||||
childProc.forEach(processHandle -> {
|
childProc.forEach(processHandle -> {
|
||||||
assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive());
|
assertTrue("Process " + processHandle.getPid() + " should be alive!", processHandle.isAlive());
|
||||||
CompletableFuture<ProcessHandle> onProcExit = processHandle.onExit();
|
CompletableFuture<ProcessHandle> onProcExit = processHandle.onExit();
|
||||||
onProcExit.thenAccept(procHandle -> {
|
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);
|
Thread.sleep(10000);
|
||||||
|
|
||||||
childProc = ProcessHandle.current().children();
|
childProc = ProcessHandle.current().children();
|
||||||
childProc.forEach(procHandle -> {
|
childProc.forEach(procHandle -> {
|
||||||
assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy());
|
assertTrue("Could not kill process " + procHandle.getPid(), procHandle.destroy());
|
||||||
});
|
});
|
||||||
|
|
||||||
Thread.sleep(5000);
|
Thread.sleep(5000);
|
||||||
|
|
||||||
childProc = ProcessHandle.current().children();
|
childProc = ProcessHandle.current().children();
|
||||||
childProc.forEach(procHandle -> {
|
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<String> cmdParams = new ArrayList<String>(5);
|
ArrayList<String> cmdParams = new ArrayList<String>(5);
|
||||||
cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath());
|
cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath());
|
||||||
cmdParams.add("-cp");
|
cmdParams.add("-cp");
|
||||||
cmdParams.add(ProcessUtils.getClassPath());
|
cmdParams.add(ProcessUtils.getClassPath());
|
||||||
cmdParams.add(mainClass.getName());
|
cmdParams.add(mainClass.getName());
|
||||||
cmdParams.add("Service "+ number);
|
cmdParams.add("Service " + number);
|
||||||
ProcessBuilder myService = new ProcessBuilder(cmdParams);
|
ProcessBuilder myService = new ProcessBuilder(cmdParams);
|
||||||
myService.inheritIO();
|
myService.inheritIO();
|
||||||
return myService.start();
|
return myService.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void waistCPU() throws NoSuchAlgorithmException{
|
private void waistCPU() throws NoSuchAlgorithmException {
|
||||||
ArrayList<Integer> randArr = new ArrayList<Integer>(4096);
|
ArrayList<Integer> randArr = new ArrayList<Integer>(4096);
|
||||||
SecureRandom sr = SecureRandom.getInstanceStrong();
|
SecureRandom sr = SecureRandom.getInstanceStrong();
|
||||||
Duration somecpu = Duration.ofMillis(4200L);
|
Duration somecpu = Duration.ofMillis(4200L);
|
||||||
Instant end = Instant.now().plus(somecpu);
|
Instant end = Instant.now().plus(somecpu);
|
||||||
while (Instant.now().isBefore(end)) {
|
while (Instant.now().isBefore(end)) {
|
||||||
//System.out.println(sr.nextInt());
|
// System.out.println(sr.nextInt());
|
||||||
randArr.add( sr.nextInt() );
|
randArr.add(sr.nextInt());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -16,3 +16,7 @@
|
||||||
*.txt
|
*.txt
|
||||||
/bin/
|
/bin/
|
||||||
/temp
|
/temp
|
||||||
|
|
||||||
|
#IntelliJ specific
|
||||||
|
.idea
|
||||||
|
*.iml
|
|
@ -53,3 +53,4 @@
|
||||||
- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size)
|
- [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 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)
|
- [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)
|
||||||
|
|
|
@ -63,6 +63,7 @@
|
||||||
<artifactId>grep4j</artifactId>
|
<artifactId>grep4j</artifactId>
|
||||||
<version>${grep4j.version}</version>
|
<version>${grep4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- web -->
|
<!-- web -->
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
|
@ -352,7 +353,7 @@
|
||||||
<logback.version>1.1.7</logback.version>
|
<logback.version>1.1.7</logback.version>
|
||||||
|
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>19.0</guava.version>
|
<guava.version>21.0</guava.version>
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
<bouncycastle.version>1.55</bouncycastle.version>
|
<bouncycastle.version>1.55</bouncycastle.version>
|
||||||
<commons-codec.version>1.10</commons-codec.version>
|
<commons-codec.version>1.10</commons-codec.version>
|
||||||
|
|
|
@ -7,25 +7,24 @@ import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||||
|
|
||||||
public class RunAlgorithm {
|
public class RunAlgorithm {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Scanner in = new Scanner(System.in);
|
Scanner in = new Scanner(System.in);
|
||||||
System.out.println("Run algorithm:");
|
System.out.println("Run algorithm:");
|
||||||
System.out.println("1 - Simulated Annealing");
|
System.out.println("1 - Simulated Annealing");
|
||||||
System.out.println("2 - Slope One");
|
System.out.println("2 - Slope One");
|
||||||
int decision = in.nextInt();
|
int decision = in.nextInt();
|
||||||
switch (decision) {
|
switch (decision) {
|
||||||
case 1:
|
case 1:
|
||||||
System.out.println(
|
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
break;
|
||||||
break;
|
case 2:
|
||||||
case 2:
|
SlopeOne.slopeOne(3);
|
||||||
SlopeOne.slopeOne(3);
|
break;
|
||||||
break;
|
default:
|
||||||
default:
|
System.out.println("Unknown option");
|
||||||
System.out.println("Unknown option");
|
break;
|
||||||
break;
|
}
|
||||||
}
|
in.close();
|
||||||
in.close();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,18 +5,18 @@ import lombok.Data;
|
||||||
@Data
|
@Data
|
||||||
public class City {
|
public class City {
|
||||||
|
|
||||||
private int x;
|
private int x;
|
||||||
private int y;
|
private int y;
|
||||||
|
|
||||||
public City() {
|
public City() {
|
||||||
this.x = (int) (Math.random() * 500);
|
this.x = (int) (Math.random() * 500);
|
||||||
this.y = (int) (Math.random() * 500);
|
this.y = (int) (Math.random() * 500);
|
||||||
}
|
}
|
||||||
|
|
||||||
public double distanceToCity(City city) {
|
public double distanceToCity(City city) {
|
||||||
int x = Math.abs(getX() - city.getX());
|
int x = Math.abs(getX() - city.getX());
|
||||||
int y = Math.abs(getY() - city.getY());
|
int y = Math.abs(getY() - city.getY());
|
||||||
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -24,7 +24,7 @@ public class SimulatedAnnealing {
|
||||||
}
|
}
|
||||||
t *= coolingRate;
|
t *= coolingRate;
|
||||||
} else {
|
} else {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (i % 100 == 0) {
|
if (i % 100 == 0) {
|
||||||
System.out.println("Iteration #" + i);
|
System.out.println("Iteration #" + i);
|
||||||
|
|
|
@ -11,26 +11,25 @@ import lombok.Data;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class InputData {
|
public class InputData {
|
||||||
|
|
||||||
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"),
|
|
||||||
new Item("Snacks"));
|
|
||||||
|
|
||||||
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), new Item("Snacks"));
|
||||||
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
|
||||||
HashMap<Item, Double> newUser;
|
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
||||||
Set<Item> newRecommendationSet;
|
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
||||||
for (int i = 0; i < numberOfUsers; i++) {
|
HashMap<Item, Double> newUser;
|
||||||
newUser = new HashMap<Item, Double>();
|
Set<Item> newRecommendationSet;
|
||||||
newRecommendationSet = new HashSet<>();
|
for (int i = 0; i < numberOfUsers; i++) {
|
||||||
for (int j = 0; j < 3; j++) {
|
newUser = new HashMap<Item, Double>();
|
||||||
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
newRecommendationSet = new HashSet<>();
|
||||||
}
|
for (int j = 0; j < 3; j++) {
|
||||||
for (Item item : newRecommendationSet) {
|
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
||||||
newUser.put(item, Math.random());
|
}
|
||||||
}
|
for (Item item : newRecommendationSet) {
|
||||||
data.put(new User("User " + i), newUser);
|
newUser.put(item, Math.random());
|
||||||
}
|
}
|
||||||
return data;
|
data.put(new User("User " + i), newUser);
|
||||||
}
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,5 +9,5 @@ import lombok.NoArgsConstructor;
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class Item {
|
public class Item {
|
||||||
|
|
||||||
private String itemName;
|
private String itemName;
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,114 +11,114 @@ import java.util.Map.Entry;
|
||||||
*/
|
*/
|
||||||
public class SlopeOne {
|
public class SlopeOne {
|
||||||
|
|
||||||
private static Map<Item, Map<Item, Double>> diff = new HashMap<>();
|
private static Map<Item, Map<Item, Double>> diff = new HashMap<>();
|
||||||
private static Map<Item, Map<Item, Integer>> freq = new HashMap<>();
|
private static Map<Item, Map<Item, Integer>> freq = new HashMap<>();
|
||||||
private static Map<User, HashMap<Item, Double>> inputData;
|
private static Map<User, HashMap<Item, Double>> inputData;
|
||||||
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
|
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
|
||||||
|
|
||||||
public static void slopeOne(int numberOfUsers) {
|
public static void slopeOne(int numberOfUsers) {
|
||||||
inputData = InputData.initializeData(numberOfUsers);
|
inputData = InputData.initializeData(numberOfUsers);
|
||||||
System.out.println("Slope One - Before the Prediction\n");
|
System.out.println("Slope One - Before the Prediction\n");
|
||||||
buildDifferencesMatrix(inputData);
|
buildDifferencesMatrix(inputData);
|
||||||
System.out.println("\nSlope One - With Predictions\n");
|
System.out.println("\nSlope One - With Predictions\n");
|
||||||
predict(inputData);
|
predict(inputData);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Based on the available data, calculate the relationships between the
|
* Based on the available data, calculate the relationships between the
|
||||||
* items and number of occurences
|
* items and number of occurences
|
||||||
*
|
*
|
||||||
* @param data
|
* @param data
|
||||||
* existing user data and their items' ratings
|
* existing user data and their items' ratings
|
||||||
*/
|
*/
|
||||||
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
||||||
for (HashMap<Item, Double> user : data.values()) {
|
for (HashMap<Item, Double> user : data.values()) {
|
||||||
for (Entry<Item, Double> e : user.entrySet()) {
|
for (Entry<Item, Double> e : user.entrySet()) {
|
||||||
if (!diff.containsKey(e.getKey())) {
|
if (!diff.containsKey(e.getKey())) {
|
||||||
diff.put(e.getKey(), new HashMap<Item, Double>());
|
diff.put(e.getKey(), new HashMap<Item, Double>());
|
||||||
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
||||||
}
|
}
|
||||||
for (Entry<Item, Double> e2 : user.entrySet()) {
|
for (Entry<Item, Double> e2 : user.entrySet()) {
|
||||||
int oldCount = 0;
|
int oldCount = 0;
|
||||||
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
||||||
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
||||||
}
|
}
|
||||||
double oldDiff = 0.0;
|
double oldDiff = 0.0;
|
||||||
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
||||||
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
||||||
}
|
}
|
||||||
double observedDiff = e.getValue() - e2.getValue();
|
double observedDiff = e.getValue() - e2.getValue();
|
||||||
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
||||||
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (Item j : diff.keySet()) {
|
for (Item j : diff.keySet()) {
|
||||||
for (Item i : diff.get(j).keySet()) {
|
for (Item i : diff.get(j).keySet()) {
|
||||||
double oldValue = diff.get(j).get(i).doubleValue();
|
double oldValue = diff.get(j).get(i).doubleValue();
|
||||||
int count = freq.get(j).get(i).intValue();
|
int count = freq.get(j).get(i).intValue();
|
||||||
diff.get(j).put(i, oldValue / count);
|
diff.get(j).put(i, oldValue / count);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
printData(data);
|
printData(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Based on existing data predict all missing ratings. If prediction is not
|
* Based on existing data predict all missing ratings. If prediction is not
|
||||||
* possible, the value will be equal to -1
|
* possible, the value will be equal to -1
|
||||||
*
|
*
|
||||||
* @param data
|
* @param data
|
||||||
* existing user data and their items' ratings
|
* existing user data and their items' ratings
|
||||||
*/
|
*/
|
||||||
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
||||||
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
||||||
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
||||||
for (Item j : diff.keySet()) {
|
for (Item j : diff.keySet()) {
|
||||||
uFreq.put(j, 0);
|
uFreq.put(j, 0);
|
||||||
uPred.put(j, 0.0);
|
uPred.put(j, 0.0);
|
||||||
}
|
}
|
||||||
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
||||||
for (Item j : e.getValue().keySet()) {
|
for (Item j : e.getValue().keySet()) {
|
||||||
for (Item k : diff.keySet()) {
|
for (Item k : diff.keySet()) {
|
||||||
try {
|
try {
|
||||||
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
||||||
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
||||||
uPred.put(k, uPred.get(k) + finalValue);
|
uPred.put(k, uPred.get(k) + finalValue);
|
||||||
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
||||||
} catch (NullPointerException e1) {
|
} catch (NullPointerException e1) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
||||||
for (Item j : uPred.keySet()) {
|
for (Item j : uPred.keySet()) {
|
||||||
if (uFreq.get(j) > 0) {
|
if (uFreq.get(j) > 0) {
|
||||||
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (Item j : InputData.items) {
|
for (Item j : InputData.items) {
|
||||||
if (e.getValue().containsKey(j)) {
|
if (e.getValue().containsKey(j)) {
|
||||||
clean.put(j, e.getValue().get(j));
|
clean.put(j, e.getValue().get(j));
|
||||||
} else {
|
} else {
|
||||||
clean.put(j, -1.0);
|
clean.put(j, -1.0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outputData.put(e.getKey(), clean);
|
outputData.put(e.getKey(), clean);
|
||||||
}
|
}
|
||||||
printData(outputData);
|
printData(outputData);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
||||||
for (User user : data.keySet()) {
|
for (User user : data.keySet()) {
|
||||||
System.out.println(user.getUsername() + ":");
|
System.out.println(user.getUsername() + ":");
|
||||||
print(data.get(user));
|
print(data.get(user));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void print(HashMap<Item, Double> hashMap) {
|
private static void print(HashMap<Item, Double> hashMap) {
|
||||||
NumberFormat formatter = new DecimalFormat("#0.000");
|
NumberFormat formatter = new DecimalFormat("#0.000");
|
||||||
for (Item j : hashMap.keySet()) {
|
for (Item j : hashMap.keySet()) {
|
||||||
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,7 +8,7 @@ import lombok.NoArgsConstructor;
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class User {
|
public class User {
|
||||||
|
|
||||||
private String username;
|
private String username;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<Integer> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.concurrent.blockingqueue;
|
||||||
|
|
||||||
|
import java.util.concurrent.BlockingQueue;
|
||||||
|
|
||||||
|
public class NumbersConsumer implements Runnable {
|
||||||
|
private final BlockingQueue<Integer> queue;
|
||||||
|
private final int poisonPill;
|
||||||
|
|
||||||
|
public NumbersConsumer(BlockingQueue<Integer> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<Integer> numbersQueue;
|
||||||
|
private final int poisonPill;
|
||||||
|
private final int poisonPillPerProducer;
|
||||||
|
|
||||||
|
public NumbersProducer(BlockingQueue<Integer> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<String> outputScraper;
|
||||||
|
private final CountDownLatch countDownLatch;
|
||||||
|
|
||||||
|
public BrokenWorker(final List<String> 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");
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<String> outputScraper;
|
||||||
|
private final CountDownLatch readyThreadCounter;
|
||||||
|
private final CountDownLatch callingThreadBlocker;
|
||||||
|
private final CountDownLatch completedThreadCounter;
|
||||||
|
|
||||||
|
public WaitingWorker(final List<String> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<String> outputScraper;
|
||||||
|
private final CountDownLatch countDownLatch;
|
||||||
|
|
||||||
|
public Worker(final List<String> 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();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.concurrent.future;
|
||||||
|
|
||||||
|
import java.util.concurrent.RecursiveTask;
|
||||||
|
|
||||||
|
public class FactorialSquareCalculator extends RecursiveTask<Integer> {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package com.baeldung.concurrent.future;
|
||||||
|
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
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<Integer> calculate(Integer input) {
|
||||||
|
return executor.submit(new Callable<Integer>() {
|
||||||
|
@Override
|
||||||
|
public Integer call() throws Exception {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
return input * input;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
|
@ -10,13 +10,11 @@ public class MyLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
|
||||||
*/
|
*/
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
private static final int MAX_ENTRIES = 5;
|
private static final int MAX_ENTRIES = 5;
|
||||||
|
|
||||||
|
|
||||||
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
|
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
|
||||||
super(initialCapacity, loadFactor, accessOrder);
|
super(initialCapacity, loadFactor, accessOrder);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean removeEldestEntry(Map.Entry eldest) {
|
protected boolean removeEldestEntry(Map.Entry eldest) {
|
||||||
return size() > MAX_ENTRIES;
|
return size() > MAX_ENTRIES;
|
||||||
|
|
|
@ -0,0 +1,57 @@
|
||||||
|
package com.baeldung.java8.lambda.exceptions;
|
||||||
|
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public class LambdaExceptionWrappers {
|
||||||
|
|
||||||
|
public static Consumer<Integer> lambdaWrapper(Consumer<Integer> consumer) {
|
||||||
|
return i -> {
|
||||||
|
try {
|
||||||
|
consumer.accept(i);
|
||||||
|
} catch (ArithmeticException e) {
|
||||||
|
System.err.println("Arithmetic Exception occured : " + e.getMessage());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static <T, E extends Exception> Consumer<T> consumerWrapper(Consumer<T> consumer, Class<E> 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 <T> Consumer<T> throwingConsumerWrapper(ThrowingConsumer<T, Exception> throwingConsumer) {
|
||||||
|
return i -> {
|
||||||
|
try {
|
||||||
|
throwingConsumer.accept(i);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException(ex);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T, E extends Exception> Consumer<T> handlingConsumerWrapper(ThrowingConsumer<T, E> throwingConsumer, Class<E> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
package com.baeldung.java8.lambda.exceptions;
|
||||||
|
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface ThrowingConsumer<T, E extends Exception> {
|
||||||
|
|
||||||
|
void accept(T t) throws E;
|
||||||
|
|
||||||
|
}
|
|
@ -42,136 +42,96 @@ public class Java8CollectorsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||||
final List<String> result = givenList
|
final List<String> result = givenList.stream().collect(toList());
|
||||||
.stream()
|
|
||||||
.collect(toList());
|
|
||||||
|
|
||||||
assertThat(result).containsAll(givenList);
|
assertThat(result).containsAll(givenList);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||||
final Set<String> result = givenList
|
final Set<String> result = givenList.stream().collect(toSet());
|
||||||
.stream()
|
|
||||||
.collect(toSet());
|
|
||||||
|
|
||||||
assertThat(result).containsAll(givenList);
|
assertThat(result).containsAll(givenList);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||||
final List<String> result = givenList
|
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||||
.stream()
|
|
||||||
.collect(toCollection(LinkedList::new));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(LinkedList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||||
assertThatThrownBy(() -> {
|
assertThatThrownBy(() -> {
|
||||||
givenList
|
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||||
.stream()
|
|
||||||
.collect(toCollection(ImmutableList::of));
|
|
||||||
}).isInstanceOf(UnsupportedOperationException.class);
|
}).isInstanceOf(UnsupportedOperationException.class);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||||
final Map<String, Integer> result = givenList
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||||
.stream()
|
|
||||||
.collect(toMap(Function.identity(), String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||||
final Map<String, Integer> result = givenList
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||||
.stream()
|
|
||||||
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||||
final List<String> result = givenList
|
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||||
.stream()
|
|
||||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(ImmutableList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoining_shouldJoin() throws Exception {
|
public void whenJoining_shouldJoin() throws Exception {
|
||||||
final String result = givenList
|
final String result = givenList.stream().collect(joining());
|
||||||
.stream()
|
|
||||||
.collect(joining());
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo("abbcccdd");
|
assertThat(result).isEqualTo("abbcccdd");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||||
final String result = givenList
|
final String result = givenList.stream().collect(joining(" "));
|
||||||
.stream()
|
|
||||||
.collect(joining(" "));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo("a bb ccc dd");
|
assertThat(result).isEqualTo("a bb ccc dd");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||||
final String result = givenList
|
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||||
.stream()
|
|
||||||
.collect(joining(" ", "PRE-", "-POST"));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||||
final Map<Boolean, List<String>> result = givenList
|
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||||
.stream()
|
|
||||||
.collect(partitioningBy(s -> s.length() > 2));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||||
.containsKeys(true, false)
|
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||||
.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
|
@Test
|
||||||
public void whenCounting_shouldCount() throws Exception {
|
public void whenCounting_shouldCount() throws Exception {
|
||||||
final Long result = givenList
|
final Long result = givenList.stream().collect(counting());
|
||||||
.stream()
|
|
||||||
.collect(counting());
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo(4);
|
assertThat(result).isEqualTo(4);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||||
final DoubleSummaryStatistics result = givenList
|
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||||
.stream()
|
|
||||||
.collect(summarizingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result.getAverage()).isEqualTo(2);
|
assertThat(result.getAverage()).isEqualTo(2);
|
||||||
assertThat(result.getCount()).isEqualTo(4);
|
assertThat(result.getCount()).isEqualTo(4);
|
||||||
|
@ -182,55 +142,37 @@ public class Java8CollectorsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAveraging_shouldAverage() throws Exception {
|
public void whenAveraging_shouldAverage() throws Exception {
|
||||||
final Double result = givenList
|
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||||
.stream()
|
|
||||||
.collect(averagingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo(2);
|
assertThat(result).isEqualTo(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSumming_shouldSum() throws Exception {
|
public void whenSumming_shouldSum() throws Exception {
|
||||||
final Double result = givenList
|
final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
|
||||||
.stream()
|
|
||||||
.filter(i -> true)
|
|
||||||
.collect(summingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo(8);
|
assertThat(result).isEqualTo(8);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||||
final Optional<String> result = givenList
|
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||||
.stream()
|
|
||||||
.collect(maxBy(Comparator.naturalOrder()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isPresent().hasValue("dd");
|
||||||
.isPresent()
|
|
||||||
.hasValue("dd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||||
final Map<Integer, Set<String>> result = givenList
|
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||||
.stream()
|
|
||||||
.collect(groupingBy(String::length, toSet()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||||
.containsEntry(1, newHashSet("a"))
|
|
||||||
.containsEntry(2, newHashSet("bb", "dd"))
|
|
||||||
.containsEntry(3, newHashSet("ccc"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||||
final ImmutableSet<String> result = givenList
|
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||||
.stream()
|
|
||||||
.collect(toImmutableSet());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
|
||||||
.isInstanceOf(ImmutableSet.class)
|
|
||||||
.contains("a", "bb", "ccc", "dd");
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -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<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
CountDownLatch countDownLatch = new CountDownLatch(5);
|
||||||
|
List<Thread> 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<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
CountDownLatch countDownLatch = new CountDownLatch(5);
|
||||||
|
List<Thread> 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<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
CountDownLatch readyThreadCounter = new CountDownLatch(5);
|
||||||
|
CountDownLatch callingThreadBlocker = new CountDownLatch(1);
|
||||||
|
CountDownLatch completedThreadCounter = new CountDownLatch(5);
|
||||||
|
List<Thread> 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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<Integer> result1 = squareCalculator.calculate(4);
|
||||||
|
Future<Integer> 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<Integer> 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<Integer> result1 = squareCalculator.calculate(4);
|
||||||
|
Future<Integer> 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<Integer> 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));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<String, String> 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<String, String> capitalCountryMap = new HashMap<>();
|
||||||
|
capitalCountryMap.put("New Delhi", "India");
|
||||||
|
capitalCountryMap.put("Washingon, D.C.", "USA");
|
||||||
|
capitalCountryMap.put("Moscow", "Russia");
|
||||||
|
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create(capitalCountryMap);
|
||||||
|
|
||||||
|
final String countryCapitalName = capitalCountryBiMap.inverse().get("India");
|
||||||
|
|
||||||
|
assertEquals("New Delhi", countryCapitalName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenQueryByKey_returnsValue() {
|
||||||
|
final BiMap<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().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<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().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<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().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<Operation, String> 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));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<String, Integer> concurrentMap;
|
||||||
|
private List<Integer> 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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<String, Object> 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<String, Object> nullKeyMap = new HashMap<>();
|
||||||
|
nullKeyMap.put(null, new Object());
|
||||||
|
concurrentMap.putAll(nullKeyMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMapAndMapWithNullValue_whenPutNullValueMap_thenThrowsNPE() {
|
||||||
|
Map<String, Object> 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"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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<String, Object> hashtable = new Hashtable<>();
|
||||||
|
Map<String, Object> synchronizedHashMap = Collections.synchronizedMap(new HashMap<>());
|
||||||
|
Map<String, Object> 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<String, Object> 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<SameHash, Integer> 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<Object, Integer> mapOfDefaultHash = new ConcurrentHashMap<>();
|
||||||
|
executorService = Executors.newFixedThreadPool(2);
|
||||||
|
long defaultHashStartTime = System.currentTimeMillis();
|
||||||
|
for (int i = 0; i < 2; i++) {
|
||||||
|
executorService.execute(() -> {
|
||||||
|
for (int j = 0; j < executeTimes; j++) {
|
||||||
|
mapOfDefaultHash.put(new Object(), 1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
executorService.shutdown();
|
||||||
|
executorService.awaitTermination(5, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
long mapOfDefaultHashDuration = System.currentTimeMillis() - defaultHashStartTime;
|
||||||
|
assertEquals(executeTimes * 2, mapOfDefaultHash.size());
|
||||||
|
assertEquals(executeTimes * 2, mapOfSameHash.size());
|
||||||
|
System.out.println(String.format("same-hash: %s, default-hash: %s", mapOfSameHashDuration, mapOfDefaultHashDuration));
|
||||||
|
assertTrue("same hashCode() should greatly degrade performance", mapOfSameHashDuration > mapOfDefaultHashDuration * 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,60 @@
|
||||||
|
package com.baeldung.java.concurrentmap;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class ConcurretMapMemoryConsistencyTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
||||||
|
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||||
|
List<Integer> sumList = parallelSum100(map, 1000);
|
||||||
|
assertEquals(1, sumList.stream().distinct().count());
|
||||||
|
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||||
|
assertEquals(0, wrongResultCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
|
||||||
|
Map<String, Integer> map = new Hashtable<>();
|
||||||
|
List<Integer> sumList = parallelSum100(map, 1000);
|
||||||
|
assertEquals(1, sumList.stream().distinct().count());
|
||||||
|
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||||
|
assertEquals(0, wrongResultCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHashMap_whenSumParallel_thenError() throws Exception {
|
||||||
|
Map<String, Integer> map = new HashMap<>();
|
||||||
|
List<Integer> sumList = parallelSum100(map, 100);
|
||||||
|
assertNotEquals(1, sumList.stream().distinct().count());
|
||||||
|
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||||
|
assertTrue(wrongResultCount > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Integer> parallelSum100(Map<String, Integer> map, int executionTimes) throws InterruptedException {
|
||||||
|
List<Integer> sumList = new ArrayList<>(1000);
|
||||||
|
for (int i = 0; i < executionTimes; i++) {
|
||||||
|
map.put("test", 0);
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(4);
|
||||||
|
for (int j = 0; j < 10; j++) {
|
||||||
|
executorService.execute(() -> {
|
||||||
|
for (int k = 0; k < 10; k++)
|
||||||
|
map.computeIfPresent("test", (key, value) -> value + 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
executorService.shutdown();
|
||||||
|
executorService.awaitTermination(5, TimeUnit.SECONDS);
|
||||||
|
sumList.add(map.get("test"));
|
||||||
|
}
|
||||||
|
return sumList;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.java.conversion;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.StreamSupport;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
|
||||||
|
|
||||||
|
public class IterableStreamConversionTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIterable_whenConvertedToStream_thenNotNull() {
|
||||||
|
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||||
|
|
||||||
|
Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToList_thenCorrect() {
|
||||||
|
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||||
|
|
||||||
|
List<String> result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -201,8 +201,6 @@ public class MapTest {
|
||||||
assertEquals("val1", rtnVal);
|
assertEquals("val1", rtnVal);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCallsEqualsOnCollision_thenCorrect() {
|
public void whenCallsEqualsOnCollision_thenCorrect() {
|
||||||
HashMap<MyKey, String> map = new HashMap<>();
|
HashMap<MyKey, String> map = new HashMap<>();
|
||||||
|
@ -311,13 +309,7 @@ public class MapTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
|
public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
|
||||||
TreeMap<Integer, String> map = new TreeMap<>(new Comparator<Integer>() {
|
TreeMap<Integer, String> map = new TreeMap<>(Comparator.reverseOrder());
|
||||||
|
|
||||||
@Override
|
|
||||||
public int compare(Integer o1, Integer o2) {
|
|
||||||
return o2 - o1;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
map.put(3, "val");
|
map.put(3, "val");
|
||||||
map.put(2, "val");
|
map.put(2, "val");
|
||||||
map.put(1, "val");
|
map.put(1, "val");
|
||||||
|
@ -335,7 +327,7 @@ public class MapTest {
|
||||||
map.put(1, "val");
|
map.put(1, "val");
|
||||||
map.put(5, "val");
|
map.put(5, "val");
|
||||||
map.put(4, "val");
|
map.put(4, "val");
|
||||||
|
|
||||||
Integer highestKey = map.lastKey();
|
Integer highestKey = map.lastKey();
|
||||||
Integer lowestKey = map.firstKey();
|
Integer lowestKey = map.firstKey();
|
||||||
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
|
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
|
||||||
|
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.java8;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.anyOf;
|
||||||
|
import static org.hamcrest.Matchers.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class Java8FindAnyFindFirstTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void createStream_whenFindAnyResultIsPresent_thenCorrect() {
|
||||||
|
|
||||||
|
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||||
|
|
||||||
|
Optional<String> result = list.stream().findAny();
|
||||||
|
|
||||||
|
assertTrue(result.isPresent());
|
||||||
|
assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
||||||
|
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
||||||
|
Optional<Integer> result = list.stream().parallel().filter(num -> num < 4).findAny();
|
||||||
|
|
||||||
|
assertTrue(result.isPresent());
|
||||||
|
assertThat(result.get(), anyOf(is(1), is(2), is(3)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void createStream_whenFindFirstResultIsPresent_thenCorrect() {
|
||||||
|
|
||||||
|
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||||
|
|
||||||
|
Optional<String> result = list.stream().findFirst();
|
||||||
|
|
||||||
|
assertTrue(result.isPresent());
|
||||||
|
assertThat(result.get(), is("A"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.java8.lambda.exceptions;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*;
|
||||||
|
|
||||||
|
public class LambdaExceptionWrappersTest {
|
||||||
|
|
||||||
|
private List<Integer> integers;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
integers = Arrays.asList(3, 9, 7, 0, 10, 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoExceptionFromLambdaWrapper_thenSuccess() {
|
||||||
|
integers.forEach(lambdaWrapper(i -> System.out.println(50 / i)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoExceptionFromConsumerWrapper_thenSuccess() {
|
||||||
|
integers.forEach(consumerWrapper(i -> System.out.println(50 / i), ArithmeticException.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = RuntimeException.class)
|
||||||
|
public void whenExceptionFromThrowingConsumerWrapper_thenSuccess() {
|
||||||
|
integers.forEach(throwingConsumerWrapper(i -> writeToFile(i)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoExceptionFromHandlingConsumerWrapper_thenSuccess() {
|
||||||
|
integers.forEach(handlingConsumerWrapper(i -> writeToFile(i), IOException.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writeToFile(Integer i) throws IOException {
|
||||||
|
if (i == 0) {
|
||||||
|
throw new IOException(); // mock IOException
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -56,9 +56,7 @@ public class NashornTest {
|
||||||
Map<String, Object> map = (Map<String, Object>) obj;
|
Map<String, Object> map = (Map<String, Object>) obj;
|
||||||
|
|
||||||
Assert.assertEquals("hello", map.get("greet"));
|
Assert.assertEquals("hello", map.get("greet"));
|
||||||
Assert.assertTrue(List.class.isAssignableFrom(map
|
Assert.assertTrue(List.class.isAssignableFrom(map.get("primes").getClass()));
|
||||||
.get("primes")
|
|
||||||
.getClass()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -1,2 +1,3 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
||||||
|
- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
|
||||||
|
|
|
@ -1,38 +1,26 @@
|
||||||
package org.baeldung.java.io;
|
package org.baeldung.java.io;
|
||||||
|
|
||||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileInputStream;
|
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.io.InputStreamReader;
|
|
||||||
import java.io.OutputStream;
|
|
||||||
import java.io.Reader;
|
|
||||||
import java.io.StringWriter;
|
|
||||||
import java.nio.charset.Charset;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
import java.util.Scanner;
|
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
|
||||||
import org.apache.commons.io.IOUtils;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import com.google.common.base.Charsets;
|
import com.google.common.base.Charsets;
|
||||||
import com.google.common.io.ByteSource;
|
import com.google.common.io.ByteSource;
|
||||||
import com.google.common.io.ByteStreams;
|
import com.google.common.io.ByteStreams;
|
||||||
import com.google.common.io.CharStreams;
|
import com.google.common.io.CharStreams;
|
||||||
import com.google.common.io.Files;
|
import com.google.common.io.Files;
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.apache.commons.io.IOUtils;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
public class JavaInputStreamToXUnitTest {
|
public class JavaInputStreamToXUnitTest {
|
||||||
|
@ -163,7 +151,7 @@ public class JavaInputStreamToXUnitTest {
|
||||||
// tests - InputStream to File
|
// tests - InputStream to File
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingPlainJava_whenConvertingAnFullInputStreamToAFile_thenCorrect() throws IOException {
|
public final void whenConvertingToFile_thenCorrect() throws IOException {
|
||||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||||
final byte[] buffer = new byte[initialStream.available()];
|
final byte[] buffer = new byte[initialStream.available()];
|
||||||
initialStream.read(buffer);
|
initialStream.read(buffer);
|
||||||
|
@ -177,7 +165,7 @@ public class JavaInputStreamToXUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingPlainJava_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException {
|
public final void whenConvertingInProgressToFile_thenCorrect() throws IOException {
|
||||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||||
final OutputStream outStream = new FileOutputStream(targetFile);
|
final OutputStream outStream = new FileOutputStream(targetFile);
|
||||||
|
@ -193,7 +181,7 @@ public class JavaInputStreamToXUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingPlainJava8_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException {
|
public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException {
|
||||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||||
|
|
||||||
|
@ -203,7 +191,7 @@ public class JavaInputStreamToXUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingGuava_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException {
|
public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException {
|
||||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||||
final byte[] buffer = new byte[initialStream.available()];
|
final byte[] buffer = new byte[initialStream.available()];
|
||||||
initialStream.read(buffer);
|
initialStream.read(buffer);
|
||||||
|
@ -215,7 +203,7 @@ public class JavaInputStreamToXUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException {
|
public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException {
|
||||||
final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
|
||||||
|
|
||||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||||
|
|
|
@ -3,7 +3,7 @@ package com.baeldung.couchbase.async;
|
||||||
public interface CouchbaseEntity {
|
public interface CouchbaseEntity {
|
||||||
|
|
||||||
String getId();
|
String getId();
|
||||||
|
|
||||||
void setId(String id);
|
void setId(String id);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,26 +8,27 @@ public class Person implements CouchbaseEntity {
|
||||||
private String type;
|
private String type;
|
||||||
private String name;
|
private String name;
|
||||||
private String homeTown;
|
private String homeTown;
|
||||||
|
|
||||||
Person() {}
|
Person() {
|
||||||
|
}
|
||||||
|
|
||||||
public Person(Builder b) {
|
public Person(Builder b) {
|
||||||
this.id = b.id;
|
this.id = b.id;
|
||||||
this.type = b.type;
|
this.type = b.type;
|
||||||
this.name = b.name;
|
this.name = b.name;
|
||||||
this.homeTown = b.homeTown;
|
this.homeTown = b.homeTown;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setId(String id) {
|
public void setId(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getType() {
|
public String getType() {
|
||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
|
@ -39,19 +40,19 @@ public class Person implements CouchbaseEntity {
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getHomeTown() {
|
public String getHomeTown() {
|
||||||
return homeTown;
|
return homeTown;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setHomeTown(String homeTown) {
|
public void setHomeTown(String homeTown) {
|
||||||
this.homeTown = homeTown;
|
this.homeTown = homeTown;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Builder {
|
public static class Builder {
|
||||||
private String id;
|
private String id;
|
||||||
private String type;
|
private String type;
|
||||||
|
@ -61,16 +62,16 @@ public class Person implements CouchbaseEntity {
|
||||||
public static Builder newInstance() {
|
public static Builder newInstance() {
|
||||||
return new Builder();
|
return new Builder();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Person build() {
|
public Person build() {
|
||||||
return new Person(this);
|
return new Person(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Builder id(String id) {
|
public Builder id(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Builder type(String type) {
|
public Builder type(String type) {
|
||||||
this.type = type;
|
this.type = type;
|
||||||
return this;
|
return this;
|
||||||
|
|
|
@ -13,9 +13,7 @@ import com.baeldung.couchbase.async.service.BucketService;
|
||||||
public class PersonCrudService extends AbstractCrudService<Person> {
|
public class PersonCrudService extends AbstractCrudService<Person> {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public PersonCrudService(
|
public PersonCrudService(@Qualifier("TutorialBucketService") BucketService bucketService, PersonDocumentConverter converter) {
|
||||||
@Qualifier("TutorialBucketService") BucketService bucketService,
|
|
||||||
PersonDocumentConverter converter) {
|
|
||||||
super(bucketService, converter);
|
super(bucketService, converter);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter<Person> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public JsonDocument toDocument(Person p) {
|
public JsonDocument toDocument(Person p) {
|
||||||
JsonObject content = JsonObject.empty()
|
JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown());
|
||||||
.put("type", "Person")
|
|
||||||
.put("name", p.getName())
|
|
||||||
.put("homeTown", p.getHomeTown());
|
|
||||||
return JsonDocument.create(p.getId(), content);
|
return JsonDocument.create(p.getId(), content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -10,19 +10,18 @@ public class RegistrationService {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private PersonCrudService crud;
|
private PersonCrudService crud;
|
||||||
|
|
||||||
public void registerNewPerson(String name, String homeTown) {
|
public void registerNewPerson(String name, String homeTown) {
|
||||||
Person person = new Person();
|
Person person = new Person();
|
||||||
person.setName(name);
|
person.setName(name);
|
||||||
person.setHomeTown(homeTown);
|
person.setHomeTown(homeTown);
|
||||||
crud.create(person);
|
crud.create(person);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Person findRegistrant(String id) {
|
public Person findRegistrant(String id) {
|
||||||
try{
|
try {
|
||||||
return crud.read(id);
|
return crud.read(id);
|
||||||
}
|
} catch (CouchbaseException e) {
|
||||||
catch(CouchbaseException e) {
|
|
||||||
return crud.readFromReplica(id);
|
return crud.readFromReplica(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,9 +11,9 @@ public abstract class AbstractBucketService implements BucketService {
|
||||||
protected void openBucket() {
|
protected void openBucket() {
|
||||||
bucket = clusterService.openBucket(getBucketName(), getBucketPassword());
|
bucket = clusterService.openBucket(getBucketName(), getBucketPassword());
|
||||||
}
|
}
|
||||||
|
|
||||||
protected abstract String getBucketName();
|
protected abstract String getBucketName();
|
||||||
|
|
||||||
protected abstract String getBucketPassword();
|
protected abstract String getBucketPassword();
|
||||||
|
|
||||||
public AbstractBucketService(ClusterService clusterService) {
|
public AbstractBucketService(ClusterService clusterService) {
|
||||||
|
@ -24,4 +24,4 @@ public abstract class AbstractBucketService implements BucketService {
|
||||||
public Bucket getBucket() {
|
public Bucket getBucket() {
|
||||||
return bucket;
|
return bucket;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -40,7 +40,7 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void create(T t) {
|
public void create(T t) {
|
||||||
if(t.getId() == null) {
|
if (t.getId() == null) {
|
||||||
t.setId(UUID.randomUUID().toString());
|
t.setId(UUID.randomUUID().toString());
|
||||||
}
|
}
|
||||||
JsonDocument doc = converter.toDocument(t);
|
JsonDocument doc = converter.toDocument(t);
|
||||||
|
@ -73,18 +73,15 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
|
||||||
@Override
|
@Override
|
||||||
public List<T> readBulk(Iterable<String> ids) {
|
public List<T> readBulk(Iterable<String> ids) {
|
||||||
final AsyncBucket asyncBucket = bucket.async();
|
final AsyncBucket asyncBucket = bucket.async();
|
||||||
Observable<JsonDocument> asyncOperation = Observable
|
Observable<JsonDocument> asyncOperation = Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||||
.from(ids)
|
public Observable<JsonDocument> call(String key) {
|
||||||
.flatMap(new Func1<String, Observable<JsonDocument>>() {
|
return asyncBucket.get(key);
|
||||||
public Observable<JsonDocument> call(String key) {
|
}
|
||||||
return asyncBucket.get(key);
|
});
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
final List<T> items = new ArrayList<T>();
|
final List<T> items = new ArrayList<T>();
|
||||||
try {
|
try {
|
||||||
asyncOperation.toBlocking()
|
asyncOperation.toBlocking().forEach(new Action1<JsonDocument>() {
|
||||||
.forEach(new Action1<JsonDocument>() {
|
|
||||||
public void call(JsonDocument doc) {
|
public void call(JsonDocument doc) {
|
||||||
T item = converter.fromDocument(doc);
|
T item = converter.fromDocument(doc);
|
||||||
items.add(item);
|
items.add(item);
|
||||||
|
@ -100,72 +97,42 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
|
||||||
@Override
|
@Override
|
||||||
public void createBulk(Iterable<T> items) {
|
public void createBulk(Iterable<T> items) {
|
||||||
final AsyncBucket asyncBucket = bucket.async();
|
final AsyncBucket asyncBucket = bucket.async();
|
||||||
Observable
|
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
|
||||||
.from(items)
|
|
||||||
.flatMap(new Func1<T, Observable<JsonDocument>>() {
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Override
|
@Override
|
||||||
public Observable<JsonDocument> call(final T t) {
|
public Observable<JsonDocument> call(final T t) {
|
||||||
if(t.getId() == null) {
|
if (t.getId() == null) {
|
||||||
t.setId(UUID.randomUUID().toString());
|
t.setId(UUID.randomUUID().toString());
|
||||||
}
|
}
|
||||||
JsonDocument doc = converter.toDocument(t);
|
JsonDocument doc = converter.toDocument(t);
|
||||||
return asyncBucket.insert(doc)
|
return asyncBucket.insert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
|
||||||
.retryWhen(RetryBuilder
|
|
||||||
.anyOf(BackpressureException.class)
|
|
||||||
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
|
|
||||||
.max(10)
|
|
||||||
.build());
|
|
||||||
}
|
}
|
||||||
})
|
}).last().toBlocking().single();
|
||||||
.last()
|
|
||||||
.toBlocking()
|
|
||||||
.single();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void updateBulk(Iterable<T> items) {
|
public void updateBulk(Iterable<T> items) {
|
||||||
final AsyncBucket asyncBucket = bucket.async();
|
final AsyncBucket asyncBucket = bucket.async();
|
||||||
Observable
|
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
|
||||||
.from(items)
|
|
||||||
.flatMap(new Func1<T, Observable<JsonDocument>>() {
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Override
|
@Override
|
||||||
public Observable<JsonDocument> call(final T t) {
|
public Observable<JsonDocument> call(final T t) {
|
||||||
JsonDocument doc = converter.toDocument(t);
|
JsonDocument doc = converter.toDocument(t);
|
||||||
return asyncBucket.upsert(doc)
|
return asyncBucket.upsert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
|
||||||
.retryWhen(RetryBuilder
|
|
||||||
.anyOf(BackpressureException.class)
|
|
||||||
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
|
|
||||||
.max(10)
|
|
||||||
.build());
|
|
||||||
}
|
}
|
||||||
})
|
}).last().toBlocking().single();
|
||||||
.last()
|
|
||||||
.toBlocking()
|
|
||||||
.single();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void deleteBulk(Iterable<String> ids) {
|
public void deleteBulk(Iterable<String> ids) {
|
||||||
final AsyncBucket asyncBucket = bucket.async();
|
final AsyncBucket asyncBucket = bucket.async();
|
||||||
Observable
|
Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||||
.from(ids)
|
|
||||||
.flatMap(new Func1<String, Observable<JsonDocument>>() {
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Override
|
@Override
|
||||||
public Observable<JsonDocument> call(String key) {
|
public Observable<JsonDocument> call(String key) {
|
||||||
return asyncBucket.remove(key)
|
return asyncBucket.remove(key).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
|
||||||
.retryWhen(RetryBuilder
|
|
||||||
.anyOf(BackpressureException.class)
|
|
||||||
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
|
|
||||||
.max(10)
|
|
||||||
.build());
|
|
||||||
}
|
}
|
||||||
})
|
}).last().toBlocking().single();
|
||||||
.last()
|
|
||||||
.toBlocking()
|
|
||||||
.single();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -3,6 +3,6 @@ package com.baeldung.couchbase.async.service;
|
||||||
import com.couchbase.client.java.Bucket;
|
import com.couchbase.client.java.Bucket;
|
||||||
|
|
||||||
public interface ClusterService {
|
public interface ClusterService {
|
||||||
|
|
||||||
Bucket openBucket(String name, String password);
|
Bucket openBucket(String name, String password);
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,7 +18,7 @@ public class ClusterServiceImpl implements ClusterService {
|
||||||
|
|
||||||
private Cluster cluster;
|
private Cluster cluster;
|
||||||
private Map<String, Bucket> buckets = new ConcurrentHashMap<>();
|
private Map<String, Bucket> buckets = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
private void init() {
|
private void init() {
|
||||||
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();
|
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();
|
||||||
|
@ -27,7 +27,7 @@ public class ClusterServiceImpl implements ClusterService {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
synchronized public Bucket openBucket(String name, String password) {
|
synchronized public Bucket openBucket(String name, String password) {
|
||||||
if(!buckets.containsKey(name)) {
|
if (!buckets.containsKey(name)) {
|
||||||
Bucket bucket = cluster.openBucket(name, password);
|
Bucket bucket = cluster.openBucket(name, password);
|
||||||
buckets.put(name, bucket);
|
buckets.put(name, bucket);
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,6 +5,6 @@ import com.couchbase.client.java.document.JsonDocument;
|
||||||
public interface JsonDocumentConverter<T> {
|
public interface JsonDocumentConverter<T> {
|
||||||
|
|
||||||
JsonDocument toDocument(T t);
|
JsonDocument toDocument(T t);
|
||||||
|
|
||||||
T fromDocument(JsonDocument doc);
|
T fromDocument(JsonDocument doc);
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,40 +14,32 @@ import com.couchbase.client.java.env.CouchbaseEnvironment;
|
||||||
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
|
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
|
||||||
|
|
||||||
public class CodeSnippets {
|
public class CodeSnippets {
|
||||||
|
|
||||||
static Cluster loadClusterWithDefaultEnvironment() {
|
static Cluster loadClusterWithDefaultEnvironment() {
|
||||||
return CouchbaseCluster.create("localhost");
|
return CouchbaseCluster.create("localhost");
|
||||||
}
|
}
|
||||||
|
|
||||||
static Cluster loadClusterWithCustomEnvironment() {
|
static Cluster loadClusterWithCustomEnvironment() {
|
||||||
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
|
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(10000).kvTimeout(3000).build();
|
||||||
.connectTimeout(10000)
|
|
||||||
.kvTimeout(3000)
|
|
||||||
.build();
|
|
||||||
return CouchbaseCluster.create(env, "localhost");
|
return CouchbaseCluster.create(env, "localhost");
|
||||||
}
|
}
|
||||||
|
|
||||||
static Bucket loadDefaultBucketWithBlankPassword(Cluster cluster) {
|
static Bucket loadDefaultBucketWithBlankPassword(Cluster cluster) {
|
||||||
return cluster.openBucket();
|
return cluster.openBucket();
|
||||||
}
|
}
|
||||||
|
|
||||||
static Bucket loadBaeldungBucket(Cluster cluster) {
|
static Bucket loadBaeldungBucket(Cluster cluster) {
|
||||||
return cluster.openBucket("baeldung", "");
|
return cluster.openBucket("baeldung", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
static JsonDocument insertExample(Bucket bucket) {
|
static JsonDocument insertExample(Bucket bucket) {
|
||||||
JsonObject content = JsonObject.empty()
|
JsonObject content = JsonObject.empty().put("name", "John Doe").put("type", "Person").put("email", "john.doe@mydomain.com").put("homeTown", "Chicago");
|
||||||
.put("name", "John Doe")
|
|
||||||
.put("type", "Person")
|
|
||||||
.put("email", "john.doe@mydomain.com")
|
|
||||||
.put("homeTown", "Chicago")
|
|
||||||
;
|
|
||||||
String id = UUID.randomUUID().toString();
|
String id = UUID.randomUUID().toString();
|
||||||
JsonDocument document = JsonDocument.create(id, content);
|
JsonDocument document = JsonDocument.create(id, content);
|
||||||
JsonDocument inserted = bucket.insert(document);
|
JsonDocument inserted = bucket.insert(document);
|
||||||
return inserted;
|
return inserted;
|
||||||
}
|
}
|
||||||
|
|
||||||
static JsonDocument retrieveAndUpsertExample(Bucket bucket, String id) {
|
static JsonDocument retrieveAndUpsertExample(Bucket bucket, String id) {
|
||||||
JsonDocument document = bucket.get(id);
|
JsonDocument document = bucket.get(id);
|
||||||
JsonObject content = document.content();
|
JsonObject content = document.content();
|
||||||
|
@ -55,7 +47,7 @@ public class CodeSnippets {
|
||||||
JsonDocument upserted = bucket.upsert(document);
|
JsonDocument upserted = bucket.upsert(document);
|
||||||
return upserted;
|
return upserted;
|
||||||
}
|
}
|
||||||
|
|
||||||
static JsonDocument replaceExample(Bucket bucket, String id) {
|
static JsonDocument replaceExample(Bucket bucket, String id) {
|
||||||
JsonDocument document = bucket.get(id);
|
JsonDocument document = bucket.get(id);
|
||||||
JsonObject content = document.content();
|
JsonObject content = document.content();
|
||||||
|
@ -63,30 +55,29 @@ public class CodeSnippets {
|
||||||
JsonDocument replaced = bucket.replace(document);
|
JsonDocument replaced = bucket.replace(document);
|
||||||
return replaced;
|
return replaced;
|
||||||
}
|
}
|
||||||
|
|
||||||
static JsonDocument removeExample(Bucket bucket, String id) {
|
static JsonDocument removeExample(Bucket bucket, String id) {
|
||||||
JsonDocument removed = bucket.remove(id);
|
JsonDocument removed = bucket.remove(id);
|
||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) {
|
static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) {
|
||||||
try{
|
try {
|
||||||
return bucket.get(id);
|
return bucket.get(id);
|
||||||
}
|
} catch (CouchbaseException e) {
|
||||||
catch(CouchbaseException e) {
|
|
||||||
List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST);
|
List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST);
|
||||||
if(!list.isEmpty()) {
|
if (!list.isEmpty()) {
|
||||||
return list.get(0);
|
return list.get(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
static JsonDocument getLatestReplicaVersion(Bucket bucket, String id) {
|
static JsonDocument getLatestReplicaVersion(Bucket bucket, String id) {
|
||||||
long maxCasValue = -1;
|
long maxCasValue = -1;
|
||||||
JsonDocument latest = null;
|
JsonDocument latest = null;
|
||||||
for(JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) {
|
for (JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) {
|
||||||
if(replica.cas() > maxCasValue) {
|
if (replica.cas() > maxCasValue) {
|
||||||
latest = replica;
|
latest = replica;
|
||||||
maxCasValue = replica.cas();
|
maxCasValue = replica.cas();
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,24 +6,25 @@ public class Person {
|
||||||
private String type;
|
private String type;
|
||||||
private String name;
|
private String name;
|
||||||
private String homeTown;
|
private String homeTown;
|
||||||
|
|
||||||
Person() {}
|
Person() {
|
||||||
|
}
|
||||||
|
|
||||||
public Person(Builder b) {
|
public Person(Builder b) {
|
||||||
this.id = b.id;
|
this.id = b.id;
|
||||||
this.type = b.type;
|
this.type = b.type;
|
||||||
this.name = b.name;
|
this.name = b.name;
|
||||||
this.homeTown = b.homeTown;
|
this.homeTown = b.homeTown;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(String id) {
|
public void setId(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getType() {
|
public String getType() {
|
||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
|
@ -35,19 +36,19 @@ public class Person {
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getHomeTown() {
|
public String getHomeTown() {
|
||||||
return homeTown;
|
return homeTown;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setHomeTown(String homeTown) {
|
public void setHomeTown(String homeTown) {
|
||||||
this.homeTown = homeTown;
|
this.homeTown = homeTown;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Builder {
|
public static class Builder {
|
||||||
private String id;
|
private String id;
|
||||||
private String type;
|
private String type;
|
||||||
|
@ -57,16 +58,16 @@ public class Person {
|
||||||
public static Builder newInstance() {
|
public static Builder newInstance() {
|
||||||
return new Builder();
|
return new Builder();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Person build() {
|
public Person build() {
|
||||||
return new Person(this);
|
return new Person(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Builder id(String id) {
|
public Builder id(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Builder type(String type) {
|
public Builder type(String type) {
|
||||||
this.type = type;
|
this.type = type;
|
||||||
return this;
|
return this;
|
||||||
|
|
|
@ -16,15 +16,15 @@ import com.couchbase.client.java.document.JsonDocument;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class PersonCrudService implements CrudService<Person> {
|
public class PersonCrudService implements CrudService<Person> {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private TutorialBucketService bucketService;
|
private TutorialBucketService bucketService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private PersonDocumentConverter converter;
|
private PersonDocumentConverter converter;
|
||||||
|
|
||||||
private Bucket bucket;
|
private Bucket bucket;
|
||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
private void init() {
|
private void init() {
|
||||||
bucket = bucketService.getBucket();
|
bucket = bucketService.getBucket();
|
||||||
|
@ -32,7 +32,7 @@ public class PersonCrudService implements CrudService<Person> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void create(Person person) {
|
public void create(Person person) {
|
||||||
if(person.getId() == null) {
|
if (person.getId() == null) {
|
||||||
person.setId(UUID.randomUUID().toString());
|
person.setId(UUID.randomUUID().toString());
|
||||||
}
|
}
|
||||||
JsonDocument document = converter.toDocument(person);
|
JsonDocument document = converter.toDocument(person);
|
||||||
|
|
|
@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter<Person> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public JsonDocument toDocument(Person p) {
|
public JsonDocument toDocument(Person p) {
|
||||||
JsonObject content = JsonObject.empty()
|
JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown());
|
||||||
.put("type", "Person")
|
|
||||||
.put("name", p.getName())
|
|
||||||
.put("homeTown", p.getHomeTown());
|
|
||||||
return JsonDocument.create(p.getId(), content);
|
return JsonDocument.create(p.getId(), content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -10,19 +10,18 @@ public class RegistrationService {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private PersonCrudService crud;
|
private PersonCrudService crud;
|
||||||
|
|
||||||
public void registerNewPerson(String name, String homeTown) {
|
public void registerNewPerson(String name, String homeTown) {
|
||||||
Person person = new Person();
|
Person person = new Person();
|
||||||
person.setName(name);
|
person.setName(name);
|
||||||
person.setHomeTown(homeTown);
|
person.setHomeTown(homeTown);
|
||||||
crud.create(person);
|
crud.create(person);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Person findRegistrant(String id) {
|
public Person findRegistrant(String id) {
|
||||||
try{
|
try {
|
||||||
return crud.read(id);
|
return crud.read(id);
|
||||||
}
|
} catch (CouchbaseException e) {
|
||||||
catch(CouchbaseException e) {
|
|
||||||
return crud.readFromReplica(id);
|
return crud.readFromReplica(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,5 +5,5 @@ import com.couchbase.client.java.Bucket;
|
||||||
public interface BucketService {
|
public interface BucketService {
|
||||||
|
|
||||||
Bucket getBucket();
|
Bucket getBucket();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,11 +7,11 @@ import com.couchbase.client.java.Bucket;
|
||||||
import com.couchbase.client.java.document.JsonDocument;
|
import com.couchbase.client.java.document.JsonDocument;
|
||||||
|
|
||||||
public interface ClusterService {
|
public interface ClusterService {
|
||||||
|
|
||||||
Bucket openBucket(String name, String password);
|
Bucket openBucket(String name, String password);
|
||||||
|
|
||||||
List<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys);
|
List<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys);
|
||||||
|
|
||||||
List<JsonDocument> getDocumentsAsync(AsyncBucket bucket, Iterable<String> keys);
|
List<JsonDocument> getDocumentsAsync(AsyncBucket bucket, Iterable<String> keys);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,7 +29,7 @@ public class ClusterServiceImpl implements ClusterService {
|
||||||
|
|
||||||
private Cluster cluster;
|
private Cluster cluster;
|
||||||
private Map<String, Bucket> buckets = new ConcurrentHashMap<>();
|
private Map<String, Bucket> buckets = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
private void init() {
|
private void init() {
|
||||||
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();
|
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();
|
||||||
|
@ -38,7 +38,7 @@ public class ClusterServiceImpl implements ClusterService {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
synchronized public Bucket openBucket(String name, String password) {
|
synchronized public Bucket openBucket(String name, String password) {
|
||||||
if(!buckets.containsKey(name)) {
|
if (!buckets.containsKey(name)) {
|
||||||
Bucket bucket = cluster.openBucket(name, password);
|
Bucket bucket = cluster.openBucket(name, password);
|
||||||
buckets.put(name, bucket);
|
buckets.put(name, bucket);
|
||||||
}
|
}
|
||||||
|
@ -48,9 +48,9 @@ public class ClusterServiceImpl implements ClusterService {
|
||||||
@Override
|
@Override
|
||||||
public List<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys) {
|
public List<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys) {
|
||||||
List<JsonDocument> docs = new ArrayList<>();
|
List<JsonDocument> docs = new ArrayList<>();
|
||||||
for(String key : keys) {
|
for (String key : keys) {
|
||||||
JsonDocument doc = bucket.get(key);
|
JsonDocument doc = bucket.get(key);
|
||||||
if(doc != null) {
|
if (doc != null) {
|
||||||
docs.add(doc);
|
docs.add(doc);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -59,18 +59,15 @@ public class ClusterServiceImpl implements ClusterService {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) {
|
public List<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) {
|
||||||
Observable<JsonDocument> asyncBulkGet = Observable
|
Observable<JsonDocument> asyncBulkGet = Observable.from(keys).flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||||
.from(keys)
|
public Observable<JsonDocument> call(String key) {
|
||||||
.flatMap(new Func1<String, Observable<JsonDocument>>() {
|
return asyncBucket.get(key);
|
||||||
public Observable<JsonDocument> call(String key) {
|
}
|
||||||
return asyncBucket.get(key);
|
});
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
final List<JsonDocument> docs = new ArrayList<>();
|
final List<JsonDocument> docs = new ArrayList<>();
|
||||||
try {
|
try {
|
||||||
asyncBulkGet.toBlocking()
|
asyncBulkGet.toBlocking().forEach(new Action1<JsonDocument>() {
|
||||||
.forEach(new Action1<JsonDocument>() {
|
|
||||||
public void call(JsonDocument doc) {
|
public void call(JsonDocument doc) {
|
||||||
docs.add(doc);
|
docs.add(doc);
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,14 +3,14 @@ package com.baeldung.couchbase.spring.service;
|
||||||
public interface CrudService<T> {
|
public interface CrudService<T> {
|
||||||
|
|
||||||
void create(T t);
|
void create(T t);
|
||||||
|
|
||||||
T read(String id);
|
T read(String id);
|
||||||
|
|
||||||
T readFromReplica(String id);
|
T readFromReplica(String id);
|
||||||
|
|
||||||
void update(T t);
|
void update(T t);
|
||||||
|
|
||||||
void delete(String id);
|
void delete(String id);
|
||||||
|
|
||||||
boolean exists(String id);
|
boolean exists(String id);
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,6 +5,6 @@ import com.couchbase.client.java.document.JsonDocument;
|
||||||
public interface JsonDocumentConverter<T> {
|
public interface JsonDocumentConverter<T> {
|
||||||
|
|
||||||
JsonDocument toDocument(T t);
|
JsonDocument toDocument(T t);
|
||||||
|
|
||||||
T fromDocument(JsonDocument doc);
|
T fromDocument(JsonDocument doc);
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,15 +14,15 @@ public class TutorialBucketService implements BucketService {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ClusterService couchbase;
|
private ClusterService couchbase;
|
||||||
|
|
||||||
private Bucket bucket;
|
private Bucket bucket;
|
||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
private void init() {
|
private void init() {
|
||||||
bucket = couchbase.openBucket("baeldung-tutorial", "");
|
bucket = couchbase.openBucket("baeldung-tutorial", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Bucket getBucket() {
|
public Bucket getBucket() {
|
||||||
return bucket;
|
return bucket;
|
||||||
}
|
}
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue