Merge branch 'master' into sla-pr/1104
Conflicts: guava/pom.xml
This commit is contained in:
commit
b2ed0e5e09
|
@ -27,3 +27,5 @@ target/
|
|||
|
||||
spring-openid/src/main/resources/application.properties
|
||||
.recommenders/
|
||||
/spring-hibernate4/nbproject/
|
||||
spring-security-openid/src/main/resources/application.properties
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
<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>algorithms</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.algorithms.dijkstra;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
public class Dijkstra {
|
||||
|
||||
public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
|
||||
|
||||
source.setDistance(0);
|
||||
|
||||
Set<Node> settledNodes = new HashSet<>();
|
||||
Set<Node> unsettledNodes = new HashSet<>();
|
||||
unsettledNodes.add(source);
|
||||
|
||||
while (unsettledNodes.size() != 0) {
|
||||
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
||||
unsettledNodes.remove(currentNode);
|
||||
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
|
||||
Node adjacentNode = adjacencyPair.getKey();
|
||||
Integer edgeWeigh = adjacencyPair.getValue();
|
||||
|
||||
if (!settledNodes.contains(adjacentNode)) {
|
||||
CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode);
|
||||
unsettledNodes.add(adjacentNode);
|
||||
}
|
||||
}
|
||||
settledNodes.add(currentNode);
|
||||
}
|
||||
return graph;
|
||||
}
|
||||
|
||||
private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) {
|
||||
Integer sourceDistance = sourceNode.getDistance();
|
||||
if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) {
|
||||
evaluationNode.setDistance(sourceDistance + edgeWeigh);
|
||||
LinkedList<Node> shortestPath = new LinkedList<>(sourceNode.getShortestPath());
|
||||
shortestPath.add(sourceNode);
|
||||
evaluationNode.setShortestPath(shortestPath);
|
||||
}
|
||||
}
|
||||
|
||||
private static Node getLowestDistanceNode(Set<Node> unsettledNodes) {
|
||||
Node lowestDistanceNode = null;
|
||||
int lowestDistance = Integer.MAX_VALUE;
|
||||
for (Node node : unsettledNodes) {
|
||||
int nodeDistance = node.getDistance();
|
||||
if (nodeDistance < lowestDistance) {
|
||||
lowestDistance = nodeDistance;
|
||||
lowestDistanceNode = node;
|
||||
}
|
||||
}
|
||||
return lowestDistanceNode;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.algorithms.dijkstra;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class Graph {
|
||||
|
||||
private Set<Node> nodes = new HashSet<>();
|
||||
|
||||
public void addNode(Node nodeA) {
|
||||
nodes.add(nodeA);
|
||||
}
|
||||
|
||||
public Set<Node> getNodes() {
|
||||
return nodes;
|
||||
}
|
||||
|
||||
public void setNodes(Set<Node> nodes) {
|
||||
this.nodes = nodes;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.algorithms.dijkstra;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class Node {
|
||||
|
||||
private String name;
|
||||
|
||||
private LinkedList<Node> shortestPath = new LinkedList<>();
|
||||
|
||||
private Integer distance = Integer.MAX_VALUE;
|
||||
|
||||
private Map<Node, Integer> adjacentNodes = new HashMap<>();
|
||||
|
||||
public Node(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void addDestination(Node destination, int distance) {
|
||||
adjacentNodes.put(destination, distance);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Map<Node, Integer> getAdjacentNodes() {
|
||||
return adjacentNodes;
|
||||
}
|
||||
|
||||
public void setAdjacentNodes(Map<Node, Integer> adjacentNodes) {
|
||||
this.adjacentNodes = adjacentNodes;
|
||||
}
|
||||
|
||||
public Integer getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
public void setDistance(Integer distance) {
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
public List<Node> getShortestPath() {
|
||||
return shortestPath;
|
||||
}
|
||||
|
||||
public void setShortestPath(LinkedList<Node> shortestPath) {
|
||||
this.shortestPath = shortestPath;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
package algorithms;
|
||||
|
||||
import com.baeldung.algorithms.dijkstra.Dijkstra;
|
||||
import com.baeldung.algorithms.dijkstra.Graph;
|
||||
import com.baeldung.algorithms.dijkstra.Node;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class DijkstraAlgorithmTest {
|
||||
|
||||
@Test
|
||||
public void whenSPPSolved_thenCorrect() {
|
||||
|
||||
Node nodeA = new Node("A");
|
||||
Node nodeB = new Node("B");
|
||||
Node nodeC = new Node("C");
|
||||
Node nodeD = new Node("D");
|
||||
Node nodeE = new Node("E");
|
||||
Node nodeF = new Node("F");
|
||||
|
||||
nodeA.addDestination(nodeB, 10);
|
||||
nodeA.addDestination(nodeC, 15);
|
||||
|
||||
nodeB.addDestination(nodeD, 12);
|
||||
nodeB.addDestination(nodeF, 15);
|
||||
|
||||
nodeC.addDestination(nodeE, 10);
|
||||
|
||||
nodeD.addDestination(nodeE, 2);
|
||||
nodeD.addDestination(nodeF, 1);
|
||||
|
||||
nodeF.addDestination(nodeE, 5);
|
||||
|
||||
Graph graph = new Graph();
|
||||
|
||||
graph.addNode(nodeA);
|
||||
graph.addNode(nodeB);
|
||||
graph.addNode(nodeC);
|
||||
graph.addNode(nodeD);
|
||||
graph.addNode(nodeE);
|
||||
graph.addNode(nodeF);
|
||||
|
||||
graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA);
|
||||
|
||||
List<Node> shortestPathForNodeB = Arrays.asList(nodeA);
|
||||
List<Node> shortestPathForNodeC = Arrays.asList(nodeA);
|
||||
List<Node> shortestPathForNodeD = Arrays.asList(nodeA, nodeB);
|
||||
List<Node> shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD);
|
||||
List<Node> shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD);
|
||||
|
||||
for (Node node : graph.getNodes()) {
|
||||
switch (node.getName()) {
|
||||
case "B":
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeB));
|
||||
break;
|
||||
case "C":
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeC));
|
||||
break;
|
||||
case "D":
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeD));
|
||||
break;
|
||||
case "E":
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeE));
|
||||
break;
|
||||
case "F":
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeF));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -27,17 +27,12 @@ public class BuilderProcessor extends AbstractProcessor {
|
|||
|
||||
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
|
||||
|
||||
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream()
|
||||
.collect(Collectors.partitioningBy(element ->
|
||||
((ExecutableType) element.asType()).getParameterTypes().size() == 1
|
||||
&& element.getSimpleName().toString().startsWith("set")));
|
||||
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set")));
|
||||
|
||||
List<Element> setters = annotatedMethods.get(true);
|
||||
List<Element> otherMethods = annotatedMethods.get(false);
|
||||
|
||||
otherMethods.forEach(element ->
|
||||
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
|
||||
"@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
||||
otherMethods.forEach(element -> processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
||||
|
||||
if (setters.isEmpty()) {
|
||||
continue;
|
||||
|
@ -45,11 +40,7 @@ public class BuilderProcessor extends AbstractProcessor {
|
|||
|
||||
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
|
||||
|
||||
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(
|
||||
setter -> setter.getSimpleName().toString(),
|
||||
setter -> ((ExecutableType) setter.asType())
|
||||
.getParameterTypes().get(0).toString()
|
||||
));
|
||||
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString()));
|
||||
|
||||
try {
|
||||
writeBuilderFile(className, setterMap);
|
||||
|
|
|
@ -9,10 +9,7 @@ public class PersonBuilderTest {
|
|||
@Test
|
||||
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
||||
|
||||
Person person = new PersonBuilder()
|
||||
.setAge(25)
|
||||
.setName("John")
|
||||
.build();
|
||||
Person person = new PersonBuilder().setAge(25).setName("John").build();
|
||||
|
||||
assertEquals(25, person.getAge());
|
||||
assertEquals("John", person.getName());
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
<?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">
|
||||
<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">
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -8,7 +8,7 @@ public class Server {
|
|||
String address = "http://localhost:8080/baeldung";
|
||||
Endpoint.publish(address, implementor);
|
||||
System.out.println("Server ready...");
|
||||
Thread.sleep(60 * 1000);
|
||||
Thread.sleep(60 * 1000);
|
||||
System.out.println("Server exiting");
|
||||
System.exit(0);
|
||||
}
|
||||
|
|
|
@ -11,7 +11,7 @@ public class RestfulServer {
|
|||
factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository()));
|
||||
factoryBean.setAddress("http://localhost:8080/");
|
||||
Server server = factoryBean.create();
|
||||
|
||||
|
||||
System.out.println("Server ready...");
|
||||
Thread.sleep(60 * 1000);
|
||||
System.out.println("Server exiting");
|
||||
|
|
|
@ -5,20 +5,20 @@
|
|||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
|
||||
<modules>
|
||||
<module>cxf-introduction</module>
|
||||
<module>cxf-spring</module>
|
||||
<module>cxf-jaxrs-implementation</module>
|
||||
<module>cxf-aegis</module>
|
||||
</modules>
|
||||
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
|
@ -27,7 +27,7 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<pluginManagement>
|
||||
|
|
|
@ -1,154 +1,155 @@
|
|||
<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>apache-fop</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<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>apache-fop</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<name>apache-fop</name>
|
||||
<name>apache-fop</name>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
|
||||
<!-- logging -->
|
||||
<!-- logging -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- new dependencies -->
|
||||
<!-- new dependencies -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlgraphics</groupId>
|
||||
<artifactId>fop</artifactId>
|
||||
<version>${fop.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.avalon.framework</groupId>
|
||||
<artifactId>avalon-framework-api</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.avalon.framework</groupId>
|
||||
<artifactId>avalon-framework-impl</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlgraphics</groupId>
|
||||
<artifactId>fop</artifactId>
|
||||
<version>${fop.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.avalon.framework</groupId>
|
||||
<artifactId>avalon-framework-api</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.avalon.framework</groupId>
|
||||
<artifactId>avalon-framework-impl</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>avalon-framework</groupId>
|
||||
<artifactId>avalon-framework-api</artifactId>
|
||||
<version>${avalon-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>avalon-framework</groupId>
|
||||
<artifactId>avalon-framework-impl</artifactId>
|
||||
<version>${avalon-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>avalon-framework</groupId>
|
||||
<artifactId>avalon-framework-api</artifactId>
|
||||
<version>${avalon-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>avalon-framework</groupId>
|
||||
<artifactId>avalon-framework-impl</artifactId>
|
||||
<version>${avalon-framework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dbdoclet</groupId>
|
||||
<artifactId>dbdoclet</artifactId>
|
||||
<version>${dbdoclet.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.dbdoclet</groupId>
|
||||
<artifactId>dbdoclet</artifactId>
|
||||
<version>${dbdoclet.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dbdoclet</groupId>
|
||||
<artifactId>herold</artifactId>
|
||||
<version>6.1.0</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sf.jtidy</groupId>
|
||||
<artifactId>jtidy</artifactId>
|
||||
<version>${jtidy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.dbdoclet</groupId>
|
||||
<artifactId>herold</artifactId>
|
||||
<version>6.1.0</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<dependency>
|
||||
<groupId>net.sf.jtidy</groupId>
|
||||
<artifactId>jtidy</artifactId>
|
||||
<version>${jtidy.version}</version>
|
||||
</dependency>
|
||||
|
||||
<build>
|
||||
<finalName>apache-fop</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</dependencies>
|
||||
|
||||
<plugins>
|
||||
<build>
|
||||
<finalName>apache-fop</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
|
@ -170,7 +171,7 @@
|
|||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
|
@ -185,25 +186,25 @@
|
|||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<fop.version>1.1</fop.version>
|
||||
<avalon-framework.version>4.3</avalon-framework.version>
|
||||
<dbdoclet.version>8.0.2</dbdoclet.version>
|
||||
<jtidy.version>r938</jtidy.version>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<properties>
|
||||
<fop.version>1.1</fop.version>
|
||||
<avalon-framework.version>4.3</avalon-framework.version>
|
||||
<dbdoclet.version>8.0.2</dbdoclet.version>
|
||||
<jtidy.version>r938</jtidy.version>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
</properties>
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)
|
|
@ -9,6 +9,7 @@
|
|||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<poi.version>3.15</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
|
@ -37,5 +38,20 @@
|
|||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml-schemas</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jxls</groupId>
|
||||
<artifactId>jxls-jexcel</artifactId>
|
||||
<version>${jexcel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,79 @@
|
|||
package com.baeldung.jexcel;
|
||||
|
||||
import jxl.*;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import jxl.read.biff.BiffException;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import jxl.write.*;
|
||||
import jxl.write.Number;
|
||||
import jxl.format.Colour;
|
||||
|
||||
public class JExcelHelper {
|
||||
|
||||
public Map<Integer, List<String>> readJExcel(String fileLocation) throws IOException, BiffException {
|
||||
Map<Integer, List<String>> data = new HashMap<>();
|
||||
|
||||
Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
|
||||
Sheet sheet = workbook.getSheet(0);
|
||||
int rows = sheet.getRows();
|
||||
int columns = sheet.getColumns();
|
||||
|
||||
for (int i = 0; i < rows; i++) {
|
||||
data.put(i, new ArrayList<String>());
|
||||
for (int j = 0; j < columns; j++) {
|
||||
data.get(i).add(sheet.getCell(j, i).getContents());
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public void writeJExcel() throws IOException, WriteException {
|
||||
WritableWorkbook workbook = null;
|
||||
try {
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
String fileLocation = path.substring(0, path.length() - 1) + "temp.xls";
|
||||
|
||||
workbook = Workbook.createWorkbook(new File(fileLocation));
|
||||
|
||||
WritableSheet sheet = workbook.createSheet("Sheet 1", 0);
|
||||
|
||||
WritableCellFormat headerFormat = new WritableCellFormat();
|
||||
WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
|
||||
headerFormat.setFont(font);
|
||||
headerFormat.setBackground(Colour.LIGHT_BLUE);
|
||||
headerFormat.setWrap(true);
|
||||
Label headerLabel = new Label(0, 0, "Name", headerFormat);
|
||||
sheet.setColumnView(0, 60);
|
||||
sheet.addCell(headerLabel);
|
||||
|
||||
headerLabel = new Label(1, 0, "Age", headerFormat);
|
||||
sheet.setColumnView(0, 40);
|
||||
sheet.addCell(headerLabel);
|
||||
|
||||
WritableCellFormat cellFormat = new WritableCellFormat();
|
||||
cellFormat.setWrap(true);
|
||||
|
||||
Label cellLabel = new Label(0, 2, "John Smith", cellFormat);
|
||||
sheet.addCell(cellLabel);
|
||||
Number cellNumber = new Number(1, 2, 20, cellFormat);
|
||||
sheet.addCell(cellNumber);
|
||||
|
||||
cellLabel = new Label(0, 3, "Ana Johnson", cellFormat);
|
||||
sheet.addCell(cellLabel);
|
||||
cellNumber = new Number(1, 3, 30, cellFormat);
|
||||
sheet.addCell(cellNumber);
|
||||
|
||||
workbook.write();
|
||||
} finally {
|
||||
if (workbook != null) {
|
||||
workbook.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,137 @@
|
|||
package com.baeldung.poi.excel;
|
||||
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellType;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.IndexedColors;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFFont;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
import org.apache.poi.ss.usermodel.FillPatternType;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ExcelPOIHelper {
|
||||
|
||||
public Map<Integer, List<String>> readExcel(String fileLocation) throws IOException {
|
||||
|
||||
Map<Integer, List<String>> data = new HashMap<>();
|
||||
FileInputStream file = new FileInputStream(new File(fileLocation));
|
||||
Workbook workbook = new XSSFWorkbook(file);
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
int i = 0;
|
||||
for (Row row : sheet) {
|
||||
data.put(i, new ArrayList<String>());
|
||||
for (Cell cell : row) {
|
||||
switch (cell.getCellTypeEnum()) {
|
||||
case STRING:
|
||||
data.get(i)
|
||||
.add(cell.getRichStringCellValue()
|
||||
.getString());
|
||||
break;
|
||||
case NUMERIC:
|
||||
if (DateUtil.isCellDateFormatted(cell)) {
|
||||
data.get(i)
|
||||
.add(cell.getDateCellValue() + "");
|
||||
} else {
|
||||
data.get(i)
|
||||
.add((int)cell.getNumericCellValue() + "");
|
||||
}
|
||||
break;
|
||||
case BOOLEAN:
|
||||
data.get(i)
|
||||
.add(cell.getBooleanCellValue() + "");
|
||||
break;
|
||||
case FORMULA:
|
||||
data.get(i)
|
||||
.add(cell.getCellFormula() + "");
|
||||
break;
|
||||
default:
|
||||
data.get(i)
|
||||
.add(" ");
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if (workbook != null){
|
||||
workbook.close();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public void writeExcel() throws IOException {
|
||||
Workbook workbook = new XSSFWorkbook();
|
||||
|
||||
try {
|
||||
Sheet sheet = workbook.createSheet("Persons");
|
||||
sheet.setColumnWidth(0, 6000);
|
||||
sheet.setColumnWidth(1, 4000);
|
||||
|
||||
Row header = sheet.createRow(0);
|
||||
|
||||
CellStyle headerStyle = workbook.createCellStyle();
|
||||
|
||||
headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
|
||||
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
|
||||
XSSFFont font = ((XSSFWorkbook) workbook).createFont();
|
||||
font.setFontName("Arial");
|
||||
font.setFontHeightInPoints((short) 16);
|
||||
font.setBold(true);
|
||||
headerStyle.setFont(font);
|
||||
|
||||
Cell headerCell = header.createCell(0);
|
||||
headerCell.setCellValue("Name");
|
||||
headerCell.setCellStyle(headerStyle);
|
||||
|
||||
headerCell = header.createCell(1);
|
||||
headerCell.setCellValue("Age");
|
||||
headerCell.setCellStyle(headerStyle);
|
||||
|
||||
CellStyle style = workbook.createCellStyle();
|
||||
style.setWrapText(true);
|
||||
|
||||
Row row = sheet.createRow(2);
|
||||
Cell cell = row.createCell(0);
|
||||
cell.setCellValue("John Smith");
|
||||
cell.setCellStyle(style);
|
||||
|
||||
cell = row.createCell(1);
|
||||
cell.setCellValue(20);
|
||||
cell.setCellStyle(style);
|
||||
|
||||
row = sheet.createRow(3);
|
||||
cell = row.createCell(0);
|
||||
cell.setCellValue("Ana Johnson");
|
||||
cell.setCellStyle(style);
|
||||
|
||||
cell = row.createCell(1);
|
||||
cell.setCellValue(30);
|
||||
cell.setCellStyle(style);
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx";
|
||||
|
||||
FileOutputStream outputStream = new FileOutputStream(fileLocation);
|
||||
workbook.write(outputStream);
|
||||
} finally {
|
||||
if (workbook != null) {
|
||||
|
||||
workbook.close();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
package com.baeldung.jexcel;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import jxl.read.biff.BiffException;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.jexcel.JExcelHelper;
|
||||
|
||||
import jxl.write.WriteException;
|
||||
import jxl.read.biff.BiffException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
|
||||
public class JExcelTest {
|
||||
|
||||
private JExcelHelper jExcelHelper;
|
||||
private static String FILE_NAME = "temp.xls";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException, WriteException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
jExcelHelper = new JExcelHelper();
|
||||
jExcelHelper.writeJExcel();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException {
|
||||
Map<Integer, List<String>> data = jExcelHelper.readJExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(0)
|
||||
.get(0));
|
||||
assertEquals("Age", data.get(0)
|
||||
.get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(2)
|
||||
.get(0));
|
||||
assertEquals("20", data.get(2)
|
||||
.get(1));
|
||||
|
||||
assertEquals("Ana Johnson", data.get(3)
|
||||
.get(0));
|
||||
assertEquals("30", data.get(3)
|
||||
.get(1));
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.poi.excel;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import jxl.read.biff.BiffException;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.poi.excel.ExcelPOIHelper;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
|
||||
public class ExcelTest {
|
||||
|
||||
private ExcelPOIHelper excelPOIHelper;
|
||||
private static String FILE_NAME = "temp.xlsx";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
excelPOIHelper = new ExcelPOIHelper();
|
||||
excelPOIHelper.writeExcel();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingPOIExcelFile_thenCorrect() throws IOException {
|
||||
Map<Integer, List<String>> data = excelPOIHelper.readExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(0)
|
||||
.get(0));
|
||||
assertEquals("Age", data.get(0)
|
||||
.get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(1)
|
||||
.get(0));
|
||||
assertEquals("20", data.get(1)
|
||||
.get(1));
|
||||
|
||||
assertEquals("Ana Johnson", data.get(2)
|
||||
.get(0));
|
||||
assertEquals("30", data.get(2)
|
||||
.get(1));
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,579 @@
|
|||
/**
|
||||
* Autogenerated by Thrift Compiler (0.10.0)
|
||||
*
|
||||
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
|
||||
* @generated
|
||||
*/
|
||||
package com.baeldung.thrift.impl;
|
||||
|
||||
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
|
||||
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01")
|
||||
public class CrossPlatformResource implements org.apache.thrift.TBase<CrossPlatformResource, CrossPlatformResource._Fields>, java.io.Serializable, Cloneable, Comparable<CrossPlatformResource> {
|
||||
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CrossPlatformResource");
|
||||
|
||||
private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I32, (short)1);
|
||||
private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)2);
|
||||
private static final org.apache.thrift.protocol.TField SALUTATION_FIELD_DESC = new org.apache.thrift.protocol.TField("salutation", org.apache.thrift.protocol.TType.STRING, (short)3);
|
||||
|
||||
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new CrossPlatformResourceStandardSchemeFactory();
|
||||
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new CrossPlatformResourceTupleSchemeFactory();
|
||||
|
||||
public int id; // required
|
||||
public java.lang.String name; // required
|
||||
public java.lang.String salutation; // optional
|
||||
|
||||
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
|
||||
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
|
||||
ID((short)1, "id"),
|
||||
NAME((short)2, "name"),
|
||||
SALUTATION((short)3, "salutation");
|
||||
|
||||
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
|
||||
|
||||
static {
|
||||
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
|
||||
byName.put(field.getFieldName(), field);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the _Fields constant that matches fieldId, or null if its not found.
|
||||
*/
|
||||
public static _Fields findByThriftId(int fieldId) {
|
||||
switch(fieldId) {
|
||||
case 1: // ID
|
||||
return ID;
|
||||
case 2: // NAME
|
||||
return NAME;
|
||||
case 3: // SALUTATION
|
||||
return SALUTATION;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the _Fields constant that matches fieldId, throwing an exception
|
||||
* if it is not found.
|
||||
*/
|
||||
public static _Fields findByThriftIdOrThrow(int fieldId) {
|
||||
_Fields fields = findByThriftId(fieldId);
|
||||
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
|
||||
return fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the _Fields constant that matches name, or null if its not found.
|
||||
*/
|
||||
public static _Fields findByName(java.lang.String name) {
|
||||
return byName.get(name);
|
||||
}
|
||||
|
||||
private final short _thriftId;
|
||||
private final java.lang.String _fieldName;
|
||||
|
||||
_Fields(short thriftId, java.lang.String fieldName) {
|
||||
_thriftId = thriftId;
|
||||
_fieldName = fieldName;
|
||||
}
|
||||
|
||||
public short getThriftFieldId() {
|
||||
return _thriftId;
|
||||
}
|
||||
|
||||
public java.lang.String getFieldName() {
|
||||
return _fieldName;
|
||||
}
|
||||
}
|
||||
|
||||
// isset id assignments
|
||||
private static final int __ID_ISSET_ID = 0;
|
||||
private byte __isset_bitfield = 0;
|
||||
private static final _Fields optionals[] = {_Fields.SALUTATION};
|
||||
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
|
||||
static {
|
||||
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
|
||||
tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT,
|
||||
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
|
||||
tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT,
|
||||
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
|
||||
tmpMap.put(_Fields.SALUTATION, new org.apache.thrift.meta_data.FieldMetaData("salutation", org.apache.thrift.TFieldRequirementType.OPTIONAL,
|
||||
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
|
||||
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
|
||||
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CrossPlatformResource.class, metaDataMap);
|
||||
}
|
||||
|
||||
public CrossPlatformResource() {
|
||||
}
|
||||
|
||||
public CrossPlatformResource(
|
||||
int id,
|
||||
java.lang.String name)
|
||||
{
|
||||
this();
|
||||
this.id = id;
|
||||
setIdIsSet(true);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a deep copy on <i>other</i>.
|
||||
*/
|
||||
public CrossPlatformResource(CrossPlatformResource other) {
|
||||
__isset_bitfield = other.__isset_bitfield;
|
||||
this.id = other.id;
|
||||
if (other.isSetName()) {
|
||||
this.name = other.name;
|
||||
}
|
||||
if (other.isSetSalutation()) {
|
||||
this.salutation = other.salutation;
|
||||
}
|
||||
}
|
||||
|
||||
public CrossPlatformResource deepCopy() {
|
||||
return new CrossPlatformResource(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
setIdIsSet(false);
|
||||
this.id = 0;
|
||||
this.name = null;
|
||||
this.salutation = null;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public CrossPlatformResource setId(int id) {
|
||||
this.id = id;
|
||||
setIdIsSet(true);
|
||||
return this;
|
||||
}
|
||||
|
||||
public void unsetId() {
|
||||
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID);
|
||||
}
|
||||
|
||||
/** Returns true if field id is set (has been assigned a value) and false otherwise */
|
||||
public boolean isSetId() {
|
||||
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID);
|
||||
}
|
||||
|
||||
public void setIdIsSet(boolean value) {
|
||||
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value);
|
||||
}
|
||||
|
||||
public java.lang.String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public CrossPlatformResource setName(java.lang.String name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void unsetName() {
|
||||
this.name = null;
|
||||
}
|
||||
|
||||
/** Returns true if field name is set (has been assigned a value) and false otherwise */
|
||||
public boolean isSetName() {
|
||||
return this.name != null;
|
||||
}
|
||||
|
||||
public void setNameIsSet(boolean value) {
|
||||
if (!value) {
|
||||
this.name = null;
|
||||
}
|
||||
}
|
||||
|
||||
public java.lang.String getSalutation() {
|
||||
return this.salutation;
|
||||
}
|
||||
|
||||
public CrossPlatformResource setSalutation(java.lang.String salutation) {
|
||||
this.salutation = salutation;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void unsetSalutation() {
|
||||
this.salutation = null;
|
||||
}
|
||||
|
||||
/** Returns true if field salutation is set (has been assigned a value) and false otherwise */
|
||||
public boolean isSetSalutation() {
|
||||
return this.salutation != null;
|
||||
}
|
||||
|
||||
public void setSalutationIsSet(boolean value) {
|
||||
if (!value) {
|
||||
this.salutation = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void setFieldValue(_Fields field, java.lang.Object value) {
|
||||
switch (field) {
|
||||
case ID:
|
||||
if (value == null) {
|
||||
unsetId();
|
||||
} else {
|
||||
setId((java.lang.Integer)value);
|
||||
}
|
||||
break;
|
||||
|
||||
case NAME:
|
||||
if (value == null) {
|
||||
unsetName();
|
||||
} else {
|
||||
setName((java.lang.String)value);
|
||||
}
|
||||
break;
|
||||
|
||||
case SALUTATION:
|
||||
if (value == null) {
|
||||
unsetSalutation();
|
||||
} else {
|
||||
setSalutation((java.lang.String)value);
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public java.lang.Object getFieldValue(_Fields field) {
|
||||
switch (field) {
|
||||
case ID:
|
||||
return getId();
|
||||
|
||||
case NAME:
|
||||
return getName();
|
||||
|
||||
case SALUTATION:
|
||||
return getSalutation();
|
||||
|
||||
}
|
||||
throw new java.lang.IllegalStateException();
|
||||
}
|
||||
|
||||
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
|
||||
public boolean isSet(_Fields field) {
|
||||
if (field == null) {
|
||||
throw new java.lang.IllegalArgumentException();
|
||||
}
|
||||
|
||||
switch (field) {
|
||||
case ID:
|
||||
return isSetId();
|
||||
case NAME:
|
||||
return isSetName();
|
||||
case SALUTATION:
|
||||
return isSetSalutation();
|
||||
}
|
||||
throw new java.lang.IllegalStateException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(java.lang.Object that) {
|
||||
if (that == null)
|
||||
return false;
|
||||
if (that instanceof CrossPlatformResource)
|
||||
return this.equals((CrossPlatformResource)that);
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean equals(CrossPlatformResource that) {
|
||||
if (that == null)
|
||||
return false;
|
||||
if (this == that)
|
||||
return true;
|
||||
|
||||
boolean this_present_id = true;
|
||||
boolean that_present_id = true;
|
||||
if (this_present_id || that_present_id) {
|
||||
if (!(this_present_id && that_present_id))
|
||||
return false;
|
||||
if (this.id != that.id)
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean this_present_name = true && this.isSetName();
|
||||
boolean that_present_name = true && that.isSetName();
|
||||
if (this_present_name || that_present_name) {
|
||||
if (!(this_present_name && that_present_name))
|
||||
return false;
|
||||
if (!this.name.equals(that.name))
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean this_present_salutation = true && this.isSetSalutation();
|
||||
boolean that_present_salutation = true && that.isSetSalutation();
|
||||
if (this_present_salutation || that_present_salutation) {
|
||||
if (!(this_present_salutation && that_present_salutation))
|
||||
return false;
|
||||
if (!this.salutation.equals(that.salutation))
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hashCode = 1;
|
||||
|
||||
hashCode = hashCode * 8191 + id;
|
||||
|
||||
hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287);
|
||||
if (isSetName())
|
||||
hashCode = hashCode * 8191 + name.hashCode();
|
||||
|
||||
hashCode = hashCode * 8191 + ((isSetSalutation()) ? 131071 : 524287);
|
||||
if (isSetSalutation())
|
||||
hashCode = hashCode * 8191 + salutation.hashCode();
|
||||
|
||||
return hashCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(CrossPlatformResource other) {
|
||||
if (!getClass().equals(other.getClass())) {
|
||||
return getClass().getName().compareTo(other.getClass().getName());
|
||||
}
|
||||
|
||||
int lastComparison = 0;
|
||||
|
||||
lastComparison = java.lang.Boolean.valueOf(isSetId()).compareTo(other.isSetId());
|
||||
if (lastComparison != 0) {
|
||||
return lastComparison;
|
||||
}
|
||||
if (isSetId()) {
|
||||
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id);
|
||||
if (lastComparison != 0) {
|
||||
return lastComparison;
|
||||
}
|
||||
}
|
||||
lastComparison = java.lang.Boolean.valueOf(isSetName()).compareTo(other.isSetName());
|
||||
if (lastComparison != 0) {
|
||||
return lastComparison;
|
||||
}
|
||||
if (isSetName()) {
|
||||
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name);
|
||||
if (lastComparison != 0) {
|
||||
return lastComparison;
|
||||
}
|
||||
}
|
||||
lastComparison = java.lang.Boolean.valueOf(isSetSalutation()).compareTo(other.isSetSalutation());
|
||||
if (lastComparison != 0) {
|
||||
return lastComparison;
|
||||
}
|
||||
if (isSetSalutation()) {
|
||||
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.salutation, other.salutation);
|
||||
if (lastComparison != 0) {
|
||||
return lastComparison;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public _Fields fieldForId(int fieldId) {
|
||||
return _Fields.findByThriftId(fieldId);
|
||||
}
|
||||
|
||||
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
|
||||
scheme(iprot).read(iprot, this);
|
||||
}
|
||||
|
||||
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
|
||||
scheme(oprot).write(oprot, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.lang.String toString() {
|
||||
java.lang.StringBuilder sb = new java.lang.StringBuilder("CrossPlatformResource(");
|
||||
boolean first = true;
|
||||
|
||||
sb.append("id:");
|
||||
sb.append(this.id);
|
||||
first = false;
|
||||
if (!first) sb.append(", ");
|
||||
sb.append("name:");
|
||||
if (this.name == null) {
|
||||
sb.append("null");
|
||||
} else {
|
||||
sb.append(this.name);
|
||||
}
|
||||
first = false;
|
||||
if (isSetSalutation()) {
|
||||
if (!first) sb.append(", ");
|
||||
sb.append("salutation:");
|
||||
if (this.salutation == null) {
|
||||
sb.append("null");
|
||||
} else {
|
||||
sb.append(this.salutation);
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
sb.append(")");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void validate() throws org.apache.thrift.TException {
|
||||
// check for required fields
|
||||
// check for sub-struct validity
|
||||
}
|
||||
|
||||
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
|
||||
try {
|
||||
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
|
||||
} catch (org.apache.thrift.TException te) {
|
||||
throw new java.io.IOException(te);
|
||||
}
|
||||
}
|
||||
|
||||
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
|
||||
try {
|
||||
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
|
||||
__isset_bitfield = 0;
|
||||
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
|
||||
} catch (org.apache.thrift.TException te) {
|
||||
throw new java.io.IOException(te);
|
||||
}
|
||||
}
|
||||
|
||||
private static class CrossPlatformResourceStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
|
||||
public CrossPlatformResourceStandardScheme getScheme() {
|
||||
return new CrossPlatformResourceStandardScheme();
|
||||
}
|
||||
}
|
||||
|
||||
private static class CrossPlatformResourceStandardScheme extends org.apache.thrift.scheme.StandardScheme<CrossPlatformResource> {
|
||||
|
||||
public void read(org.apache.thrift.protocol.TProtocol iprot, CrossPlatformResource struct) throws org.apache.thrift.TException {
|
||||
org.apache.thrift.protocol.TField schemeField;
|
||||
iprot.readStructBegin();
|
||||
while (true)
|
||||
{
|
||||
schemeField = iprot.readFieldBegin();
|
||||
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
|
||||
break;
|
||||
}
|
||||
switch (schemeField.id) {
|
||||
case 1: // ID
|
||||
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
|
||||
struct.id = iprot.readI32();
|
||||
struct.setIdIsSet(true);
|
||||
} else {
|
||||
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
|
||||
}
|
||||
break;
|
||||
case 2: // NAME
|
||||
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
|
||||
struct.name = iprot.readString();
|
||||
struct.setNameIsSet(true);
|
||||
} else {
|
||||
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
|
||||
}
|
||||
break;
|
||||
case 3: // SALUTATION
|
||||
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
|
||||
struct.salutation = iprot.readString();
|
||||
struct.setSalutationIsSet(true);
|
||||
} else {
|
||||
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
|
||||
}
|
||||
iprot.readFieldEnd();
|
||||
}
|
||||
iprot.readStructEnd();
|
||||
|
||||
// check for required fields of primitive type, which can't be checked in the validate method
|
||||
struct.validate();
|
||||
}
|
||||
|
||||
public void write(org.apache.thrift.protocol.TProtocol oprot, CrossPlatformResource struct) throws org.apache.thrift.TException {
|
||||
struct.validate();
|
||||
|
||||
oprot.writeStructBegin(STRUCT_DESC);
|
||||
oprot.writeFieldBegin(ID_FIELD_DESC);
|
||||
oprot.writeI32(struct.id);
|
||||
oprot.writeFieldEnd();
|
||||
if (struct.name != null) {
|
||||
oprot.writeFieldBegin(NAME_FIELD_DESC);
|
||||
oprot.writeString(struct.name);
|
||||
oprot.writeFieldEnd();
|
||||
}
|
||||
if (struct.salutation != null) {
|
||||
if (struct.isSetSalutation()) {
|
||||
oprot.writeFieldBegin(SALUTATION_FIELD_DESC);
|
||||
oprot.writeString(struct.salutation);
|
||||
oprot.writeFieldEnd();
|
||||
}
|
||||
}
|
||||
oprot.writeFieldStop();
|
||||
oprot.writeStructEnd();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class CrossPlatformResourceTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
|
||||
public CrossPlatformResourceTupleScheme getScheme() {
|
||||
return new CrossPlatformResourceTupleScheme();
|
||||
}
|
||||
}
|
||||
|
||||
private static class CrossPlatformResourceTupleScheme extends org.apache.thrift.scheme.TupleScheme<CrossPlatformResource> {
|
||||
|
||||
@Override
|
||||
public void write(org.apache.thrift.protocol.TProtocol prot, CrossPlatformResource struct) throws org.apache.thrift.TException {
|
||||
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
|
||||
java.util.BitSet optionals = new java.util.BitSet();
|
||||
if (struct.isSetId()) {
|
||||
optionals.set(0);
|
||||
}
|
||||
if (struct.isSetName()) {
|
||||
optionals.set(1);
|
||||
}
|
||||
if (struct.isSetSalutation()) {
|
||||
optionals.set(2);
|
||||
}
|
||||
oprot.writeBitSet(optionals, 3);
|
||||
if (struct.isSetId()) {
|
||||
oprot.writeI32(struct.id);
|
||||
}
|
||||
if (struct.isSetName()) {
|
||||
oprot.writeString(struct.name);
|
||||
}
|
||||
if (struct.isSetSalutation()) {
|
||||
oprot.writeString(struct.salutation);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void read(org.apache.thrift.protocol.TProtocol prot, CrossPlatformResource struct) throws org.apache.thrift.TException {
|
||||
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
|
||||
java.util.BitSet incoming = iprot.readBitSet(3);
|
||||
if (incoming.get(0)) {
|
||||
struct.id = iprot.readI32();
|
||||
struct.setIdIsSet(true);
|
||||
}
|
||||
if (incoming.get(1)) {
|
||||
struct.name = iprot.readString();
|
||||
struct.setNameIsSet(true);
|
||||
}
|
||||
if (incoming.get(2)) {
|
||||
struct.salutation = iprot.readString();
|
||||
struct.setSalutationIsSet(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
|
||||
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
|
||||
}
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,472 @@
|
|||
/**
|
||||
* Autogenerated by Thrift Compiler (0.10.0)
|
||||
*
|
||||
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
|
||||
* @generated
|
||||
*/
|
||||
package com.baeldung.thrift.impl;
|
||||
|
||||
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
|
||||
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01")
|
||||
public class InvalidOperationException extends org.apache.thrift.TException implements org.apache.thrift.TBase<InvalidOperationException, InvalidOperationException._Fields>, java.io.Serializable, Cloneable, Comparable<InvalidOperationException> {
|
||||
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InvalidOperationException");
|
||||
|
||||
private static final org.apache.thrift.protocol.TField CODE_FIELD_DESC = new org.apache.thrift.protocol.TField("code", org.apache.thrift.protocol.TType.I32, (short)1);
|
||||
private static final org.apache.thrift.protocol.TField DESCRIPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("description", org.apache.thrift.protocol.TType.STRING, (short)2);
|
||||
|
||||
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new InvalidOperationExceptionStandardSchemeFactory();
|
||||
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new InvalidOperationExceptionTupleSchemeFactory();
|
||||
|
||||
public int code; // required
|
||||
public java.lang.String description; // required
|
||||
|
||||
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
|
||||
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
|
||||
CODE((short)1, "code"),
|
||||
DESCRIPTION((short)2, "description");
|
||||
|
||||
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
|
||||
|
||||
static {
|
||||
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
|
||||
byName.put(field.getFieldName(), field);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the _Fields constant that matches fieldId, or null if its not found.
|
||||
*/
|
||||
public static _Fields findByThriftId(int fieldId) {
|
||||
switch(fieldId) {
|
||||
case 1: // CODE
|
||||
return CODE;
|
||||
case 2: // DESCRIPTION
|
||||
return DESCRIPTION;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the _Fields constant that matches fieldId, throwing an exception
|
||||
* if it is not found.
|
||||
*/
|
||||
public static _Fields findByThriftIdOrThrow(int fieldId) {
|
||||
_Fields fields = findByThriftId(fieldId);
|
||||
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
|
||||
return fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the _Fields constant that matches name, or null if its not found.
|
||||
*/
|
||||
public static _Fields findByName(java.lang.String name) {
|
||||
return byName.get(name);
|
||||
}
|
||||
|
||||
private final short _thriftId;
|
||||
private final java.lang.String _fieldName;
|
||||
|
||||
_Fields(short thriftId, java.lang.String fieldName) {
|
||||
_thriftId = thriftId;
|
||||
_fieldName = fieldName;
|
||||
}
|
||||
|
||||
public short getThriftFieldId() {
|
||||
return _thriftId;
|
||||
}
|
||||
|
||||
public java.lang.String getFieldName() {
|
||||
return _fieldName;
|
||||
}
|
||||
}
|
||||
|
||||
// isset id assignments
|
||||
private static final int __CODE_ISSET_ID = 0;
|
||||
private byte __isset_bitfield = 0;
|
||||
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
|
||||
static {
|
||||
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
|
||||
tmpMap.put(_Fields.CODE, new org.apache.thrift.meta_data.FieldMetaData("code", org.apache.thrift.TFieldRequirementType.DEFAULT,
|
||||
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
|
||||
tmpMap.put(_Fields.DESCRIPTION, new org.apache.thrift.meta_data.FieldMetaData("description", org.apache.thrift.TFieldRequirementType.DEFAULT,
|
||||
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
|
||||
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
|
||||
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(InvalidOperationException.class, metaDataMap);
|
||||
}
|
||||
|
||||
public InvalidOperationException() {
|
||||
}
|
||||
|
||||
public InvalidOperationException(
|
||||
int code,
|
||||
java.lang.String description)
|
||||
{
|
||||
this();
|
||||
this.code = code;
|
||||
setCodeIsSet(true);
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a deep copy on <i>other</i>.
|
||||
*/
|
||||
public InvalidOperationException(InvalidOperationException other) {
|
||||
__isset_bitfield = other.__isset_bitfield;
|
||||
this.code = other.code;
|
||||
if (other.isSetDescription()) {
|
||||
this.description = other.description;
|
||||
}
|
||||
}
|
||||
|
||||
public InvalidOperationException deepCopy() {
|
||||
return new InvalidOperationException(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
setCodeIsSet(false);
|
||||
this.code = 0;
|
||||
this.description = null;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
public InvalidOperationException setCode(int code) {
|
||||
this.code = code;
|
||||
setCodeIsSet(true);
|
||||
return this;
|
||||
}
|
||||
|
||||
public void unsetCode() {
|
||||
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __CODE_ISSET_ID);
|
||||
}
|
||||
|
||||
/** Returns true if field code is set (has been assigned a value) and false otherwise */
|
||||
public boolean isSetCode() {
|
||||
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __CODE_ISSET_ID);
|
||||
}
|
||||
|
||||
public void setCodeIsSet(boolean value) {
|
||||
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __CODE_ISSET_ID, value);
|
||||
}
|
||||
|
||||
public java.lang.String getDescription() {
|
||||
return this.description;
|
||||
}
|
||||
|
||||
public InvalidOperationException setDescription(java.lang.String description) {
|
||||
this.description = description;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void unsetDescription() {
|
||||
this.description = null;
|
||||
}
|
||||
|
||||
/** Returns true if field description is set (has been assigned a value) and false otherwise */
|
||||
public boolean isSetDescription() {
|
||||
return this.description != null;
|
||||
}
|
||||
|
||||
public void setDescriptionIsSet(boolean value) {
|
||||
if (!value) {
|
||||
this.description = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void setFieldValue(_Fields field, java.lang.Object value) {
|
||||
switch (field) {
|
||||
case CODE:
|
||||
if (value == null) {
|
||||
unsetCode();
|
||||
} else {
|
||||
setCode((java.lang.Integer)value);
|
||||
}
|
||||
break;
|
||||
|
||||
case DESCRIPTION:
|
||||
if (value == null) {
|
||||
unsetDescription();
|
||||
} else {
|
||||
setDescription((java.lang.String)value);
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public java.lang.Object getFieldValue(_Fields field) {
|
||||
switch (field) {
|
||||
case CODE:
|
||||
return getCode();
|
||||
|
||||
case DESCRIPTION:
|
||||
return getDescription();
|
||||
|
||||
}
|
||||
throw new java.lang.IllegalStateException();
|
||||
}
|
||||
|
||||
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
|
||||
public boolean isSet(_Fields field) {
|
||||
if (field == null) {
|
||||
throw new java.lang.IllegalArgumentException();
|
||||
}
|
||||
|
||||
switch (field) {
|
||||
case CODE:
|
||||
return isSetCode();
|
||||
case DESCRIPTION:
|
||||
return isSetDescription();
|
||||
}
|
||||
throw new java.lang.IllegalStateException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(java.lang.Object that) {
|
||||
if (that == null)
|
||||
return false;
|
||||
if (that instanceof InvalidOperationException)
|
||||
return this.equals((InvalidOperationException)that);
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean equals(InvalidOperationException that) {
|
||||
if (that == null)
|
||||
return false;
|
||||
if (this == that)
|
||||
return true;
|
||||
|
||||
boolean this_present_code = true;
|
||||
boolean that_present_code = true;
|
||||
if (this_present_code || that_present_code) {
|
||||
if (!(this_present_code && that_present_code))
|
||||
return false;
|
||||
if (this.code != that.code)
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean this_present_description = true && this.isSetDescription();
|
||||
boolean that_present_description = true && that.isSetDescription();
|
||||
if (this_present_description || that_present_description) {
|
||||
if (!(this_present_description && that_present_description))
|
||||
return false;
|
||||
if (!this.description.equals(that.description))
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hashCode = 1;
|
||||
|
||||
hashCode = hashCode * 8191 + code;
|
||||
|
||||
hashCode = hashCode * 8191 + ((isSetDescription()) ? 131071 : 524287);
|
||||
if (isSetDescription())
|
||||
hashCode = hashCode * 8191 + description.hashCode();
|
||||
|
||||
return hashCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(InvalidOperationException other) {
|
||||
if (!getClass().equals(other.getClass())) {
|
||||
return getClass().getName().compareTo(other.getClass().getName());
|
||||
}
|
||||
|
||||
int lastComparison = 0;
|
||||
|
||||
lastComparison = java.lang.Boolean.valueOf(isSetCode()).compareTo(other.isSetCode());
|
||||
if (lastComparison != 0) {
|
||||
return lastComparison;
|
||||
}
|
||||
if (isSetCode()) {
|
||||
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.code, other.code);
|
||||
if (lastComparison != 0) {
|
||||
return lastComparison;
|
||||
}
|
||||
}
|
||||
lastComparison = java.lang.Boolean.valueOf(isSetDescription()).compareTo(other.isSetDescription());
|
||||
if (lastComparison != 0) {
|
||||
return lastComparison;
|
||||
}
|
||||
if (isSetDescription()) {
|
||||
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.description, other.description);
|
||||
if (lastComparison != 0) {
|
||||
return lastComparison;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public _Fields fieldForId(int fieldId) {
|
||||
return _Fields.findByThriftId(fieldId);
|
||||
}
|
||||
|
||||
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
|
||||
scheme(iprot).read(iprot, this);
|
||||
}
|
||||
|
||||
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
|
||||
scheme(oprot).write(oprot, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.lang.String toString() {
|
||||
java.lang.StringBuilder sb = new java.lang.StringBuilder("InvalidOperationException(");
|
||||
boolean first = true;
|
||||
|
||||
sb.append("code:");
|
||||
sb.append(this.code);
|
||||
first = false;
|
||||
if (!first) sb.append(", ");
|
||||
sb.append("description:");
|
||||
if (this.description == null) {
|
||||
sb.append("null");
|
||||
} else {
|
||||
sb.append(this.description);
|
||||
}
|
||||
first = false;
|
||||
sb.append(")");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void validate() throws org.apache.thrift.TException {
|
||||
// check for required fields
|
||||
// check for sub-struct validity
|
||||
}
|
||||
|
||||
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
|
||||
try {
|
||||
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
|
||||
} catch (org.apache.thrift.TException te) {
|
||||
throw new java.io.IOException(te);
|
||||
}
|
||||
}
|
||||
|
||||
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
|
||||
try {
|
||||
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
|
||||
__isset_bitfield = 0;
|
||||
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
|
||||
} catch (org.apache.thrift.TException te) {
|
||||
throw new java.io.IOException(te);
|
||||
}
|
||||
}
|
||||
|
||||
private static class InvalidOperationExceptionStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
|
||||
public InvalidOperationExceptionStandardScheme getScheme() {
|
||||
return new InvalidOperationExceptionStandardScheme();
|
||||
}
|
||||
}
|
||||
|
||||
private static class InvalidOperationExceptionStandardScheme extends org.apache.thrift.scheme.StandardScheme<InvalidOperationException> {
|
||||
|
||||
public void read(org.apache.thrift.protocol.TProtocol iprot, InvalidOperationException struct) throws org.apache.thrift.TException {
|
||||
org.apache.thrift.protocol.TField schemeField;
|
||||
iprot.readStructBegin();
|
||||
while (true)
|
||||
{
|
||||
schemeField = iprot.readFieldBegin();
|
||||
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
|
||||
break;
|
||||
}
|
||||
switch (schemeField.id) {
|
||||
case 1: // CODE
|
||||
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
|
||||
struct.code = iprot.readI32();
|
||||
struct.setCodeIsSet(true);
|
||||
} else {
|
||||
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
|
||||
}
|
||||
break;
|
||||
case 2: // DESCRIPTION
|
||||
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
|
||||
struct.description = iprot.readString();
|
||||
struct.setDescriptionIsSet(true);
|
||||
} else {
|
||||
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
|
||||
}
|
||||
iprot.readFieldEnd();
|
||||
}
|
||||
iprot.readStructEnd();
|
||||
|
||||
// check for required fields of primitive type, which can't be checked in the validate method
|
||||
struct.validate();
|
||||
}
|
||||
|
||||
public void write(org.apache.thrift.protocol.TProtocol oprot, InvalidOperationException struct) throws org.apache.thrift.TException {
|
||||
struct.validate();
|
||||
|
||||
oprot.writeStructBegin(STRUCT_DESC);
|
||||
oprot.writeFieldBegin(CODE_FIELD_DESC);
|
||||
oprot.writeI32(struct.code);
|
||||
oprot.writeFieldEnd();
|
||||
if (struct.description != null) {
|
||||
oprot.writeFieldBegin(DESCRIPTION_FIELD_DESC);
|
||||
oprot.writeString(struct.description);
|
||||
oprot.writeFieldEnd();
|
||||
}
|
||||
oprot.writeFieldStop();
|
||||
oprot.writeStructEnd();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class InvalidOperationExceptionTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
|
||||
public InvalidOperationExceptionTupleScheme getScheme() {
|
||||
return new InvalidOperationExceptionTupleScheme();
|
||||
}
|
||||
}
|
||||
|
||||
private static class InvalidOperationExceptionTupleScheme extends org.apache.thrift.scheme.TupleScheme<InvalidOperationException> {
|
||||
|
||||
@Override
|
||||
public void write(org.apache.thrift.protocol.TProtocol prot, InvalidOperationException struct) throws org.apache.thrift.TException {
|
||||
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
|
||||
java.util.BitSet optionals = new java.util.BitSet();
|
||||
if (struct.isSetCode()) {
|
||||
optionals.set(0);
|
||||
}
|
||||
if (struct.isSetDescription()) {
|
||||
optionals.set(1);
|
||||
}
|
||||
oprot.writeBitSet(optionals, 2);
|
||||
if (struct.isSetCode()) {
|
||||
oprot.writeI32(struct.code);
|
||||
}
|
||||
if (struct.isSetDescription()) {
|
||||
oprot.writeString(struct.description);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void read(org.apache.thrift.protocol.TProtocol prot, InvalidOperationException struct) throws org.apache.thrift.TException {
|
||||
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
|
||||
java.util.BitSet incoming = iprot.readBitSet(2);
|
||||
if (incoming.get(0)) {
|
||||
struct.code = iprot.readI32();
|
||||
struct.setCodeIsSet(true);
|
||||
}
|
||||
if (incoming.get(1)) {
|
||||
struct.description = iprot.readString();
|
||||
struct.setDescriptionIsSet(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
|
||||
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
<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>apache-thrift</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<properties>
|
||||
<java.versin>1.8</java.versin>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<thrift.version>0.10.0</thrift.version>
|
||||
<maven-thrift.version>0.1.11</maven-thrift.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.thrift</groupId>
|
||||
<artifactId>libthrift</artifactId>
|
||||
<version>${thrift.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>1.7.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>generate-sources</phase>
|
||||
<goals><goal>add-source</goal></goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>generated</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.thrift;
|
||||
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) throws TTransportException {
|
||||
CrossPlatformServiceServer server = new CrossPlatformServiceServer();
|
||||
server.start();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.thrift;
|
||||
|
||||
import com.baeldung.thrift.impl.CrossPlatformService;
|
||||
|
||||
import org.apache.thrift.TException;
|
||||
import org.apache.thrift.protocol.TBinaryProtocol;
|
||||
import org.apache.thrift.protocol.TProtocol;
|
||||
import org.apache.thrift.transport.TSocket;
|
||||
import org.apache.thrift.transport.TTransport;
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
|
||||
public class CrossPlatformServiceClient {
|
||||
|
||||
public boolean ping() {
|
||||
try {
|
||||
TTransport transport;
|
||||
|
||||
transport = new TSocket("localhost", 9090);
|
||||
transport.open();
|
||||
|
||||
TProtocol protocol = new TBinaryProtocol(transport);
|
||||
CrossPlatformService.Client client = new CrossPlatformService.Client(protocol);
|
||||
|
||||
System.out.print("Calling remote method...");
|
||||
|
||||
boolean result = client.ping();
|
||||
|
||||
System.out.println("done.");
|
||||
|
||||
transport.close();
|
||||
|
||||
return result;
|
||||
} catch (TTransportException e) {
|
||||
e.printStackTrace();
|
||||
} catch (TException x) {
|
||||
x.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.thrift;
|
||||
|
||||
import com.baeldung.thrift.impl.CrossPlatformResource;
|
||||
import com.baeldung.thrift.impl.CrossPlatformService;
|
||||
import com.baeldung.thrift.impl.InvalidOperationException;
|
||||
|
||||
import org.apache.thrift.TException;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class CrossPlatformServiceImpl implements CrossPlatformService.Iface {
|
||||
|
||||
@Override
|
||||
public CrossPlatformResource get(final int id) throws InvalidOperationException, TException {
|
||||
// add some action
|
||||
return new CrossPlatformResource();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(final CrossPlatformResource resource) throws InvalidOperationException, TException {
|
||||
// add some action
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CrossPlatformResource> getList() throws InvalidOperationException, TException {
|
||||
// add some action
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean ping() throws InvalidOperationException, TException {
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.thrift;
|
||||
|
||||
import com.baeldung.thrift.impl.CrossPlatformService;
|
||||
|
||||
import org.apache.thrift.server.TServer;
|
||||
import org.apache.thrift.server.TSimpleServer;
|
||||
import org.apache.thrift.transport.TServerSocket;
|
||||
import org.apache.thrift.transport.TServerTransport;
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
|
||||
public class CrossPlatformServiceServer {
|
||||
|
||||
private TServer server;
|
||||
|
||||
public void start() throws TTransportException {
|
||||
TServerTransport serverTransport = new TServerSocket(9090);
|
||||
server = new TSimpleServer(new TServer.Args(serverTransport)
|
||||
.processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl())));
|
||||
|
||||
System.out.print("Starting the server... ");
|
||||
|
||||
server.serve();
|
||||
|
||||
System.out.println("done.");
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (server != null && server.isServing()) {
|
||||
System.out.print("Stopping the server... ");
|
||||
|
||||
server.stop();
|
||||
|
||||
System.out.println("done.");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
namespace cpp com.baeldung.thrift.impl
|
||||
namespace java com.baeldung.thrift.impl
|
||||
|
||||
exception InvalidOperationException {
|
||||
1: i32 code,
|
||||
2: string description
|
||||
}
|
||||
|
||||
struct CrossPlatformResource {
|
||||
1: i32 id,
|
||||
2: string name,
|
||||
3: optional string salutation
|
||||
}
|
||||
|
||||
service CrossPlatformService {
|
||||
|
||||
CrossPlatformResource get(1:i32 id) throws (1:InvalidOperationException e),
|
||||
|
||||
void save(1:CrossPlatformResource resource) throws (1:InvalidOperationException e),
|
||||
|
||||
list <CrossPlatformResource> getList() throws (1:InvalidOperationException e),
|
||||
|
||||
bool ping() throws (1:InvalidOperationException e)
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.thrift;
|
||||
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CrossPlatformServiceTest {
|
||||
|
||||
private CrossPlatformServiceServer server = new CrossPlatformServiceServer();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
new Thread(() -> {
|
||||
try {
|
||||
server.start();
|
||||
} catch (TTransportException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}).start();
|
||||
try {
|
||||
// wait for the server start up
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
server.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ping() {
|
||||
CrossPlatformServiceClient client = new CrossPlatformServiceClient();
|
||||
Assert.assertTrue(client.ping());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Intro to AspectJ](http://www.baeldung.com/aspectj)
|
||||
- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging)
|
|
@ -12,39 +12,69 @@
|
|||
<artifactId>aspectjrt</artifactId>
|
||||
<version>${aspectj.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
<version>${aspectj.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-core</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- unit test -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cglib</groupId>
|
||||
<artifactId>cglib</artifactId>
|
||||
<version>3.2.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aop</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -65,9 +95,9 @@
|
|||
<source>${source.version}</source>
|
||||
<target>${source.version}</target>
|
||||
</configuration>
|
||||
|
||||
|
||||
</plugin>
|
||||
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>aspectj-maven-plugin</artifactId>
|
||||
|
@ -81,41 +111,22 @@
|
|||
<Xlint>ignore</Xlint>
|
||||
<encoding>${project.build.sourceEncoding}</encoding>
|
||||
<!-- Post-compile weaving -->
|
||||
<!--
|
||||
<weaveDependencies>
|
||||
<weaveDependency>
|
||||
<groupId>org.agroup</groupId>
|
||||
<artifactId>to-weave</artifactId>
|
||||
</weaveDependency>
|
||||
<weaveDependency>
|
||||
<groupId>org.anothergroup</groupId>
|
||||
<artifactId>gen</artifactId>
|
||||
</weaveDependency>
|
||||
</weaveDependencies>
|
||||
-->
|
||||
</configuration>
|
||||
<!-- <weaveDependencies> <weaveDependency> <groupId>org.agroup</groupId> <artifactId>to-weave</artifactId> </weaveDependency>
|
||||
<weaveDependency> <groupId>org.anothergroup</groupId> <artifactId>gen</artifactId> </weaveDependency> </weaveDependencies> -->
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
<goal>test-compile</goal>
|
||||
<goal>test-compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!--
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.10</version>
|
||||
<configuration>
|
||||
<argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
|
||||
<useSystemClassLoader>true</useSystemClassLoader>
|
||||
<forkMode>always</forkMode>
|
||||
</configuration>
|
||||
</plugin>
|
||||
-->
|
||||
|
||||
<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.10</version>
|
||||
<configuration> <argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
|
||||
<useSystemClassLoader>true</useSystemClassLoader> <forkMode>always</forkMode> </configuration> </plugin> -->
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.performancemonitor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Month;
|
||||
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.springframework.aop.Advisor;
|
||||
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
|
||||
import org.springframework.aop.interceptor.PerformanceMonitorInterceptor;
|
||||
import org.springframework.aop.support.DefaultPointcutAdvisor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
|
||||
@Configuration
|
||||
@EnableAspectJAutoProxy
|
||||
public class AopConfiguration {
|
||||
|
||||
@Pointcut("execution(public String com.baeldung.performancemonitor.PersonService.getFullName(..))")
|
||||
public void monitor() { }
|
||||
|
||||
@Pointcut("execution(public int com.baeldung.performancemonitor.PersonService.getAge(..))")
|
||||
public void myMonitor() { }
|
||||
|
||||
@Bean
|
||||
public PerformanceMonitorInterceptor performanceMonitorInterceptor() {
|
||||
return new PerformanceMonitorInterceptor(true);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Advisor performanceMonitorAdvisor() {
|
||||
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
|
||||
pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.monitor()");
|
||||
return new DefaultPointcutAdvisor(pointcut, performanceMonitorInterceptor());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Person person(){
|
||||
return new Person("John","Smith", LocalDate.of(1980, Month.JANUARY, 12));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersonService personService(){
|
||||
return new PersonService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MyPerformanceMonitorInterceptor myPerformanceMonitorInterceptor() {
|
||||
return new MyPerformanceMonitorInterceptor(true);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Advisor myPerformanceMonitorAdvisor() {
|
||||
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
|
||||
pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.myMonitor()");
|
||||
return new DefaultPointcutAdvisor(pointcut, myPerformanceMonitorInterceptor());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.performancemonitor;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.springframework.aop.interceptor.AbstractMonitoringInterceptor;
|
||||
|
||||
public class MyPerformanceMonitorInterceptor extends AbstractMonitoringInterceptor {
|
||||
|
||||
public MyPerformanceMonitorInterceptor() {
|
||||
}
|
||||
|
||||
public MyPerformanceMonitorInterceptor(boolean useDynamicLogger) {
|
||||
setUseDynamicLogger(useDynamicLogger);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object invokeUnderTrace(MethodInvocation invocation, Log log) throws Throwable {
|
||||
|
||||
String name = createInvocationTraceName(invocation);
|
||||
long start = System.currentTimeMillis();
|
||||
log.info("Method "+name+" execution started at:"+new Date());
|
||||
try {
|
||||
return invocation.proceed();
|
||||
}
|
||||
finally {
|
||||
long end = System.currentTimeMillis();
|
||||
long time = end - start;
|
||||
log.info("Method "+name+" execution lasted:"+time+" ms");
|
||||
log.info("Method "+name+" execution ended at:"+new Date());
|
||||
|
||||
if (time > 10){
|
||||
log.warn("Method execution longer than 10 ms!");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.performancemonitor;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
|
||||
public class PerfomanceApp {
|
||||
public static void main(String[] args) {
|
||||
|
||||
ApplicationContext context = new AnnotationConfigApplicationContext(AopConfiguration.class);
|
||||
Person person = (Person) context.getBean("person");
|
||||
PersonService personService = (PersonService) context.getBean("personService");
|
||||
|
||||
System.out.println("Name is:"+personService.getFullName(person));
|
||||
System.out.println("Age is:"+personService.getAge(person));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.performancemonitor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class Person {
|
||||
private String lastName;
|
||||
private String firstName;
|
||||
private LocalDate dateOfBirth;
|
||||
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public Person(String firstName, String lastName, LocalDate dateOfBirth) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
|
||||
public LocalDate getDateOfBirth() {
|
||||
return dateOfBirth;
|
||||
}
|
||||
|
||||
public void setDateOfBirth(LocalDate dateOfBirth) {
|
||||
this.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.performancemonitor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
|
||||
public class PersonService {
|
||||
|
||||
public String getFullName(Person person){
|
||||
return person.getLastName()+" "+person.getFirstName();
|
||||
}
|
||||
|
||||
public int getAge(Person person){
|
||||
Period p = Period.between(person.getDateOfBirth(), LocalDate.now());
|
||||
return p.getYears();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
log4j.rootLogger=TRACE, stdout
|
||||
|
||||
# Redirect log messages to console
|
||||
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.stdout.Target=System.out
|
||||
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
|
||||
|
||||
log4j.logger.org.springframework.aop.interceptor.PerformanceMonitorInterceptor=TRACE, stdout
|
||||
log4j.logger.com.baeldung.performancemonitor.MyPerformanceMonitorInterceptor=INFO, stdout
|
|
@ -54,8 +54,8 @@
|
|||
<assertj-guava.version>3.1.0</assertj-guava.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<assertj-core.version>3.6.1</assertj-core.version>
|
||||
|
||||
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
||||
</project>
|
|
@ -38,8 +38,7 @@ public class AssertJCoreTest {
|
|||
public void whenCheckingForElement_thenContains() throws Exception {
|
||||
List<String> list = Arrays.asList("1", "2", "3");
|
||||
|
||||
assertThat(list)
|
||||
.contains("1");
|
||||
assertThat(list).contains("1");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -50,12 +49,7 @@ public class AssertJCoreTest {
|
|||
assertThat(list).startsWith("1");
|
||||
assertThat(list).doesNotContainNull();
|
||||
|
||||
assertThat(list)
|
||||
.isNotEmpty()
|
||||
.contains("1")
|
||||
.startsWith("1")
|
||||
.doesNotContainNull()
|
||||
.containsSequence("2", "3");
|
||||
assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -67,11 +61,7 @@ public class AssertJCoreTest {
|
|||
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
|
||||
char someCharacter = 'c';
|
||||
|
||||
assertThat(someCharacter)
|
||||
.isNotEqualTo('a')
|
||||
.inUnicode()
|
||||
.isGreaterThanOrEqualTo('b')
|
||||
.isLowerCase();
|
||||
assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -94,11 +84,7 @@ public class AssertJCoreTest {
|
|||
final File someFile = File.createTempFile("aaa", "bbb");
|
||||
someFile.deleteOnExit();
|
||||
|
||||
assertThat(someFile)
|
||||
.exists()
|
||||
.isFile()
|
||||
.canRead()
|
||||
.canWrite();
|
||||
assertThat(someFile).exists().isFile().canRead().canWrite();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -113,20 +99,14 @@ public class AssertJCoreTest {
|
|||
public void whenGivenMap_then() throws Exception {
|
||||
Map<Integer, String> map = Maps.newHashMap(2, "a");
|
||||
|
||||
assertThat(map)
|
||||
.isNotEmpty()
|
||||
.containsKey(2)
|
||||
.doesNotContainKeys(10)
|
||||
.contains(entry(2, "a"));
|
||||
assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGivenException_then() throws Exception {
|
||||
Exception ex = new Exception("abc");
|
||||
|
||||
assertThat(ex)
|
||||
.hasNoCause()
|
||||
.hasMessageEndingWith("c");
|
||||
assertThat(ex).hasNoCause().hasMessageEndingWith("c");
|
||||
}
|
||||
|
||||
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
|
||||
|
@ -134,8 +114,6 @@ public class AssertJCoreTest {
|
|||
public void whenRunningAssertion_thenDescribed() throws Exception {
|
||||
Person person = new Person("Alex", 34);
|
||||
|
||||
assertThat(person.getAge())
|
||||
.as("%s's age should be equal to 100")
|
||||
.isEqualTo(100);
|
||||
assertThat(person.getAge()).as("%s's age should be equal to 100").isEqualTo(100);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -26,9 +26,7 @@ public class AssertJGuavaTest {
|
|||
final File temp1 = File.createTempFile("bael", "dung1");
|
||||
final File temp2 = File.createTempFile("bael", "dung2");
|
||||
|
||||
assertThat(Files.asByteSource(temp1))
|
||||
.hasSize(0)
|
||||
.hasSameContentAs(Files.asByteSource(temp2));
|
||||
assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -37,11 +35,7 @@ public class AssertJGuavaTest {
|
|||
mmap.put(1, "one");
|
||||
mmap.put(1, "1");
|
||||
|
||||
assertThat(mmap)
|
||||
.hasSize(2)
|
||||
.containsKeys(1)
|
||||
.contains(entry(1, "one"))
|
||||
.contains(entry(1, "1"));
|
||||
assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -62,31 +56,21 @@ public class AssertJGuavaTest {
|
|||
mmap2.put(1, "one");
|
||||
mmap2.put(1, "1");
|
||||
|
||||
assertThat(mmap1)
|
||||
.containsAllEntriesOf(mmap2)
|
||||
.containsAllEntriesOf(mmap1_clone)
|
||||
.hasSameEntriesAs(mmap1_clone);
|
||||
assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
||||
final Optional<String> something = Optional.of("something");
|
||||
|
||||
assertThat(something)
|
||||
.isPresent()
|
||||
.extractingValue()
|
||||
.isEqualTo("something");
|
||||
assertThat(something).isPresent().extractingValue().isEqualTo("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final Range<String> range = Range.openClosed("a", "g");
|
||||
|
||||
assertThat(range)
|
||||
.hasOpenedLowerBound()
|
||||
.isNotEmpty()
|
||||
.hasClosedUpperBound()
|
||||
.contains("b");
|
||||
assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -96,10 +80,7 @@ public class AssertJGuavaTest {
|
|||
map.put(Range.closed(0, 60), "F");
|
||||
map.put(Range.closed(61, 70), "D");
|
||||
|
||||
assertThat(map)
|
||||
.isNotEmpty()
|
||||
.containsKeys(0)
|
||||
.contains(MapEntry.entry(34, "F"));
|
||||
assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -109,13 +90,7 @@ public class AssertJGuavaTest {
|
|||
table.put(1, "A", "PRESENT");
|
||||
table.put(1, "B", "ABSENT");
|
||||
|
||||
assertThat(table)
|
||||
.hasRowCount(1)
|
||||
.containsValues("ABSENT")
|
||||
.containsCell(1, "B", "ABSENT");
|
||||
assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -20,20 +20,14 @@ public class AssertJJava8Test {
|
|||
public void givenOptional_shouldAssert() throws Exception {
|
||||
final Optional<String> givenOptional = Optional.of("something");
|
||||
|
||||
assertThat(givenOptional)
|
||||
.isPresent()
|
||||
.hasValue("something");
|
||||
assertThat(givenOptional).isPresent().hasValue("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPredicate_shouldAssert() throws Exception {
|
||||
final Predicate<String> predicate = s -> s.length() > 4;
|
||||
|
||||
assertThat(predicate)
|
||||
.accepts("aaaaa", "bbbbb")
|
||||
.rejects("a", "b")
|
||||
.acceptsAll(asList("aaaaa", "bbbbb"))
|
||||
.rejectsAll(asList("a", "b"));
|
||||
assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -41,92 +35,74 @@ public class AssertJJava8Test {
|
|||
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
||||
final LocalDate todayDate = LocalDate.now();
|
||||
|
||||
assertThat(givenLocalDate)
|
||||
.isBefore(LocalDate.of(2020, 7, 8))
|
||||
.isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||
assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||
|
||||
assertThat(todayDate)
|
||||
.isAfter(LocalDate.of(1989, 7, 8))
|
||||
.isToday();
|
||||
assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_shouldAssert() throws Exception {
|
||||
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
||||
|
||||
assertThat(givenLocalDate)
|
||||
.isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||
assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalTime_shouldAssert() throws Exception {
|
||||
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
||||
|
||||
assertThat(givenLocalTime)
|
||||
.isAfter(LocalTime.of(1, 0))
|
||||
.hasSameHourAs(LocalTime.of(12, 0));
|
||||
assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::getYear)
|
||||
.contains(2015);
|
||||
assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::isLeapYear)
|
||||
.contains(true);
|
||||
assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(Object::getClass)
|
||||
.contains(LocalDate.class);
|
||||
assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
|
||||
.contains(2015, 6);
|
||||
assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldSatisfy() throws Exception {
|
||||
final String givenString = "someString";
|
||||
|
||||
assertThat(givenString)
|
||||
.satisfies(s -> {
|
||||
assertThat(s).isNotEmpty();
|
||||
assertThat(s).hasSize(10);
|
||||
});
|
||||
assertThat(givenString).satisfies(s -> {
|
||||
assertThat(s).isNotEmpty();
|
||||
assertThat(s).hasSize(10);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldMatch() throws Exception {
|
||||
final String emptyString = "";
|
||||
|
||||
assertThat(emptyString)
|
||||
.matches(String::isEmpty);
|
||||
assertThat(emptyString).matches(String::isEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
||||
final List<String> givenList = Arrays.asList("");
|
||||
|
||||
assertThat(givenList)
|
||||
.hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||
assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -41,5 +41,5 @@
|
|||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
||||
</project>
|
||||
|
|
|
@ -4,12 +4,12 @@ import com.google.auto.value.AutoValue;
|
|||
|
||||
@AutoValue
|
||||
public abstract class AutoValueMoney {
|
||||
public abstract String getCurrency();
|
||||
public abstract String getCurrency();
|
||||
|
||||
public abstract long getAmount();
|
||||
public abstract long getAmount();
|
||||
|
||||
public static AutoValueMoney create(String currency, long amount) {
|
||||
return new AutoValue_AutoValueMoney(currency, amount);
|
||||
public static AutoValueMoney create(String currency, long amount) {
|
||||
return new AutoValue_AutoValueMoney(currency, amount);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,20 +4,20 @@ import com.google.auto.value.AutoValue;
|
|||
|
||||
@AutoValue
|
||||
public abstract class AutoValueMoneyWithBuilder {
|
||||
public abstract String getCurrency();
|
||||
public abstract String getCurrency();
|
||||
|
||||
public abstract long getAmount();
|
||||
public abstract long getAmount();
|
||||
|
||||
static Builder builder() {
|
||||
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
||||
}
|
||||
static Builder builder() {
|
||||
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
||||
}
|
||||
|
||||
@AutoValue.Builder
|
||||
abstract static class Builder {
|
||||
abstract Builder setCurrency(String currency);
|
||||
@AutoValue.Builder
|
||||
abstract static class Builder {
|
||||
abstract Builder setCurrency(String currency);
|
||||
|
||||
abstract Builder setAmount(long amount);
|
||||
abstract Builder setAmount(long amount);
|
||||
|
||||
abstract AutoValueMoneyWithBuilder build();
|
||||
}
|
||||
abstract AutoValueMoneyWithBuilder build();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,49 +3,49 @@ package com.baeldung.autovalue;
|
|||
import java.util.Objects;
|
||||
|
||||
public final class Foo {
|
||||
private final String text;
|
||||
private final int number;
|
||||
private final String text;
|
||||
private final int number;
|
||||
|
||||
public Foo(String text, int number) {
|
||||
this.text = text;
|
||||
this.number = number;
|
||||
}
|
||||
public Foo(String text, int number) {
|
||||
this.text = text;
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(text, number);
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(text, number);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo [text=" + text + ", number=" + number + "]";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo [text=" + text + ", number=" + number + "]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Foo other = (Foo) obj;
|
||||
if (number != other.number)
|
||||
return false;
|
||||
if (text == null) {
|
||||
if (other.text != null)
|
||||
return false;
|
||||
} else if (!text.equals(other.text))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Foo other = (Foo) obj;
|
||||
if (number != other.number)
|
||||
return false;
|
||||
if (text == null) {
|
||||
if (other.text != null)
|
||||
return false;
|
||||
} else if (!text.equals(other.text))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,52 +1,53 @@
|
|||
package com.baeldung.autovalue;
|
||||
|
||||
public final class ImmutableMoney {
|
||||
private final long amount;
|
||||
private final String currency;
|
||||
public ImmutableMoney(long amount, String currency) {
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + (int) (amount ^ (amount >>> 32));
|
||||
result = prime * result
|
||||
+ ((currency == null) ? 0 : currency.hashCode());
|
||||
return result;
|
||||
}
|
||||
private final long amount;
|
||||
private final String currency;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
ImmutableMoney other = (ImmutableMoney) obj;
|
||||
if (amount != other.amount)
|
||||
return false;
|
||||
if (currency == null) {
|
||||
if (other.currency != null)
|
||||
return false;
|
||||
} else if (!currency.equals(other.currency))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
public ImmutableMoney(long amount, String currency) {
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + (int) (amount ^ (amount >>> 32));
|
||||
result = prime * result + ((currency == null) ? 0 : currency.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
ImmutableMoney other = (ImmutableMoney) obj;
|
||||
if (amount != other.amount)
|
||||
return false;
|
||||
if (currency == null) {
|
||||
if (other.currency != null)
|
||||
return false;
|
||||
} else if (!currency.equals(other.currency))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ImmutableMoney [amount=" + amount + ", currency=" + currency
|
||||
+ "]";
|
||||
}
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,35 +1,34 @@
|
|||
package com.baeldung.autovalue;
|
||||
|
||||
public class MutableMoney {
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MutableMoney [amount=" + amount + ", currency=" + currency
|
||||
+ "]";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||
}
|
||||
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(long amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
public void setAmount(long amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
private long amount;
|
||||
private String currency;
|
||||
private long amount;
|
||||
private String currency;
|
||||
|
||||
public MutableMoney(long amount, String currency) {
|
||||
super();
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
public MutableMoney(long amount, String currency) {
|
||||
super();
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -5,55 +5,59 @@ import static org.junit.Assert.*;
|
|||
import org.junit.Test;
|
||||
|
||||
public class MoneyUnitTest {
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
||||
MutableMoney m2 = new MutableMoney(10000, "USD");
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
||||
MutableMoney m2 = new MutableMoney(10000, "USD");
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
||||
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
||||
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
||||
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
||||
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
||||
assertEquals(m.getAmount(), 10000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
@Test
|
||||
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
||||
assertEquals(m.getAmount(), 10000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertEquals(m.getAmount(), 5000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
@Test
|
||||
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertEquals(m.getAmount(), 5000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
/target/
|
|
@ -2,10 +2,10 @@
|
|||
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>aws-lambda</artifactId>
|
||||
<artifactId>aws</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>aws-lambda</name>
|
||||
<name>aws</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.lambda;
|
||||
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.lambda;
|
||||
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
import com.amazonaws.services.lambda.runtime.RequestHandler;
|
|
@ -1,7 +1,6 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.lambda;
|
||||
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
import com.amazonaws.services.lambda.runtime.RequestHandler;
|
||||
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
|
@ -45,7 +45,7 @@
|
|||
|
||||
</dependencies>
|
||||
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -61,7 +61,7 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
|
@ -101,7 +101,7 @@
|
|||
<aspectjweaver.version>1.8.9</aspectjweaver.version>
|
||||
<weld-se-core.version>2.4.1.Final</weld-se-core.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,91 +1,90 @@
|
|||
<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>core-java9</artifactId>
|
||||
<version>0.2-SNAPSHOT</version>
|
||||
<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>core-java9</artifactId>
|
||||
<version>0.2-SNAPSHOT</version>
|
||||
|
||||
<name>core-java9</name>
|
||||
<name>core-java9</name>
|
||||
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>apache.snapshots</id>
|
||||
<url>http://repository.apache.org/snapshots/</url>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>apache.snapshots</id>
|
||||
<url>http://repository.apache.org/snapshots/</url>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<build>
|
||||
<finalName>core-java-9</finalName>
|
||||
|
||||
</dependencies>
|
||||
<plugins>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-9</finalName>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.9</source>
|
||||
<target>1.9</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.9</source>
|
||||
<target>1.9</target>
|
||||
<verbose>true</verbose>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
</build>
|
||||
|
||||
</plugins>
|
||||
<properties>
|
||||
<!-- project build encoding -->
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
|
||||
</build>
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
|
||||
<properties>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
</properties>
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,16 +1,16 @@
|
|||
package com.baeldung.java9.language;
|
||||
|
||||
public interface PrivateInterface {
|
||||
|
||||
|
||||
private static String staticPrivate() {
|
||||
return "static private";
|
||||
}
|
||||
|
||||
|
||||
private String instancePrivate() {
|
||||
return "instance private";
|
||||
}
|
||||
|
||||
public default void check(){
|
||||
|
||||
public default void check() {
|
||||
String result = staticPrivate();
|
||||
if (!result.equals("static private"))
|
||||
throw new AssertionError("Incorrect result for static private interface method");
|
||||
|
|
|
@ -8,37 +8,36 @@ import java.time.Duration;
|
|||
import java.time.Instant;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
|
||||
public class ProcessUtils {
|
||||
|
||||
public static String getClassPath(){
|
||||
public static String getClassPath() {
|
||||
String cp = System.getProperty("java.class.path");
|
||||
System.out.println("ClassPath is "+cp);
|
||||
System.out.println("ClassPath is " + cp);
|
||||
return cp;
|
||||
}
|
||||
|
||||
public static File getJavaCmd() throws IOException{
|
||||
public static File getJavaCmd() throws IOException {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
File javaCmd;
|
||||
if(System.getProperty("os.name").startsWith("Win")){
|
||||
if (System.getProperty("os.name").startsWith("Win")) {
|
||||
javaCmd = new File(javaHome, "bin/java.exe");
|
||||
}else{
|
||||
} else {
|
||||
javaCmd = new File(javaHome, "bin/java");
|
||||
}
|
||||
if(javaCmd.canExecute()){
|
||||
if (javaCmd.canExecute()) {
|
||||
return javaCmd;
|
||||
}else{
|
||||
} else {
|
||||
throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable");
|
||||
}
|
||||
}
|
||||
|
||||
public static String getMainClass(){
|
||||
public static String getMainClass() {
|
||||
return System.getProperty("sun.java.command");
|
||||
}
|
||||
|
||||
public static String getSystemProperties(){
|
||||
StringBuilder sb = new StringBuilder();
|
||||
System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) );
|
||||
public static String getSystemProperties() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
System.getProperties().forEach((s1, s2) -> sb.append(s1 + " - " + s2));
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,7 +8,6 @@ public class ServiceMain {
|
|||
ProcessHandle thisProcess = ProcessHandle.current();
|
||||
long pid = thisProcess.getPid();
|
||||
|
||||
|
||||
Optional<String[]> opArgs = Optional.ofNullable(args);
|
||||
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() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.filter(Optional::isPresent)
|
||||
.map(Optional::get)
|
||||
.collect(Collectors.toList());
|
||||
List<String> filteredList = listOfOptionals.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
|
||||
|
||||
assertEquals(2, filteredList.size());
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
|
@ -33,9 +30,7 @@ public class Java9OptionalsStreamTest {
|
|||
public void filterOutPresentOptionalsWithFlatMap() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
|
||||
.collect(Collectors.toList());
|
||||
List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList());
|
||||
assertEquals(2, filteredList.size());
|
||||
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
|
@ -46,9 +41,7 @@ public class Java9OptionalsStreamTest {
|
|||
public void filterOutPresentOptionalsWithFlatMap2() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
|
||||
.collect(Collectors.toList());
|
||||
List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList());
|
||||
assertEquals(2, filteredList.size());
|
||||
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
|
@ -59,9 +52,7 @@ public class Java9OptionalsStreamTest {
|
|||
public void filterOutPresentOptionalsWithJava9() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.flatMap(Optional::stream)
|
||||
.collect(Collectors.toList());
|
||||
List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
|
||||
|
||||
assertEquals(2, filteredList.size());
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
package com.baeldung.java9;
|
||||
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertSame;
|
||||
|
||||
|
@ -13,7 +13,6 @@ import org.junit.Test;
|
|||
|
||||
public class MultiResultionImageTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void baseMultiResImageTest() {
|
||||
int baseIndex = 1;
|
||||
|
@ -38,10 +37,8 @@ public class MultiResultionImageTest {
|
|||
return 8 * (i + 1);
|
||||
}
|
||||
|
||||
|
||||
private static BufferedImage createImage(int i) {
|
||||
return new BufferedImage(getSize(i), getSize(i),
|
||||
BufferedImage.TYPE_INT_RGB);
|
||||
return new BufferedImage(getSize(i), getSize(i), BufferedImage.TYPE_INT_RGB);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,6 +1,4 @@
|
|||
package com.baeldung.java9.httpclient;
|
||||
|
||||
|
||||
package com.baeldung.java9.httpclient;
|
||||
|
||||
import static java.net.HttpURLConnection.HTTP_OK;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
@ -28,8 +26,8 @@ import org.junit.Test;
|
|||
|
||||
public class SimpleHttpRequestsTest {
|
||||
|
||||
private URI httpURI;
|
||||
|
||||
private URI httpURI;
|
||||
|
||||
@Before
|
||||
public void init() throws URISyntaxException {
|
||||
httpURI = new URI("http://www.baeldung.com/");
|
||||
|
@ -37,26 +35,26 @@ public class SimpleHttpRequestsTest {
|
|||
|
||||
@Test
|
||||
public void quickGet() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.create( httpURI ).GET();
|
||||
HttpRequest request = HttpRequest.create(httpURI).GET();
|
||||
HttpResponse response = request.response();
|
||||
int responseStatusCode = response.statusCode();
|
||||
String responseBody = response.body(HttpResponse.asString());
|
||||
assertTrue("Get response status code is bigger then 400", responseStatusCode < 400);
|
||||
assertTrue("Get response status code is bigger then 400", responseStatusCode < 400);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{
|
||||
public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.create(httpURI).GET();
|
||||
long before = System.currentTimeMillis();
|
||||
CompletableFuture<HttpResponse> futureResponse = request.responseAsync();
|
||||
futureResponse.thenAccept( response -> {
|
||||
futureResponse.thenAccept(response -> {
|
||||
String responseBody = response.body(HttpResponse.asString());
|
||||
});
|
||||
});
|
||||
HttpResponse resp = futureResponse.get();
|
||||
HttpHeaders hs = resp.headers();
|
||||
assertTrue("There should be more then 1 header.", hs.map().size() >1);
|
||||
assertTrue("There should be more then 1 header.", hs.map().size() > 1);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void postMehtod() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI);
|
||||
|
@ -66,61 +64,63 @@ public class SimpleHttpRequestsTest {
|
|||
int statusCode = response.statusCode();
|
||||
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{
|
||||
public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException {
|
||||
CookieManager cManager = new CookieManager();
|
||||
cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
|
||||
|
||||
SSLParameters sslParam = new SSLParameters (new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" });
|
||||
|
||||
|
||||
SSLParameters sslParam = new SSLParameters(new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" });
|
||||
|
||||
HttpClient.Builder hcBuilder = HttpClient.create();
|
||||
hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam);
|
||||
HttpClient httpClient = hcBuilder.build();
|
||||
HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com"));
|
||||
|
||||
|
||||
HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET();
|
||||
HttpResponse response = request.response();
|
||||
int statusCode = response.statusCode();
|
||||
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
||||
}
|
||||
|
||||
SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{
|
||||
|
||||
SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException {
|
||||
SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters();
|
||||
String [] proto = sslP1.getApplicationProtocols();
|
||||
String [] cifers = sslP1.getCipherSuites();
|
||||
String[] proto = sslP1.getApplicationProtocols();
|
||||
String[] cifers = sslP1.getCipherSuites();
|
||||
System.out.println(printStringArr(proto));
|
||||
System.out.println(printStringArr(cifers));
|
||||
return sslP1;
|
||||
}
|
||||
|
||||
String printStringArr(String ... args ){
|
||||
if(args == null){
|
||||
|
||||
String printStringArr(String... args) {
|
||||
if (args == null) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String s : args){
|
||||
for (String s : args) {
|
||||
sb.append(s);
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String printHeaders(HttpHeaders h){
|
||||
if(h == null){
|
||||
|
||||
String printHeaders(HttpHeaders h) {
|
||||
if (h == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Map<String, List<String>> hMap = h.map();
|
||||
for(String k : hMap.keySet()){
|
||||
sb.append(k).append(":");
|
||||
List<String> l = hMap.get(k);
|
||||
if( l != null ){
|
||||
l.forEach( s -> { sb.append(s).append(","); } );
|
||||
}
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Map<String, List<String>> hMap = h.map();
|
||||
for (String k : hMap.keySet()) {
|
||||
sb.append(k).append(":");
|
||||
List<String> l = hMap.get(k);
|
||||
if (l != null) {
|
||||
l.forEach(s -> {
|
||||
sb.append(s).append(",");
|
||||
});
|
||||
}
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,7 +7,7 @@ public class TryWithResourcesTest {
|
|||
|
||||
static int closeCount = 0;
|
||||
|
||||
static class MyAutoCloseable implements AutoCloseable{
|
||||
static class MyAutoCloseable implements AutoCloseable {
|
||||
final FinalWrapper finalWrapper = new FinalWrapper();
|
||||
|
||||
public void close() {
|
||||
|
@ -57,7 +57,6 @@ public class TryWithResourcesTest {
|
|||
assertEquals("Expected and Actual does not match", 5, closeCount);
|
||||
}
|
||||
|
||||
|
||||
static class CloseableException extends Exception implements AutoCloseable {
|
||||
@Override
|
||||
public void close() {
|
||||
|
@ -66,5 +65,3 @@ public class TryWithResourcesTest {
|
|||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.java9.language.collections;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class ListFactoryMethodsTest {
|
||||
|
||||
@Test
|
||||
public void whenListCreated_thenSuccess() {
|
||||
List<String> traditionlList = new ArrayList<String>();
|
||||
traditionlList.add("foo");
|
||||
traditionlList.add("bar");
|
||||
traditionlList.add("baz");
|
||||
List<String> factoryCreatedList = List.of("foo", "bar", "baz");
|
||||
assertEquals(traditionlList, factoryCreatedList);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
|
||||
List<String> list = List.of("foo", "bar");
|
||||
list.add("baz");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void onElemModify_ifUnSupportedOpExpnThrown_thenSuccess() {
|
||||
List<String> list = List.of("foo", "bar");
|
||||
list.set(0, "baz");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
|
||||
List<String> list = List.of("foo", "bar");
|
||||
list.remove("foo");
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void onNullElem_ifNullPtrExpnThrown_thenSuccess() {
|
||||
List.of("foo", "bar", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifNotArrayList_thenSuccess() {
|
||||
List<String> list = List.of("foo", "bar");
|
||||
assertFalse(list instanceof ArrayList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifListSizeIsOne_thenSuccess() {
|
||||
int[] arr = { 1, 2, 3, 4 };
|
||||
List<int[]> list = List.of(arr);
|
||||
assertEquals(1, list.size());
|
||||
assertArrayEquals(arr, list.get(0));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
package com.baeldung.java9.language.collections;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class MapFactoryMethodsTest {
|
||||
|
||||
@Test
|
||||
public void whenMapCreated_thenSuccess() {
|
||||
Map<String, String> traditionlMap = new HashMap<String, String>();
|
||||
traditionlMap.put("foo", "a");
|
||||
traditionlMap.put("bar", "b");
|
||||
traditionlMap.put("baz", "c");
|
||||
Map<String, String> factoryCreatedMap = Map.of("foo", "a", "bar", "b", "baz", "c");
|
||||
assertEquals(traditionlMap, factoryCreatedMap);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
|
||||
Map<String, String> map = Map.of("foo", "a", "bar", "b");
|
||||
map.put("baz", "c");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void onElemModify_ifUnSupportedOpExpnThrown_thenSuccess() {
|
||||
Map<String, String> map = Map.of("foo", "a", "bar", "b");
|
||||
map.put("foo", "c");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
|
||||
Map<String, String> map = Map.of("foo", "a", "bar", "b");
|
||||
map.remove("foo");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenDuplicateKeys_ifIllegalArgExp_thenSuccess() {
|
||||
Map.of("foo", "a", "foo", "b");
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void onNullKey_ifNullPtrExp_thenSuccess() {
|
||||
Map.of("foo", "a", null, "b");
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void onNullValue_ifNullPtrExp_thenSuccess() {
|
||||
Map.of("foo", "a", "bar", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifNotHashMap_thenSuccess() {
|
||||
Map<String, String> map = Map.of("foo", "a", "bar", "b");
|
||||
assertFalse(map instanceof HashMap);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.java9.language.collections;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class SetFactoryMethodsTest {
|
||||
|
||||
@Test
|
||||
public void whenSetCreated_thenSuccess() {
|
||||
Set<String> traditionlSet = new HashSet<String>();
|
||||
traditionlSet.add("foo");
|
||||
traditionlSet.add("bar");
|
||||
traditionlSet.add("baz");
|
||||
Set<String> factoryCreatedSet = Set.of("foo", "bar", "baz");
|
||||
assertEquals(traditionlSet, factoryCreatedSet);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void onDuplicateElem_IfIllegalArgExp_thenSuccess() {
|
||||
Set.of("foo", "bar", "baz", "foo");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
|
||||
Set<String> set = Set.of("foo", "bar");
|
||||
set.add("baz");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
|
||||
Set<String> set = Set.of("foo", "bar", "baz");
|
||||
set.remove("foo");
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void onNullElem_ifNullPtrExpnThrown_thenSuccess() {
|
||||
Set.of("foo", "bar", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifNotHashSet_thenSuccess() {
|
||||
Set<String> list = Set.of("foo", "bar");
|
||||
assertFalse(list instanceof HashSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifSetSizeIsOne_thenSuccess() {
|
||||
int[] arr = { 1, 2, 3, 4 };
|
||||
Set<int[]> set = Set.of(arr);
|
||||
assertEquals(1, set.size());
|
||||
assertArrayEquals(arr, set.iterator().next());
|
||||
}
|
||||
|
||||
}
|
|
@ -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 Stream<String> getStreamAfterTakeWhileOperation() {
|
||||
return Stream
|
||||
.iterate("", s -> s + "s")
|
||||
.takeWhile(s -> s.length() < 10);
|
||||
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10);
|
||||
}
|
||||
|
||||
public Stream<String> getStreamAfterDropWhileOperation() {
|
||||
return Stream
|
||||
.iterate("", s -> s + "s")
|
||||
.takeWhile(s -> s.length() < 10)
|
||||
.dropWhile(s -> !s.contains("sssss"));
|
||||
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10).dropWhile(s -> !s.contains("sssss"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -72,25 +67,25 @@ public class StreamFeaturesTest {
|
|||
|
||||
}
|
||||
|
||||
public static class OfNullableTest {
|
||||
public static class OfNullableTest {
|
||||
|
||||
private List<String> collection = Arrays.asList("A", "B", "C");
|
||||
private Map<String, Integer> map = new HashMap<>() {{
|
||||
put("A", 10);
|
||||
put("C", 30);
|
||||
}};
|
||||
private Map<String, Integer> map = new HashMap<>() {
|
||||
{
|
||||
put("A", 10);
|
||||
put("C", 30);
|
||||
}
|
||||
};
|
||||
|
||||
private Stream<Integer> getStreamWithOfNullable() {
|
||||
return collection.stream()
|
||||
.flatMap(s -> Stream.ofNullable(map.get(s)));
|
||||
return collection.stream().flatMap(s -> Stream.ofNullable(map.get(s)));
|
||||
}
|
||||
|
||||
private Stream<Integer> getStream() {
|
||||
return collection.stream()
|
||||
.flatMap(s -> {
|
||||
Integer temp = map.get(s);
|
||||
return temp != null ? Stream.of(temp) : Stream.empty();
|
||||
});
|
||||
return collection.stream().flatMap(s -> {
|
||||
Integer temp = map.get(s);
|
||||
return temp != null ? Stream.of(temp) : Stream.empty();
|
||||
});
|
||||
}
|
||||
|
||||
private List<Integer> testOfNullableFrom(Stream<Integer> stream) {
|
||||
|
@ -107,10 +102,7 @@ public class StreamFeaturesTest {
|
|||
@Test
|
||||
public void testOfNullable() {
|
||||
|
||||
assertEquals(
|
||||
testOfNullableFrom(getStream()),
|
||||
testOfNullableFrom(getStreamWithOfNullable())
|
||||
);
|
||||
assertEquals(testOfNullableFrom(getStream()), testOfNullableFrom(getStreamWithOfNullable()));
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -22,90 +22,89 @@ import static org.junit.Assert.assertTrue;
|
|||
|
||||
public class ProcessApi {
|
||||
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void processInfoExample()throws NoSuchAlgorithmException{
|
||||
public void processInfoExample() throws NoSuchAlgorithmException {
|
||||
ProcessHandle self = ProcessHandle.current();
|
||||
long PID = self.getPid();
|
||||
ProcessHandle.Info procInfo = self.info();
|
||||
Optional<String[]> args = procInfo.arguments();
|
||||
Optional<String> cmd = procInfo.commandLine();
|
||||
Optional<String> cmd = procInfo.commandLine();
|
||||
Optional<Instant> startTime = procInfo.startInstant();
|
||||
Optional<Duration> cpuUsage = procInfo.totalCpuDuration();
|
||||
|
||||
waistCPU();
|
||||
System.out.println("Args "+ args);
|
||||
System.out.println("Command " +cmd.orElse("EmptyCmd"));
|
||||
System.out.println("Start time: "+ startTime.get().toString());
|
||||
System.out.println("Args " + args);
|
||||
System.out.println("Command " + cmd.orElse("EmptyCmd"));
|
||||
System.out.println("Start time: " + startTime.get().toString());
|
||||
System.out.println(cpuUsage.get().toMillis());
|
||||
|
||||
|
||||
Stream<ProcessHandle> allProc = ProcessHandle.current().children();
|
||||
allProc.forEach(p -> {
|
||||
System.out.println("Proc "+ p.getPid());
|
||||
System.out.println("Proc " + p.getPid());
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createAndDestroyProcess() throws IOException, InterruptedException{
|
||||
public void createAndDestroyProcess() throws IOException, InterruptedException {
|
||||
int numberOfChildProcesses = 5;
|
||||
for(int i=0; i < numberOfChildProcesses; i++){
|
||||
for (int i = 0; i < numberOfChildProcesses; i++) {
|
||||
createNewJVM(ServiceMain.class, i).getPid();
|
||||
}
|
||||
|
||||
Stream<ProcessHandle> childProc = ProcessHandle.current().children();
|
||||
assertEquals( childProc.count(), numberOfChildProcesses);
|
||||
|
||||
|
||||
Stream<ProcessHandle> childProc = ProcessHandle.current().children();
|
||||
assertEquals(childProc.count(), numberOfChildProcesses);
|
||||
|
||||
childProc = ProcessHandle.current().children();
|
||||
childProc.forEach(processHandle -> {
|
||||
assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive());
|
||||
assertTrue("Process " + processHandle.getPid() + " should be alive!", processHandle.isAlive());
|
||||
CompletableFuture<ProcessHandle> onProcExit = processHandle.onExit();
|
||||
onProcExit.thenAccept(procHandle -> {
|
||||
System.out.println("Process with PID "+ procHandle.getPid() + " has stopped");
|
||||
System.out.println("Process with PID " + procHandle.getPid() + " has stopped");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Thread.sleep(10000);
|
||||
|
||||
|
||||
childProc = ProcessHandle.current().children();
|
||||
childProc.forEach(procHandle -> {
|
||||
assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy());
|
||||
assertTrue("Could not kill process " + procHandle.getPid(), procHandle.destroy());
|
||||
});
|
||||
|
||||
|
||||
Thread.sleep(5000);
|
||||
|
||||
|
||||
childProc = ProcessHandle.current().children();
|
||||
childProc.forEach(procHandle -> {
|
||||
assertFalse("Process "+ procHandle.getPid() +" should not be alive!", procHandle.isAlive());
|
||||
assertFalse("Process " + procHandle.getPid() + " should not be alive!", procHandle.isAlive());
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
private Process createNewJVM(Class mainClass, int number) throws IOException{
|
||||
private Process createNewJVM(Class mainClass, int number) throws IOException {
|
||||
ArrayList<String> cmdParams = new ArrayList<String>(5);
|
||||
cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath());
|
||||
cmdParams.add("-cp");
|
||||
cmdParams.add(ProcessUtils.getClassPath());
|
||||
cmdParams.add(mainClass.getName());
|
||||
cmdParams.add("Service "+ number);
|
||||
cmdParams.add("Service " + number);
|
||||
ProcessBuilder myService = new ProcessBuilder(cmdParams);
|
||||
myService.inheritIO();
|
||||
return myService.start();
|
||||
}
|
||||
|
||||
private void waistCPU() throws NoSuchAlgorithmException{
|
||||
|
||||
private void waistCPU() throws NoSuchAlgorithmException {
|
||||
ArrayList<Integer> randArr = new ArrayList<Integer>(4096);
|
||||
SecureRandom sr = SecureRandom.getInstanceStrong();
|
||||
Duration somecpu = Duration.ofMillis(4200L);
|
||||
Instant end = Instant.now().plus(somecpu);
|
||||
while (Instant.now().isBefore(end)) {
|
||||
//System.out.println(sr.nextInt());
|
||||
randArr.add( sr.nextInt() );
|
||||
// System.out.println(sr.nextInt());
|
||||
randArr.add(sr.nextInt());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -16,3 +16,7 @@
|
|||
*.txt
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea
|
||||
*.iml
|
|
@ -46,3 +46,14 @@
|
|||
- [Grep in Java](http://www.baeldung.com/grep-in-java)
|
||||
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
|
||||
- [Simulated Annealing for Travelling Salesman Problem](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
- [Slope One Algorithm: Collaborative Filtering Recommendation Systems](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library)
|
||||
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
|
||||
- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding)
|
||||
- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size)
|
||||
- [The Basics of Java Generics](http://www.baeldung.com/java-generics)
|
||||
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
|
||||
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
|
||||
- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
|
||||
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
|
||||
|
|
|
@ -63,6 +63,7 @@
|
|||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- web -->
|
||||
|
||||
<!-- marshalling -->
|
||||
|
@ -352,7 +353,7 @@
|
|||
<logback.version>1.1.7</logback.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<guava.version>21.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
|
|
|
@ -3,29 +3,33 @@ package com.baeldung.algorithms;
|
|||
import java.util.Scanner;
|
||||
|
||||
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
|
||||
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
|
||||
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||
|
||||
public class RunAlgorithm {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
System.out.println(
|
||||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||
break;
|
||||
case 2:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
System.out.println("3 - Simple Genetic Algorithm");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||
break;
|
||||
case 2:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
case 3:
|
||||
SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -5,18 +5,18 @@ import lombok.Data;
|
|||
@Data
|
||||
public class City {
|
||||
|
||||
private int x;
|
||||
private int y;
|
||||
private int x;
|
||||
private int y;
|
||||
|
||||
public City() {
|
||||
this.x = (int) (Math.random() * 500);
|
||||
this.y = (int) (Math.random() * 500);
|
||||
}
|
||||
public City() {
|
||||
this.x = (int) (Math.random() * 500);
|
||||
this.y = (int) (Math.random() * 500);
|
||||
}
|
||||
|
||||
public double distanceToCity(City city) {
|
||||
int x = Math.abs(getX() - city.getX());
|
||||
int y = Math.abs(getY() - city.getY());
|
||||
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
||||
}
|
||||
public double distanceToCity(City city) {
|
||||
int x = Math.abs(getX() - city.getX());
|
||||
int y = Math.abs(getY() - city.getY());
|
||||
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -24,7 +24,7 @@ public class SimulatedAnnealing {
|
|||
}
|
||||
t *= coolingRate;
|
||||
} else {
|
||||
continue;
|
||||
continue;
|
||||
}
|
||||
if (i % 100 == 0) {
|
||||
System.out.println("Iteration #" + i);
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.algorithms.ga.binary;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class Individual {
|
||||
|
||||
protected int defaultGeneLength = 64;
|
||||
private byte[] genes = new byte[defaultGeneLength];
|
||||
private int fitness = 0;
|
||||
|
||||
public Individual() {
|
||||
for (int i = 0; i < genes.length; i++) {
|
||||
byte gene = (byte) Math.round(Math.random());
|
||||
genes[i] = gene;
|
||||
}
|
||||
}
|
||||
|
||||
protected byte getSingleGene(int index) {
|
||||
return genes[index];
|
||||
}
|
||||
|
||||
protected void setSingleGene(int index, byte value) {
|
||||
genes[index] = value;
|
||||
fitness = 0;
|
||||
}
|
||||
|
||||
public int getFitness() {
|
||||
if (fitness == 0) {
|
||||
fitness = SimpleGeneticAlgorithm.getFitness(this);
|
||||
}
|
||||
return fitness;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String geneString = "";
|
||||
for (int i = 0; i < genes.length; i++) {
|
||||
geneString += getSingleGene(i);
|
||||
}
|
||||
return geneString;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.algorithms.ga.binary;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class Population {
|
||||
|
||||
private List<Individual> individuals;
|
||||
|
||||
public Population(int size, boolean createNew) {
|
||||
individuals = new ArrayList<>();
|
||||
if (createNew) {
|
||||
createNewPopulation(size);
|
||||
}
|
||||
}
|
||||
|
||||
protected Individual getIndividual(int index) {
|
||||
return individuals.get(index);
|
||||
}
|
||||
|
||||
protected Individual getFittest() {
|
||||
Individual fittest = individuals.get(0);
|
||||
for (int i = 0; i < individuals.size(); i++) {
|
||||
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
|
||||
fittest = getIndividual(i);
|
||||
}
|
||||
}
|
||||
return fittest;
|
||||
}
|
||||
|
||||
private void createNewPopulation(int size) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
Individual newIndividual = new Individual();
|
||||
individuals.add(i, newIndividual);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,117 @@
|
|||
package com.baeldung.algorithms.ga.binary;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class SimpleGeneticAlgorithm {
|
||||
|
||||
private static final double uniformRate = 0.5;
|
||||
private static final double mutationRate = 0.025;
|
||||
private static final int tournamentSize = 5;
|
||||
private static final boolean elitism = true;
|
||||
private static byte[] solution = new byte[64];
|
||||
|
||||
public static boolean runAlgorithm(int populationSize, String solution) {
|
||||
if (solution.length() != SimpleGeneticAlgorithm.solution.length) {
|
||||
throw new RuntimeException("The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes");
|
||||
}
|
||||
SimpleGeneticAlgorithm.setSolution(solution);
|
||||
Population myPop = new Population(populationSize, true);
|
||||
|
||||
int generationCount = 1;
|
||||
while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) {
|
||||
System.out.println("Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness());
|
||||
myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop);
|
||||
generationCount++;
|
||||
}
|
||||
System.out.println("Solution found!");
|
||||
System.out.println("Generation: " + generationCount);
|
||||
System.out.println("Genes: ");
|
||||
System.out.println(myPop.getFittest());
|
||||
return true;
|
||||
}
|
||||
|
||||
public static Population evolvePopulation(Population pop) {
|
||||
int elitismOffset;
|
||||
Population newPopulation = new Population(pop.getIndividuals().size(), false);
|
||||
|
||||
if (elitism) {
|
||||
newPopulation.getIndividuals().add(0, pop.getFittest());
|
||||
elitismOffset = 1;
|
||||
} else {
|
||||
elitismOffset = 0;
|
||||
}
|
||||
|
||||
for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) {
|
||||
Individual indiv1 = tournamentSelection(pop);
|
||||
Individual indiv2 = tournamentSelection(pop);
|
||||
Individual newIndiv = crossover(indiv1, indiv2);
|
||||
newPopulation.getIndividuals().add(i, newIndiv);
|
||||
}
|
||||
|
||||
for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) {
|
||||
mutate(newPopulation.getIndividual(i));
|
||||
}
|
||||
|
||||
return newPopulation;
|
||||
}
|
||||
|
||||
private static Individual crossover(Individual indiv1, Individual indiv2) {
|
||||
Individual newSol = new Individual();
|
||||
for (int i = 0; i < newSol.getDefaultGeneLength(); i++) {
|
||||
if (Math.random() <= uniformRate) {
|
||||
newSol.setSingleGene(i, indiv1.getSingleGene(i));
|
||||
} else {
|
||||
newSol.setSingleGene(i, indiv2.getSingleGene(i));
|
||||
}
|
||||
}
|
||||
return newSol;
|
||||
}
|
||||
|
||||
private static void mutate(Individual indiv) {
|
||||
for (int i = 0; i < indiv.getDefaultGeneLength(); i++) {
|
||||
if (Math.random() <= mutationRate) {
|
||||
byte gene = (byte) Math.round(Math.random());
|
||||
indiv.setSingleGene(i, gene);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Individual tournamentSelection(Population pop) {
|
||||
Population tournament = new Population(tournamentSize, false);
|
||||
for (int i = 0; i < tournamentSize; i++) {
|
||||
int randomId = (int) (Math.random() * pop.getIndividuals().size());
|
||||
tournament.getIndividuals().add(i, pop.getIndividual(randomId));
|
||||
}
|
||||
Individual fittest = tournament.getFittest();
|
||||
return fittest;
|
||||
}
|
||||
|
||||
protected static int getFitness(Individual individual) {
|
||||
int fitness = 0;
|
||||
for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) {
|
||||
if (individual.getSingleGene(i) == solution[i]) {
|
||||
fitness++;
|
||||
}
|
||||
}
|
||||
return fitness;
|
||||
}
|
||||
|
||||
protected static int getMaxFitness() {
|
||||
int maxFitness = solution.length;
|
||||
return maxFitness;
|
||||
}
|
||||
|
||||
protected static void setSolution(String newSolution) {
|
||||
solution = new byte[newSolution.length()];
|
||||
for (int i = 0; i < newSolution.length(); i++) {
|
||||
String character = newSolution.substring(i, i + 1);
|
||||
if (character.contains("0") || character.contains("1")) {
|
||||
solution[i] = Byte.parseByte(character);
|
||||
} else {
|
||||
solution[i] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -11,26 +11,25 @@ import lombok.Data;
|
|||
|
||||
@Data
|
||||
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) {
|
||||
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
||||
HashMap<Item, Double> newUser;
|
||||
Set<Item> newRecommendationSet;
|
||||
for (int i = 0; i < numberOfUsers; i++) {
|
||||
newUser = new HashMap<Item, Double>();
|
||||
newRecommendationSet = new HashSet<>();
|
||||
for (int j = 0; j < 3; j++) {
|
||||
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
||||
}
|
||||
for (Item item : newRecommendationSet) {
|
||||
newUser.put(item, Math.random());
|
||||
}
|
||||
data.put(new User("User " + i), newUser);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
protected static List<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) {
|
||||
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
||||
HashMap<Item, Double> newUser;
|
||||
Set<Item> newRecommendationSet;
|
||||
for (int i = 0; i < numberOfUsers; i++) {
|
||||
newUser = new HashMap<Item, Double>();
|
||||
newRecommendationSet = new HashSet<>();
|
||||
for (int j = 0; j < 3; j++) {
|
||||
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
||||
}
|
||||
for (Item item : newRecommendationSet) {
|
||||
newUser.put(item, Math.random());
|
||||
}
|
||||
data.put(new User("User " + i), newUser);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -9,5 +9,5 @@ import lombok.NoArgsConstructor;
|
|||
@AllArgsConstructor
|
||||
public class Item {
|
||||
|
||||
private String itemName;
|
||||
private String itemName;
|
||||
}
|
||||
|
|
|
@ -11,114 +11,114 @@ import java.util.Map.Entry;
|
|||
*/
|
||||
public class SlopeOne {
|
||||
|
||||
private static Map<Item, Map<Item, Double>> diff = 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>> outputData = 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<User, HashMap<Item, Double>> inputData;
|
||||
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
|
||||
|
||||
public static void slopeOne(int numberOfUsers) {
|
||||
inputData = InputData.initializeData(numberOfUsers);
|
||||
System.out.println("Slope One - Before the Prediction\n");
|
||||
buildDifferencesMatrix(inputData);
|
||||
System.out.println("\nSlope One - With Predictions\n");
|
||||
predict(inputData);
|
||||
}
|
||||
public static void slopeOne(int numberOfUsers) {
|
||||
inputData = InputData.initializeData(numberOfUsers);
|
||||
System.out.println("Slope One - Before the Prediction\n");
|
||||
buildDifferencesMatrix(inputData);
|
||||
System.out.println("\nSlope One - With Predictions\n");
|
||||
predict(inputData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Based on the available data, calculate the relationships between the
|
||||
* items and number of occurences
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
||||
for (HashMap<Item, Double> user : data.values()) {
|
||||
for (Entry<Item, Double> e : user.entrySet()) {
|
||||
if (!diff.containsKey(e.getKey())) {
|
||||
diff.put(e.getKey(), new HashMap<Item, Double>());
|
||||
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
||||
}
|
||||
for (Entry<Item, Double> e2 : user.entrySet()) {
|
||||
int oldCount = 0;
|
||||
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
||||
}
|
||||
double oldDiff = 0.0;
|
||||
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
||||
}
|
||||
double observedDiff = e.getValue() - e2.getValue();
|
||||
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
||||
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Item j : diff.keySet()) {
|
||||
for (Item i : diff.get(j).keySet()) {
|
||||
double oldValue = diff.get(j).get(i).doubleValue();
|
||||
int count = freq.get(j).get(i).intValue();
|
||||
diff.get(j).put(i, oldValue / count);
|
||||
}
|
||||
}
|
||||
printData(data);
|
||||
}
|
||||
/**
|
||||
* Based on the available data, calculate the relationships between the
|
||||
* items and number of occurences
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
||||
for (HashMap<Item, Double> user : data.values()) {
|
||||
for (Entry<Item, Double> e : user.entrySet()) {
|
||||
if (!diff.containsKey(e.getKey())) {
|
||||
diff.put(e.getKey(), new HashMap<Item, Double>());
|
||||
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
||||
}
|
||||
for (Entry<Item, Double> e2 : user.entrySet()) {
|
||||
int oldCount = 0;
|
||||
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
||||
}
|
||||
double oldDiff = 0.0;
|
||||
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
||||
}
|
||||
double observedDiff = e.getValue() - e2.getValue();
|
||||
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
||||
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Item j : diff.keySet()) {
|
||||
for (Item i : diff.get(j).keySet()) {
|
||||
double oldValue = diff.get(j).get(i).doubleValue();
|
||||
int count = freq.get(j).get(i).intValue();
|
||||
diff.get(j).put(i, oldValue / count);
|
||||
}
|
||||
}
|
||||
printData(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Based on existing data predict all missing ratings. If prediction is not
|
||||
* possible, the value will be equal to -1
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
||||
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
||||
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
||||
for (Item j : diff.keySet()) {
|
||||
uFreq.put(j, 0);
|
||||
uPred.put(j, 0.0);
|
||||
}
|
||||
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
||||
for (Item j : e.getValue().keySet()) {
|
||||
for (Item k : diff.keySet()) {
|
||||
try {
|
||||
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
||||
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
||||
uPred.put(k, uPred.get(k) + finalValue);
|
||||
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
||||
} catch (NullPointerException e1) {
|
||||
}
|
||||
}
|
||||
}
|
||||
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
||||
for (Item j : uPred.keySet()) {
|
||||
if (uFreq.get(j) > 0) {
|
||||
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
||||
}
|
||||
}
|
||||
for (Item j : InputData.items) {
|
||||
if (e.getValue().containsKey(j)) {
|
||||
clean.put(j, e.getValue().get(j));
|
||||
} else {
|
||||
clean.put(j, -1.0);
|
||||
}
|
||||
}
|
||||
outputData.put(e.getKey(), clean);
|
||||
}
|
||||
printData(outputData);
|
||||
}
|
||||
/**
|
||||
* Based on existing data predict all missing ratings. If prediction is not
|
||||
* possible, the value will be equal to -1
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
||||
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
||||
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
||||
for (Item j : diff.keySet()) {
|
||||
uFreq.put(j, 0);
|
||||
uPred.put(j, 0.0);
|
||||
}
|
||||
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
||||
for (Item j : e.getValue().keySet()) {
|
||||
for (Item k : diff.keySet()) {
|
||||
try {
|
||||
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
||||
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
||||
uPred.put(k, uPred.get(k) + finalValue);
|
||||
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
||||
} catch (NullPointerException e1) {
|
||||
}
|
||||
}
|
||||
}
|
||||
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
||||
for (Item j : uPred.keySet()) {
|
||||
if (uFreq.get(j) > 0) {
|
||||
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
||||
}
|
||||
}
|
||||
for (Item j : InputData.items) {
|
||||
if (e.getValue().containsKey(j)) {
|
||||
clean.put(j, e.getValue().get(j));
|
||||
} else {
|
||||
clean.put(j, -1.0);
|
||||
}
|
||||
}
|
||||
outputData.put(e.getKey(), clean);
|
||||
}
|
||||
printData(outputData);
|
||||
}
|
||||
|
||||
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
||||
for (User user : data.keySet()) {
|
||||
System.out.println(user.getUsername() + ":");
|
||||
print(data.get(user));
|
||||
}
|
||||
}
|
||||
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
||||
for (User user : data.keySet()) {
|
||||
System.out.println(user.getUsername() + ":");
|
||||
print(data.get(user));
|
||||
}
|
||||
}
|
||||
|
||||
private static void print(HashMap<Item, Double> hashMap) {
|
||||
NumberFormat formatter = new DecimalFormat("#0.000");
|
||||
for (Item j : hashMap.keySet()) {
|
||||
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
||||
}
|
||||
}
|
||||
private static void print(HashMap<Item, Double> hashMap) {
|
||||
NumberFormat formatter = new DecimalFormat("#0.000");
|
||||
for (Item j : hashMap.keySet()) {
|
||||
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ import lombok.NoArgsConstructor;
|
|||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue