Merge branch 'master' into pr/1014-stephen
This commit is contained in:
commit
444c475d7c
|
@ -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,59 @@
|
|||
package com.baeldung.algorithms.dijkstra;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
public class Dijkstra {
|
||||
|
||||
public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
|
||||
|
||||
source.setDistance(0);
|
||||
|
||||
Set<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,85 @@
|
|||
package algorithms;
|
||||
|
||||
import com.baeldung.algorithms.dijkstra.Dijkstra;
|
||||
import com.baeldung.algorithms.dijkstra.Graph;
|
||||
import com.baeldung.algorithms.dijkstra.Node;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class DijkstraAlgorithmTest {
|
||||
|
||||
@Test
|
||||
public void whenSPPSolved_thenCorrect() {
|
||||
|
||||
Node nodeA = new Node("A");
|
||||
Node nodeB = new Node("B");
|
||||
Node nodeC = new Node("C");
|
||||
Node nodeD = new Node("D");
|
||||
Node nodeE = new Node("E");
|
||||
Node nodeF = new Node("F");
|
||||
|
||||
nodeA.addDestination(nodeB, 10);
|
||||
nodeA.addDestination(nodeC, 15);
|
||||
|
||||
nodeB.addDestination(nodeD, 12);
|
||||
nodeB.addDestination(nodeF, 15);
|
||||
|
||||
nodeC.addDestination(nodeE, 10);
|
||||
|
||||
nodeD.addDestination(nodeE, 2);
|
||||
nodeD.addDestination(nodeF, 1);
|
||||
|
||||
nodeF.addDestination(nodeE, 5);
|
||||
|
||||
Graph graph = new Graph();
|
||||
|
||||
graph.addNode(nodeA);
|
||||
graph.addNode(nodeB);
|
||||
graph.addNode(nodeC);
|
||||
graph.addNode(nodeD);
|
||||
graph.addNode(nodeE);
|
||||
graph.addNode(nodeF);
|
||||
|
||||
graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA);
|
||||
|
||||
List<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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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>
|
||||
|
|
|
@ -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>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>net.sf.jtidy</groupId>
|
||||
<artifactId>jtidy</artifactId>
|
||||
<version>${jtidy.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>apache-fop</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<build>
|
||||
<finalName>apache-fop</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugins>
|
||||
|
||||
<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-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>
|
||||
<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>
|
||||
|
@ -186,24 +187,24 @@
|
|||
</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>
|
||||
<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>
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.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>
|
||||
<!-- 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>
|
||||
</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)
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Intro to AspectJ](http://www.baeldung.com/aspectj)
|
||||
- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging)
|
|
@ -45,6 +45,36 @@
|
|||
<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>
|
||||
|
@ -81,18 +111,8 @@
|
|||
<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>
|
||||
-->
|
||||
<!-- <weaveDependencies> <weaveDependency> <groupId>org.agroup</groupId> <artifactId>to-weave</artifactId> </weaveDependency>
|
||||
<weaveDependency> <groupId>org.anothergroup</groupId> <artifactId>gen</artifactId> </weaveDependency> </weaveDependencies> -->
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
|
@ -102,20 +122,11 @@
|
|||
</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
|
|
@ -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;
|
||||
|
|
@ -1,91 +1,88 @@
|
|||
<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>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
<!-- 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>
|
||||
|
|
|
@ -16,3 +16,7 @@
|
|||
*.txt
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea
|
||||
*.iml
|
|
@ -46,3 +46,11 @@
|
|||
- [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)
|
||||
|
|
|
@ -63,6 +63,12 @@
|
|||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.lmax</groupId>
|
||||
<artifactId>disruptor</artifactId>
|
||||
<version>${disruptor.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
|
||||
<!-- marshalling -->
|
||||
|
@ -352,7 +358,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>
|
||||
|
@ -363,6 +369,7 @@
|
|||
<unix4j.version>0.4</unix4j.version>
|
||||
<grep4j.version>1.8.7</grep4j.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
<disruptor.version>3.3.6</disruptor.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
|
|
|
@ -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 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,47 @@
|
|||
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,34 @@
|
|||
package com.baeldung.disruptor;
|
||||
|
||||
import com.lmax.disruptor.RingBuffer;
|
||||
|
||||
public class DelayedMultiEventProducer implements EventProducer {
|
||||
|
||||
@Override
|
||||
public void startProducing(final RingBuffer<ValueEvent> ringBuffer, final int count) {
|
||||
final Runnable simpleProducer = () -> produce(ringBuffer, count, false);
|
||||
final Runnable delayedProducer = () -> produce(ringBuffer, count, true);
|
||||
new Thread(simpleProducer).start();
|
||||
new Thread(delayedProducer).start();
|
||||
}
|
||||
|
||||
private void produce(final RingBuffer<ValueEvent> ringBuffer, final int count, final boolean addDelay) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
final long seq = ringBuffer.next();
|
||||
final ValueEvent valueEvent = ringBuffer.get(seq);
|
||||
valueEvent.setValue(i);
|
||||
ringBuffer.publish(seq);
|
||||
if (addDelay) {
|
||||
addDelay();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void addDelay() {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException interruptedException) {
|
||||
// No-Op lets swallow it
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.disruptor;
|
||||
|
||||
import com.lmax.disruptor.EventHandler;
|
||||
|
||||
/**
|
||||
* Consumer that consumes event from ring buffer.
|
||||
*/
|
||||
public interface EventConsumer {
|
||||
/**
|
||||
* One or more event handler to handle event from ring buffer.
|
||||
*/
|
||||
public EventHandler<ValueEvent>[] getEventHandler();
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.disruptor;
|
||||
|
||||
import com.lmax.disruptor.RingBuffer;
|
||||
|
||||
/**
|
||||
* Producer that produces event for ring buffer.
|
||||
*/
|
||||
public interface EventProducer {
|
||||
/**
|
||||
* Start the producer that would start producing the values.
|
||||
* @param ringBuffer
|
||||
* @param count
|
||||
*/
|
||||
public void startProducing(final RingBuffer<ValueEvent> ringBuffer, final int count);
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.disruptor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.lmax.disruptor.EventHandler;
|
||||
|
||||
public class MultiEventPrintConsumer implements EventConsumer {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public EventHandler<ValueEvent>[] getEventHandler() {
|
||||
final EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> print(event.getValue(), sequence);
|
||||
final EventHandler<ValueEvent> otherEventHandler = (event, sequence, endOfBatch) -> print(event.getValue(), sequence);
|
||||
return new EventHandler[] { eventHandler, otherEventHandler };
|
||||
}
|
||||
|
||||
private void print(final int id, final long sequenceId) {
|
||||
logger.info("Id is " + id + " sequence id that was used is " + sequenceId);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.disruptor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.lmax.disruptor.EventHandler;
|
||||
|
||||
public class SingleEventPrintConsumer implements EventConsumer {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public EventHandler<ValueEvent>[] getEventHandler() {
|
||||
final EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> print(event.getValue(), sequence);
|
||||
return new EventHandler[] { eventHandler };
|
||||
}
|
||||
|
||||
private void print(final int id, final long sequenceId) {
|
||||
logger.info("Id is " + id + " sequence id that was used is " + sequenceId);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.disruptor;
|
||||
|
||||
import com.lmax.disruptor.RingBuffer;
|
||||
|
||||
public class SingleEventProducer implements EventProducer {
|
||||
|
||||
@Override
|
||||
public void startProducing(RingBuffer<ValueEvent> ringBuffer, int count) {
|
||||
final Runnable producer = () -> produce(ringBuffer, count);
|
||||
new Thread(producer).start();
|
||||
}
|
||||
|
||||
private void produce(final RingBuffer<ValueEvent> ringBuffer, final int count) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
final long seq = ringBuffer.next();
|
||||
final ValueEvent valueEvent = ringBuffer.get(seq);
|
||||
valueEvent.setValue(i);
|
||||
ringBuffer.publish(seq);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.disruptor;
|
||||
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
|
||||
import com.lmax.disruptor.EventFactory;
|
||||
|
||||
public final class ValueEvent {
|
||||
|
||||
private int value;
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public final static EventFactory<ValueEvent> EVENT_FACTORY = () -> new ValueEvent();
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ToStringBuilder.reflectionToString(this);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.java8.lambda.exceptions;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class LambdaExceptionWrappers {
|
||||
|
||||
public static Consumer<Integer> lambdaWrapper(Consumer<Integer> consumer) {
|
||||
return i -> {
|
||||
try {
|
||||
consumer.accept(i);
|
||||
} catch (ArithmeticException e) {
|
||||
System.err.println("Arithmetic Exception occured : " + e.getMessage());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static <T, E extends Exception> Consumer<T> consumerWrapper(Consumer<T> consumer, Class<E> clazz) {
|
||||
return i -> {
|
||||
try {
|
||||
consumer.accept(i);
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
E exCast = clazz.cast(ex);
|
||||
System.err.println("Exception occured : " + exCast.getMessage());
|
||||
} catch (ClassCastException ccEx) {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static <T> Consumer<T> throwingConsumerWrapper(ThrowingConsumer<T, Exception> throwingConsumer) {
|
||||
return i -> {
|
||||
try {
|
||||
throwingConsumer.accept(i);
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static <T, E extends Exception> Consumer<T> handlingConsumerWrapper(ThrowingConsumer<T, E> throwingConsumer, Class<E> exceptionClass) {
|
||||
return i -> {
|
||||
try {
|
||||
throwingConsumer.accept(i);
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
E exCast = exceptionClass.cast(ex);
|
||||
System.err.println("Exception occured : " + exCast.getMessage());
|
||||
} catch (ClassCastException ccEx) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.java8.lambda.exceptions;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ThrowingConsumer<T, E extends Exception> {
|
||||
|
||||
void accept(T t) throws E;
|
||||
|
||||
}
|
|
@ -1,48 +0,0 @@
|
|||
package com.baeldung.scripting;
|
||||
|
||||
import javax.script.Bindings;
|
||||
import javax.script.Invocable;
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptEngineManager;
|
||||
import javax.script.ScriptException;
|
||||
|
||||
public class Nashorn {
|
||||
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
|
||||
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
|
||||
|
||||
Object result = engine.eval(
|
||||
"var greeting='hello world';" +
|
||||
"print(greeting);" +
|
||||
"greeting");
|
||||
|
||||
System.out.println(result);
|
||||
|
||||
Bindings bindings = engine.createBindings();
|
||||
bindings.put("count", 3);
|
||||
bindings.put("name", "baeldung");
|
||||
|
||||
String script = "var greeting='Hello ';" +
|
||||
"for(var i=count;i>0;i--) { " +
|
||||
"greeting+=name + ' '" +
|
||||
"}" +
|
||||
"greeting";
|
||||
|
||||
Object bindingsResult = engine.eval(script, bindings);
|
||||
System.out.println(bindingsResult);
|
||||
|
||||
engine.eval("function composeGreeting(name) {" +
|
||||
"return 'Hello ' + name" +
|
||||
"}");
|
||||
Invocable invocable = (Invocable) engine;
|
||||
|
||||
Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung");
|
||||
System.out.println(funcResult);
|
||||
|
||||
Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" +
|
||||
"var map = new HashMap();" +
|
||||
"map.put('hello', 'world');" +
|
||||
"map");
|
||||
|
||||
System.out.println(map);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
var first = {
|
||||
name: "Whiskey",
|
||||
age: 5
|
||||
};
|
||||
|
||||
var second = {
|
||||
volume: 100
|
||||
};
|
||||
|
||||
Object.bindProperties(first, second);
|
||||
|
||||
print(first.volume);
|
||||
|
||||
second.volume = 1000;
|
||||
print(first.volume);
|
|
@ -0,0 +1 @@
|
|||
print(__FILE__, __LINE__, __DIR__);
|
|
@ -0,0 +1,19 @@
|
|||
var math = {
|
||||
increment: function (num) {
|
||||
return ++num;
|
||||
},
|
||||
|
||||
failFunc: function () {
|
||||
try {
|
||||
throw "BOOM";
|
||||
} catch (e if typeof e === 'string') {
|
||||
print("String thrown: " + e);
|
||||
}
|
||||
catch (e) {
|
||||
print("this shouldn't happen!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
math;
|
|
@ -0,0 +1,11 @@
|
|||
var demo = {
|
||||
__noSuchProperty__: function (propName) {
|
||||
print("Accessed non-existing property: " + propName);
|
||||
},
|
||||
|
||||
__noSuchMethod__: function (methodName) {
|
||||
print("Invoked non-existing method: " + methodName);
|
||||
}
|
||||
};
|
||||
|
||||
demo;
|
|
@ -0,0 +1 @@
|
|||
function increment(num) ++num;
|
|
@ -0,0 +1,2 @@
|
|||
print(" hello world".trimLeft());
|
||||
print("hello world ".trimRight());
|
|
@ -0,0 +1,9 @@
|
|||
function arrays(arr) {
|
||||
|
||||
var javaIntArray = Java.to(arr, "int[]");
|
||||
print(javaIntArray[0]);
|
||||
print(javaIntArray[1]);
|
||||
print(javaIntArray[2]);
|
||||
}
|
||||
|
||||
arrays([100, "1654", true]);
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.disruptor;
|
||||
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import com.lmax.disruptor.BusySpinWaitStrategy;
|
||||
import com.lmax.disruptor.RingBuffer;
|
||||
import com.lmax.disruptor.WaitStrategy;
|
||||
import com.lmax.disruptor.dsl.Disruptor;
|
||||
import com.lmax.disruptor.dsl.ProducerType;
|
||||
import com.lmax.disruptor.util.DaemonThreadFactory;
|
||||
|
||||
public class DisruptorTest {
|
||||
private Disruptor<ValueEvent> disruptor;
|
||||
private WaitStrategy waitStrategy;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
waitStrategy = new BusySpinWaitStrategy();
|
||||
}
|
||||
|
||||
private void createDisruptor(final ProducerType producerType, final EventConsumer eventConsumer) {
|
||||
final ThreadFactory threadFactory = DaemonThreadFactory.INSTANCE;
|
||||
disruptor = new Disruptor<ValueEvent>(ValueEvent.EVENT_FACTORY, 16, threadFactory, producerType, waitStrategy);
|
||||
disruptor.handleEventsWith(eventConsumer.getEventHandler());
|
||||
}
|
||||
|
||||
private void startProducing(final RingBuffer<ValueEvent> ringBuffer, final int count, final EventProducer eventProducer) {
|
||||
eventProducer.startProducing(ringBuffer, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultipleProducerSingleConsumer_thenOutputInFifoOrder() {
|
||||
final EventConsumer eventConsumer = new SingleEventPrintConsumer();
|
||||
final EventProducer eventProducer = new DelayedMultiEventProducer();
|
||||
createDisruptor(ProducerType.MULTI, eventConsumer);
|
||||
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
|
||||
|
||||
startProducing(ringBuffer, 32, eventProducer);
|
||||
|
||||
disruptor.halt();
|
||||
disruptor.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSingleProducerSingleConsumer_thenOutputInFifoOrder() {
|
||||
final EventConsumer eventConsumer = new SingleEventConsumer();
|
||||
final EventProducer eventProducer = new SingleEventProducer();
|
||||
createDisruptor(ProducerType.SINGLE, eventConsumer);
|
||||
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
|
||||
|
||||
startProducing(ringBuffer, 32, eventProducer);
|
||||
|
||||
disruptor.halt();
|
||||
disruptor.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSingleProducerMultipleConsumer_thenOutputInFifoOrder() {
|
||||
final EventConsumer eventConsumer = new MultiEventConsumer();
|
||||
final EventProducer eventProducer = new SingleEventProducer();
|
||||
createDisruptor(ProducerType.SINGLE, eventConsumer);
|
||||
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
|
||||
|
||||
startProducing(ringBuffer, 32, eventProducer);
|
||||
|
||||
disruptor.halt();
|
||||
disruptor.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultipleProducerMultipleConsumer_thenOutputInFifoOrder() {
|
||||
final EventConsumer eventConsumer = new MultiEventPrintConsumer();
|
||||
final EventProducer eventProducer = new DelayedMultiEventProducer();
|
||||
createDisruptor(ProducerType.MULTI, eventConsumer);
|
||||
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
|
||||
|
||||
startProducing(ringBuffer, 32, eventProducer);
|
||||
|
||||
disruptor.halt();
|
||||
disruptor.shutdown();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.disruptor;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import com.lmax.disruptor.EventHandler;
|
||||
|
||||
public class MultiEventConsumer implements EventConsumer {
|
||||
|
||||
private int expectedValue = -1;
|
||||
private int otherExpectedValue = -1;
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public EventHandler<ValueEvent>[] getEventHandler() {
|
||||
final EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> assertExpectedValue(event.getValue());
|
||||
final EventHandler<ValueEvent> otherEventHandler = (event, sequence, endOfBatch) -> assertOtherExpectedValue(event.getValue());
|
||||
return new EventHandler[] { eventHandler, otherEventHandler };
|
||||
}
|
||||
|
||||
private void assertExpectedValue(final int id) {
|
||||
assertEquals(++expectedValue, id);
|
||||
}
|
||||
|
||||
private void assertOtherExpectedValue(final int id) {
|
||||
assertEquals(++otherExpectedValue, id);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.disruptor;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import com.lmax.disruptor.EventHandler;
|
||||
|
||||
public class SingleEventConsumer implements EventConsumer {
|
||||
|
||||
private int expectedValue = -1;
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public EventHandler<ValueEvent>[] getEventHandler() {
|
||||
final EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> assertExpectedValue(event.getValue());
|
||||
return new EventHandler[] { eventHandler };
|
||||
}
|
||||
|
||||
private void assertExpectedValue(final int id) {
|
||||
assertEquals(++expectedValue, id);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,122 @@
|
|||
package com.baeldung.guava;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import com.google.common.collect.BiMap;
|
||||
import com.google.common.collect.EnumHashBiMap;
|
||||
import com.google.common.collect.HashBiMap;
|
||||
import com.google.common.collect.ImmutableBiMap;
|
||||
|
||||
public class GuavaBiMapTest {
|
||||
@Test
|
||||
public void whenQueryByValue_shouldReturnKey() {
|
||||
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
|
||||
capitalCountryBiMap.put("New Delhi", "India");
|
||||
capitalCountryBiMap.put("Washingon, D.C.", "USA");
|
||||
capitalCountryBiMap.put("Moscow", "Russia");
|
||||
|
||||
final String countryHeadName = capitalCountryBiMap.inverse().get("India");
|
||||
|
||||
assertEquals("New Delhi", countryHeadName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateBiMapFromExistingMap_shouldReturnKey() {
|
||||
final Map<String, String> personCountryHeadMap = new HashMap<>();
|
||||
personCountryHeadMap.put("New Delhi", "India");
|
||||
personCountryHeadMap.put("Washingon, D.C.", "USA");
|
||||
personCountryHeadMap.put("Moscow", "Russia");
|
||||
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create(personCountryHeadMap);
|
||||
|
||||
final String countryHeadName = capitalCountryBiMap.inverse().get("India");
|
||||
|
||||
assertEquals("New Delhi", countryHeadName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenQueryByKey_shouldReturnValue() {
|
||||
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
|
||||
|
||||
capitalCountryBiMap.put("New Delhi", "India");
|
||||
capitalCountryBiMap.put("Washingon, D.C.", "USA");
|
||||
capitalCountryBiMap.put("Moscow", "Russia");
|
||||
|
||||
assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C."));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenSameValueIsBeingPresent_shouldThrowException() {
|
||||
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
|
||||
|
||||
capitalCountryBiMap.put("New Delhi", "India");
|
||||
capitalCountryBiMap.put("Washingon, D.C.", "USA");
|
||||
capitalCountryBiMap.put("Moscow", "Russia");
|
||||
capitalCountryBiMap.put("Trump", "USA");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameValueIsBeingPresent_whenForcePutIsUsed_shouldCompleteSuccessfully() {
|
||||
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
|
||||
|
||||
capitalCountryBiMap.put("New Delhi", "India");
|
||||
capitalCountryBiMap.put("Washingon, D.C.", "USA");
|
||||
capitalCountryBiMap.put("Moscow", "Russia");
|
||||
capitalCountryBiMap.forcePut("Trump", "USA");
|
||||
|
||||
assertEquals("USA", capitalCountryBiMap.get("Trump"));
|
||||
assertEquals("Trump", capitalCountryBiMap.inverse().get("USA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSameKeyIsBeingPresent_shouldReplaceAlreadyPresent() {
|
||||
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
|
||||
|
||||
capitalCountryBiMap.put("New Delhi", "India");
|
||||
capitalCountryBiMap.put("Washingon, D.C.", "USA");
|
||||
capitalCountryBiMap.put("Moscow", "Russia");
|
||||
capitalCountryBiMap.put("Washingon, D.C.", "HongKong");
|
||||
|
||||
assertEquals("HongKong", capitalCountryBiMap.get("Washingon, D.C."));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingImmutableBiMap_shouldAllowPutSuccessfully() {
|
||||
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
|
||||
|
||||
assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C."));
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenUsingImmutableBiMap_shouldNotAllowRemove() {
|
||||
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
|
||||
|
||||
capitalCountryBiMap.remove("New Delhi");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenUsingImmutableBiMap_shouldNotAllowPut() {
|
||||
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
|
||||
|
||||
capitalCountryBiMap.put("New York", "USA");
|
||||
}
|
||||
|
||||
private enum Operation {
|
||||
ADD, SUBTRACT, MULTIPLY, DIVIDE
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEnumAsKeyInMap_shouldReplaceAlreadyPresent() {
|
||||
final BiMap<Operation, String> operationStringBiMap = EnumHashBiMap.create(Operation.class);
|
||||
|
||||
operationStringBiMap.put(Operation.ADD, "Add");
|
||||
operationStringBiMap.put(Operation.SUBTRACT, "Subtract");
|
||||
operationStringBiMap.put(Operation.MULTIPLY, "Multiply");
|
||||
operationStringBiMap.put(Operation.DIVIDE, "Divide");
|
||||
|
||||
assertEquals("Divide", operationStringBiMap.get(Operation.DIVIDE));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.java.conversion;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
|
||||
|
||||
public class IterableStreamConversionTest {
|
||||
|
||||
@Test
|
||||
public void givenIterable_whenConvertedToStream_thenNotNull() {
|
||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||
|
||||
Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToList_thenCorrect() {
|
||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||
|
||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
|
||||
.map(String::toUpperCase).collect(Collectors.toList());
|
||||
|
||||
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)
|
|
@ -1,3 +1,11 @@
|
|||
### Relevant Articles:
|
||||
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
|
||||
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
|
||||
- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel)
|
||||
- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng)
|
||||
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
|
||||
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
|
||||
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
|
||||
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
|
||||
- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
|
||||
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
|
||||
|
|
|
@ -7,8 +7,10 @@ import java.util.Arrays;
|
|||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8FindAnyFindFirstTest {
|
||||
|
||||
|
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.java8.lambda.exceptions;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*;
|
||||
|
||||
public class LambdaExceptionWrappersTest {
|
||||
|
||||
private List<Integer> integers;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
integers = Arrays.asList(3, 9, 7, 0, 10, 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoExceptionFromLambdaWrapper_thenSuccess() {
|
||||
integers.forEach(lambdaWrapper(i -> System.out.println(50 / i)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoExceptionFromConsumerWrapper_thenSuccess() {
|
||||
integers.forEach(consumerWrapper(i -> System.out.println(50 / i), ArithmeticException.class));
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void whenExceptionFromThrowingConsumerWrapper_thenSuccess() {
|
||||
integers.forEach(throwingConsumerWrapper(i -> writeToFile(i)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoExceptionFromHandlingConsumerWrapper_thenSuccess() {
|
||||
integers.forEach(handlingConsumerWrapper(i -> writeToFile(i), IOException.class));
|
||||
}
|
||||
|
||||
private void writeToFile(Integer i) throws IOException {
|
||||
if (i == 0) {
|
||||
throw new IOException(); // mock IOException
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
|
|
@ -0,0 +1,111 @@
|
|||
package com.baeldung.scripting;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.script.*;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class NashornTest {
|
||||
|
||||
private ScriptEngine engine;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
engine = new ScriptEngineManager().getEngineByName("nashorn");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void trim() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/trim.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void locations() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/locations.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bindProperties() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/bind.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void magicMethods() throws ScriptException {
|
||||
engine.eval("var demo = load('classpath:js/no_such.js');" + "var tmp = demo.doesNotExist;" + "var none = demo.callNonExistingMethod()");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void typedArrays() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornTest.class.getResourceAsStream("/js/typed_arrays.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void basicUsage() throws ScriptException {
|
||||
Object result = engine.eval("var greeting='hello world';" + "print(greeting);" + "greeting");
|
||||
|
||||
Assert.assertEquals("hello world", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jsonObjectExample() throws ScriptException {
|
||||
Object obj = engine.eval("Java.asJSONCompatible({ number: 42, greet: 'hello', primes: [2,3,5,7,11,13] })");
|
||||
Map<String, Object> map = (Map<String, Object>) obj;
|
||||
|
||||
Assert.assertEquals("hello", map.get("greet"));
|
||||
Assert.assertTrue(List.class.isAssignableFrom(map
|
||||
.get("primes")
|
||||
.getClass()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void tryCatchGuard() throws ScriptException {
|
||||
engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.failFunc();");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extensionsExamples() throws ScriptException {
|
||||
String script = "var list = [1, 2, 3, 4, 5];" + "var result = '';" + "for each (var i in list) {" + "result+=i+'-';" + "};" + "print(result);";
|
||||
engine.eval(script);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bindingsExamples() throws ScriptException {
|
||||
Bindings bindings = engine.createBindings();
|
||||
bindings.put("count", 3);
|
||||
bindings.put("name", "baeldung");
|
||||
|
||||
String script = "var greeting='Hello ';" + "for(var i=count;i>0;i--) { " + "greeting+=name + ' '" + "}" + "greeting";
|
||||
|
||||
Object bindingsResult = engine.eval(script, bindings);
|
||||
Assert.assertEquals("Hello baeldung baeldung baeldung ", bindingsResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jvmBoundaryExamples() throws ScriptException, NoSuchMethodException {
|
||||
engine.eval("function composeGreeting(name) {" + "return 'Hello ' + name" + "}");
|
||||
|
||||
Invocable invocable = (Invocable) engine;
|
||||
|
||||
Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung");
|
||||
Assert.assertEquals("Hello baeldung", funcResult);
|
||||
|
||||
Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" + "var map = new HashMap();" + "map.put('hello', 'world');" + "map");
|
||||
|
||||
Assert.assertTrue(Map.class.isAssignableFrom(map.getClass()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadExamples() throws ScriptException {
|
||||
Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)");
|
||||
|
||||
Assert.assertEquals(6.0, loadResult);
|
||||
|
||||
Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);");
|
||||
|
||||
Assert.assertEquals(6.0, math);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
||||
- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
|
|
@ -1,38 +1,26 @@
|
|||
package org.baeldung.java.io;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.io.ByteSource;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.io.CharStreams;
|
||||
import com.google.common.io.Files;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Scanner;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public class JavaInputStreamToXUnitTest {
|
||||
|
@ -163,7 +151,7 @@ public class JavaInputStreamToXUnitTest {
|
|||
// tests - InputStream to File
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingAnFullInputStreamToAFile_thenCorrect() throws IOException {
|
||||
public final void whenConvertingToFile_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final byte[] buffer = new byte[initialStream.available()];
|
||||
initialStream.read(buffer);
|
||||
|
@ -177,7 +165,7 @@ public class JavaInputStreamToXUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException {
|
||||
public final void whenConvertingInProgressToFile_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final OutputStream outStream = new FileOutputStream(targetFile);
|
||||
|
@ -193,7 +181,7 @@ public class JavaInputStreamToXUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava8_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException {
|
||||
public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
|
||||
|
@ -203,7 +191,7 @@ public class JavaInputStreamToXUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException {
|
||||
public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final byte[] buffer = new byte[initialStream.available()];
|
||||
initialStream.read(buffer);
|
||||
|
@ -215,7 +203,7 @@ public class JavaInputStreamToXUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException {
|
||||
public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException {
|
||||
final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
|
||||
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
|
|
|
@ -1,91 +1,91 @@
|
|||
<?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>couchbase-sdk</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>couchbase-sdk</name>
|
||||
<description>Couchbase SDK Tutorials</description>
|
||||
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>couchbase-sdk</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>couchbase-sdk</name>
|
||||
<description>Couchbase SDK Tutorials</description>
|
||||
|
||||
<dependencies>
|
||||
<!-- Couchbase SDK -->
|
||||
<dependency>
|
||||
<groupId>com.couchbase.client</groupId>
|
||||
<artifactId>java-client</artifactId>
|
||||
<version>${couchbase.client.version}</version>
|
||||
</dependency>
|
||||
<dependencies>
|
||||
<!-- Couchbase SDK -->
|
||||
<dependency>
|
||||
<groupId>com.couchbase.client</groupId>
|
||||
<artifactId>java-client</artifactId>
|
||||
<version>${couchbase.client.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Context for Dependency Injection -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context-support</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
<!-- Spring Context for Dependency Injection -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context-support</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Logging with SLF4J & LogBack -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<!-- Logging with SLF4J & LogBack -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Test-Scoped Dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Test-Scoped Dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
|
@ -96,20 +96,20 @@
|
|||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<couchbase.client.version>2.3.6</couchbase.client.version>
|
||||
<spring-framework.version>4.3.4.RELEASE</spring-framework.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<couchbase.client.version>2.3.6</couchbase.client.version>
|
||||
<spring-framework.version>4.3.4.RELEASE</spring-framework.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,6 +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/maven-v4_0_0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>deltaspike</artifactId>
|
||||
|
@ -19,11 +19,10 @@
|
|||
</licenses>
|
||||
|
||||
<properties>
|
||||
<!-- Explicitly declaring the source encoding eliminates the following
|
||||
message: -->
|
||||
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
|
||||
resources, i.e. build is platform dependent! -->
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Explicitly declaring the source encoding eliminates the following message: -->
|
||||
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! -->
|
||||
<project.build.sourceEncoding>
|
||||
UTF-8</project.build.sourceEncoding>
|
||||
|
||||
<slf4j.version>1.7.21</slf4j.version>
|
||||
<querydsl.version>3.7.4</querydsl.version>
|
||||
|
@ -32,8 +31,7 @@
|
|||
<!-- JBoss dependency versions -->
|
||||
<wildfly.maven.plugin.version>1.0.2.Final</wildfly.maven.plugin.version>
|
||||
|
||||
<!-- Define the version of the JBoss BOMs we want to import to specify
|
||||
tested stacks. -->
|
||||
<!-- Define the version of the JBoss BOMs we want to import to specify tested stacks. -->
|
||||
<jboss.bom.version>8.2.2.Final</jboss.bom.version>
|
||||
|
||||
<!-- other plugin versions -->
|
||||
|
@ -50,14 +48,11 @@
|
|||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill
|
||||
of Materials (BOM). A BOM specifies the versions of a "stack" (or a collection)
|
||||
of artifacts. We use this here so that we always get the correct versions
|
||||
of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you can
|
||||
read this as the JBoss stack of the Java EE 7 APIs, with some extras tools
|
||||
for your project, such as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate
|
||||
stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras
|
||||
from the Hibernate family of projects) -->
|
||||
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill of Materials (BOM). A BOM specifies the versions of a "stack"
|
||||
(or a collection) of artifacts. We use this here so that we always get the correct versions of artifacts. Here we use the jboss-javaee-7.0-with-tools
|
||||
stack (you can read this as the JBoss stack of the Java EE 7 APIs, with some extras tools for your project, such as Arquillian for testing) and
|
||||
the jboss-javaee-7.0-with-hibernate stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras from the Hibernate family of
|
||||
projects) -->
|
||||
<dependency>
|
||||
<groupId>org.wildfly.bom</groupId>
|
||||
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
|
||||
|
@ -77,43 +72,37 @@
|
|||
|
||||
<dependencies>
|
||||
|
||||
<!-- First declare the APIs we depend on and need for compilation. All
|
||||
of them are provided by JBoss WildFly -->
|
||||
<!-- First declare the APIs we depend on and need for compilation. All of them are provided by JBoss WildFly -->
|
||||
|
||||
<!-- Import the CDI API, we use provided scope as the API is included in
|
||||
JBoss WildFly -->
|
||||
<!-- Import the CDI API, we use provided scope as the API is included in JBoss WildFly -->
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Import the Common Annotations API (JSR-250), we use provided scope
|
||||
as the API is included in JBoss WildFly -->
|
||||
<!-- Import the Common Annotations API (JSR-250), we use provided scope as the API is included in JBoss WildFly -->
|
||||
<dependency>
|
||||
<groupId>org.jboss.spec.javax.annotation</groupId>
|
||||
<artifactId>jboss-annotations-api_1.2_spec</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Import the JAX-RS API, we use provided scope as the API is included
|
||||
in JBoss WildFly -->
|
||||
<!-- Import the JAX-RS API, we use provided scope as the API is included in JBoss WildFly -->
|
||||
<dependency>
|
||||
<groupId>org.jboss.resteasy</groupId>
|
||||
<artifactId>jaxrs-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Import the JPA API, we use provided scope as the API is included in
|
||||
JBoss WildFly -->
|
||||
<!-- Import the JPA API, we use provided scope as the API is included in JBoss WildFly -->
|
||||
<dependency>
|
||||
<groupId>org.hibernate.javax.persistence</groupId>
|
||||
<artifactId>hibernate-jpa-2.1-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Import the EJB API, we use provided scope as the API is included in
|
||||
JBoss WildFly -->
|
||||
<!-- Import the EJB API, we use provided scope as the API is included in JBoss WildFly -->
|
||||
<dependency>
|
||||
<groupId>org.jboss.spec.javax.ejb</groupId>
|
||||
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
|
||||
|
@ -135,8 +124,7 @@
|
|||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- Import the JSF API, we use provided scope as the API is included in
|
||||
JBoss WildFly -->
|
||||
<!-- Import the JSF API, we use provided scope as the API is included in JBoss WildFly -->
|
||||
<dependency>
|
||||
<groupId>org.jboss.spec.javax.faces</groupId>
|
||||
<artifactId>jboss-jsf-api_2.2_spec</artifactId>
|
||||
|
@ -145,16 +133,14 @@
|
|||
|
||||
<!-- Now we declare any tools needed -->
|
||||
|
||||
<!-- Annotation processor to generate the JPA 2.0 metamodel classes for
|
||||
typesafe criteria queries -->
|
||||
<!-- Annotation processor to generate the JPA 2.0 metamodel classes for typesafe criteria queries -->
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-jpamodelgen</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Annotation processor that raising compilation errors whenever constraint
|
||||
annotations are incorrectly used. -->
|
||||
<!-- Annotation processor that raising compilation errors whenever constraint annotations are incorrectly used. -->
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator-annotation-processor</artifactId>
|
||||
|
@ -169,8 +155,7 @@
|
|||
</dependency>
|
||||
|
||||
<!-- Optional, but highly recommended -->
|
||||
<!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA)
|
||||
JPA from JUnit/TestNG -->
|
||||
<!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA) JPA from JUnit/TestNG -->
|
||||
<dependency>
|
||||
<groupId>org.jboss.arquillian.junit</groupId>
|
||||
<artifactId>arquillian-junit-container</artifactId>
|
||||
|
@ -225,8 +210,7 @@
|
|||
</dependencies>
|
||||
|
||||
<build>
|
||||
<!-- Maven will append the version to the finalName (which is the name
|
||||
given to the generated war, and hence the context root) -->
|
||||
<!-- Maven will append the version to the finalName (which is the name given to the generated war, and hence the context root) -->
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -265,10 +249,8 @@
|
|||
|
||||
<profiles>
|
||||
<profile>
|
||||
<!-- The default profile skips all tests, though you can tune it to run
|
||||
just unit tests based on a custom pattern -->
|
||||
<!-- Seperate profiles are provided for running all tests, including Arquillian
|
||||
tests that execute in the specified container -->
|
||||
<!-- The default profile skips all tests, though you can tune it to run just unit tests based on a custom pattern -->
|
||||
<!-- Seperate profiles are provided for running all tests, including Arquillian tests that execute in the specified container -->
|
||||
<id>default</id>
|
||||
<activation>
|
||||
<activeByDefault>true</activeByDefault>
|
||||
|
@ -288,10 +270,8 @@
|
|||
|
||||
<profile>
|
||||
|
||||
<!-- An optional Arquillian testing profile that executes tests
|
||||
in your WildFly instance -->
|
||||
<!-- This profile will start a new WildFly instance, and execute the
|
||||
test, shutting it down when done -->
|
||||
<!-- An optional Arquillian testing profile that executes tests in your WildFly instance -->
|
||||
<!-- This profile will start a new WildFly instance, and execute the test, shutting it down when done -->
|
||||
<!-- Run with: mvn clean test -Parq-wildfly-managed -->
|
||||
<id>arq-wildfly-managed</id>
|
||||
<dependencies>
|
||||
|
|
|
@ -1,15 +1,20 @@
|
|||
<?xml version="1.0"?>
|
||||
<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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>ejb-client</artifactId>
|
||||
<name>ejb-client</name>
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>ejb-client</artifactId>
|
||||
<name>EJB3 Client Maven</name>
|
||||
<description>EJB3 Client Maven</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-surefire-plugin.version>2.19</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
@ -45,10 +50,4 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
|
||||
</properties>
|
||||
</project>
|
|
@ -1,16 +1,18 @@
|
|||
package com.baeldung.ejb.setup.test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
import com.baeldung.ejb.client.EJBClient;
|
||||
import com.baeldung.ejb.tutorial.HelloWorldBean;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class EJBSetupTest {
|
||||
|
||||
@Test
|
||||
public void testEJBClient() {
|
||||
public void EJBClientTest() {
|
||||
EJBClient ejbClient = new EJBClient();
|
||||
HelloWorldBean bean = new HelloWorldBean();
|
||||
assertEquals(bean.getHelloWorld(), ejbClient.getEJBRemoteMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,45 +1,95 @@
|
|||
<?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>
|
||||
<parent>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>ejb-remote</artifactId>
|
||||
<packaging>ejb</packaging>
|
||||
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>
|
||||
|
||||
<!-- <name>ejb-remote</name> -->
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>${javaee-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<parent>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.wildfly.plugins</groupId>
|
||||
<artifactId>wildfly-maven-plugin</artifactId>
|
||||
<version>${wildfly-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<hostname>127.0.0.1</hostname>
|
||||
<port>9990</port>
|
||||
<username>testUser</username>
|
||||
<password>admin1234!</password>
|
||||
<filename>${build.finalName}.jar</filename>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<!-- <finalName>ejb-remote</finalName> -->
|
||||
</build>
|
||||
<artifactId>ejb-remote</artifactId>
|
||||
<packaging>ejb</packaging>
|
||||
|
||||
<properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>${javaee-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<profiles>
|
||||
<!-- mvn clean package cargo:run -->
|
||||
<profile>
|
||||
<id>wildfly-standalone</id>
|
||||
<activation>
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<version>${cargo-maven2-plugin.version}</version>
|
||||
|
||||
<configuration>
|
||||
|
||||
<container>
|
||||
<containerId>wildfly10x</containerId>
|
||||
<zipUrlInstaller>
|
||||
<url>http://download.jboss.org/wildfly/10.1.0.Final/wildfly-10.1.0.Final.zip</url>
|
||||
</zipUrlInstaller>
|
||||
</container>
|
||||
|
||||
<configuration>
|
||||
<properties>
|
||||
<cargo.hostname>127.0.0.1</cargo.hostname>
|
||||
<cargo.jboss.management-http.port>9990</cargo.jboss.management-http.port>
|
||||
<cargo.servlet.users>testUser:admin1234!</cargo.servlet.users>
|
||||
</properties>
|
||||
</configuration>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<!--mvn clean install wildfly:deploy -Pwildfly-runtime-->
|
||||
<profile>
|
||||
<id>wildfly-runtime</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.wildfly.plugins</groupId>
|
||||
<artifactId>wildfly-maven-plugin</artifactId>
|
||||
<version>1.1.0.Alpha5</version>
|
||||
<configuration>
|
||||
<hostname>127.0.0.1</hostname>
|
||||
<port>9990</port>
|
||||
<username>testUser</username>
|
||||
<password>admin1234!</password>
|
||||
<filename>${build.finalName}.jar</filename>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<javaee-api.version>7.0</javaee-api.version>
|
||||
<wildfly-maven-plugin.version>1.1.0.Beta1</wildfly-maven-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
|
||||
|
|
151
ejb/pom.xml
151
ejb/pom.xml
|
@ -1,89 +1,82 @@
|
|||
<?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.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>ejb</name>
|
||||
<description>EJB Tutorial</description>
|
||||
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.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>ejb</name>
|
||||
<description>EJB Tutorial</description>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>jboss-public-repository-group</id>
|
||||
<name>JBoss Public Maven Repository Group</name>
|
||||
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
|
||||
<layout>default</layout>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>never</updatePolicy>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>never</updatePolicy>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>jboss-public-repository-group</id>
|
||||
<name>JBoss Public Maven Repository Group</name>
|
||||
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
|
||||
<layout>default</layout>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>never</updatePolicy>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>never</updatePolicy>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb-remote</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<type>ejb</type>
|
||||
</dependency>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb-remote</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<type>ejb</type>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>${javaee-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>7.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wildfly</groupId>
|
||||
<artifactId>wildfly-ejb-client-bom</artifactId>
|
||||
<version>${wildfly.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<dependency>
|
||||
<groupId>org.wildfly</groupId>
|
||||
<artifactId>wildfly-ejb-client-bom</artifactId>
|
||||
<version>10.1.0.Final</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-ejb-plugin</artifactId>
|
||||
<version>${maven-ejb-plugin.version}</version>
|
||||
<configuration>
|
||||
<ejbVersion>3.2</ejbVersion>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
<plugin>
|
||||
<artifactId>maven-ejb-plugin</artifactId>
|
||||
<version>2.4</version>
|
||||
<configuration>
|
||||
<ejbVersion>3.2</ejbVersion>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<modules>
|
||||
<module>ejb-remote</module>
|
||||
<module>ejb-client</module>
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<javaee-api.version>7.0</javaee-api.version>
|
||||
<wildfly.version>10.1.0.Final</wildfly.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-ejb-plugin.version>2.5.1</maven-ejb-plugin.version>
|
||||
</properties>
|
||||
<modules>
|
||||
<module>ejb-remote</module>
|
||||
<module>ejb-client</module>
|
||||
</modules>
|
||||
</project>
|
|
@ -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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung.enterprise.patterns</groupId>
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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.feign</groupId>
|
||||
|
|
|
@ -0,0 +1,25 @@
|
|||
apply plugin: 'java'
|
||||
apply plugin: 'maven'
|
||||
|
||||
repositories{
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies{
|
||||
compile 'org.springframework:spring-context:4.3.5.RELEASE'
|
||||
}
|
||||
|
||||
task hello {
|
||||
println "this Baeldung's tutorial is ${awesomeness}"
|
||||
}
|
||||
|
||||
uploadArchives {
|
||||
repositories {
|
||||
mavenDeployer {
|
||||
repository(url: 'http://yourmavenrepo/repository') {
|
||||
authentication(userName: 'user', password: 'password');
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
awesomeness=awesome
|
||||
group=com.baeldung.tutorial
|
||||
version=1.0.1
|
Binary file not shown.
|
@ -0,0 +1,6 @@
|
|||
#Sat Dec 31 15:46:08 BRT 2016
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip
|
|
@ -0,0 +1,160 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS=""
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn ( ) {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die ( ) {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
esac
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
|
||||
function splitJvmOpts() {
|
||||
JVM_OPTS=("$@")
|
||||
}
|
||||
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
|
||||
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
|
||||
|
||||
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
|
|
@ -0,0 +1,90 @@
|
|||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windowz variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
if "%@eval[2+2]" == "4" goto 4NT_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
goto execute
|
||||
|
||||
:4NT_args
|
||||
@rem Get arguments from the 4NT Shell from JP Software
|
||||
set CMD_LINE_ARGS=%$
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
|
@ -0,0 +1,5 @@
|
|||
public class Main{
|
||||
public static void main(String[] args){
|
||||
System.out.println("Baeldung Rocks");
|
||||
}
|
||||
}
|
|
@ -92,7 +92,7 @@
|
|||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<guava.version>21.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
|
||||
|
|
|
@ -0,0 +1,63 @@
|
|||
package org.baeldung.guava;
|
||||
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
||||
public class GuavaMultiMapTest {
|
||||
|
||||
@Test
|
||||
public void givenMap_whenAddTwoValuesForSameKey_shouldOverridePreviousKey() {
|
||||
//given
|
||||
String key = "a-key";
|
||||
Map<String, String> map = new LinkedHashMap<>();
|
||||
|
||||
//when
|
||||
map.put(key, "firstValue");
|
||||
map.put(key, "secondValue");
|
||||
|
||||
//then
|
||||
assertEquals(1, map.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiMap_whenAddTwoValuesForSameKey_shouldHaveTwoEntriesInMap() {
|
||||
//given
|
||||
String key = "a-key";
|
||||
Multimap<String, String> map = ArrayListMultimap.create();
|
||||
|
||||
//when
|
||||
map.put(key, "firstValue");
|
||||
map.put(key, "secondValue");
|
||||
|
||||
//then
|
||||
assertEquals(2, map.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapOfListValues_whenAddTwoValuesForSameKey_shouldHaveTwoElementsInList() {
|
||||
//given
|
||||
String key = "a-key";
|
||||
Map<String, List<String>> map = new LinkedHashMap<>();
|
||||
|
||||
//when
|
||||
List<String> values = map.get(key);
|
||||
if(values == null){
|
||||
values = new LinkedList<>();
|
||||
values.add("firstValue");
|
||||
values.add("secondValue");
|
||||
}
|
||||
map.put(key, values);
|
||||
|
||||
//then
|
||||
assertEquals(1, map.size());
|
||||
}
|
||||
}
|
|
@ -8,10 +8,9 @@ import static org.junit.Assert.assertTrue;
|
|||
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
|
||||
import com.google.common.collect.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
|
@ -19,9 +18,6 @@ import com.google.common.base.Function;
|
|||
import com.google.common.base.Joiner;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
public class GuavaStringTest {
|
||||
|
||||
|
|
|
@ -28,13 +28,14 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
|||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
@Ignore("Server is not available")
|
||||
public class HttpClientMultipartLiveTest {
|
||||
|
||||
private static final String SERVER = "http://echo.200please.com";
|
||||
// No longer available
|
||||
// private static final String SERVER = "http://echo.200please.com";
|
||||
|
||||
private static final String SERVER = "http://posttestserver.com/post.php";
|
||||
private static final String TEXTFILENAME = "temp.txt";
|
||||
private static final String IMAGEFILENAME = "image.jpg";
|
||||
private static final String ZIPFILENAME = "zipFile.zip";
|
||||
|
@ -46,7 +47,8 @@ public class HttpClientMultipartLiveTest {
|
|||
|
||||
@Before
|
||||
public final void before() {
|
||||
client = HttpClientBuilder.create().build();
|
||||
client = HttpClientBuilder.create()
|
||||
.build();
|
||||
post = new HttpPost(SERVER);
|
||||
}
|
||||
|
||||
|
@ -80,7 +82,9 @@ public class HttpClientMultipartLiveTest {
|
|||
|
||||
@Test
|
||||
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
|
||||
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME);
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
|
||||
final File file = new File(url.getPath());
|
||||
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
|
||||
|
@ -97,11 +101,12 @@ public class HttpClientMultipartLiveTest {
|
|||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
|
||||
final int statusCode = response.getStatusLine().getStatusCode();
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
|
@ -109,7 +114,9 @@ public class HttpClientMultipartLiveTest {
|
|||
|
||||
@Test
|
||||
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException {
|
||||
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME);
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + TEXTFILENAME);
|
||||
final File file = new File(url.getPath());
|
||||
final String message = "This is a multipart post";
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
|
@ -119,11 +126,12 @@ public class HttpClientMultipartLiveTest {
|
|||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
final int statusCode = response.getStatusLine().getStatusCode();
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
|
@ -131,8 +139,12 @@ public class HttpClientMultipartLiveTest {
|
|||
|
||||
@Test
|
||||
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
|
||||
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + ZIPFILENAME);
|
||||
final URL url2 = Thread.currentThread().getContextClassLoader().getResource("uploads/" + IMAGEFILENAME);
|
||||
final URL url = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + ZIPFILENAME);
|
||||
final URL url2 = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("uploads/" + IMAGEFILENAME);
|
||||
final InputStream inputStream = new FileInputStream(url.getPath());
|
||||
final File file = new File(url2.getPath());
|
||||
final String message = "This is a multipart post";
|
||||
|
@ -144,11 +156,12 @@ public class HttpClientMultipartLiveTest {
|
|||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
final int statusCode = response.getStatusLine().getStatusCode();
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
|
@ -166,11 +179,12 @@ public class HttpClientMultipartLiveTest {
|
|||
final HttpEntity entity = builder.build();
|
||||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
final int statusCode = response.getStatusLine().getStatusCode();
|
||||
final int statusCode = response.getStatusLine()
|
||||
.getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||
System.out.println(responseString);
|
||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||
|
@ -179,7 +193,8 @@ public class HttpClientMultipartLiveTest {
|
|||
// UTIL
|
||||
|
||||
final String getContent() throws IOException {
|
||||
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
|
||||
rd = new BufferedReader(new InputStreamReader(response.getEntity()
|
||||
.getContent()));
|
||||
String body = "";
|
||||
String content = "";
|
||||
while ((body = rd.readLine()) != null) {
|
||||
|
@ -189,7 +204,9 @@ public class HttpClientMultipartLiveTest {
|
|||
}
|
||||
|
||||
final String getContentTypeHeader() throws IOException {
|
||||
return post.getEntity().getContentType().toString();
|
||||
return post.getEntity()
|
||||
.getContentType()
|
||||
.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,11 +1,24 @@
|
|||
package org.baeldung.httpclient;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.conn.ssl.*;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.SSLSocketFactory;
|
||||
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
|
||||
import org.apache.http.conn.ssl.TrustStrategy;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
|
@ -15,14 +28,6 @@ import org.apache.http.ssl.SSLContextBuilder;
|
|||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLException;
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/**
|
||||
* This test requires a localhost server over HTTPS <br>
|
||||
* It should only be manually run, not part of the automated build
|
||||
|
@ -35,13 +40,15 @@ public class HttpsClientSslLiveTest {
|
|||
|
||||
// tests
|
||||
|
||||
@Test(expected = SSLException.class)
|
||||
@Test(expected = SSLHandshakeException.class)
|
||||
public final void whenHttpsUrlIsConsumed_thenException() throws IOException {
|
||||
final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
|
||||
final CloseableHttpClient httpClient = HttpClientBuilder.create()
|
||||
.build();
|
||||
|
||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||
final HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
|
@ -57,7 +64,8 @@ public class HttpsClientSslLiveTest {
|
|||
|
||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||
final HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
|
||||
httpClient.close();
|
||||
}
|
||||
|
@ -65,44 +73,62 @@ public class HttpsClientSslLiveTest {
|
|||
@Test
|
||||
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
|
||||
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
|
||||
final SSLContext sslContext = SSLContexts.custom()
|
||||
.loadTrustMaterial(null, acceptingTrustStrategy)
|
||||
.build();
|
||||
|
||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
|
||||
|
||||
final CloseableHttpClient httpClient = HttpClients.custom().setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLSocketFactory(sslsf).build();
|
||||
final CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
|
||||
.setSSLSocketFactory(sslsf)
|
||||
.build();
|
||||
|
||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||
final HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
|
||||
httpClient.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
|
||||
final SSLContextBuilder builder = new SSLContextBuilder();
|
||||
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
|
||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
|
||||
final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
|
||||
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
|
||||
.build();
|
||||
final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
|
||||
|
||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
|
||||
final CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setSSLHostnameVerifier(hostnameVerifier)
|
||||
.setSSLSocketFactory(sslsf)
|
||||
.build();
|
||||
|
||||
// new
|
||||
|
||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||
final HttpResponse response = httpClient.execute(getMethod);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
httpClient.close();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
|
||||
SSLContext sslContext = new SSLContextBuilder()
|
||||
.loadTrustMaterial(null, (certificate, authType) -> true).build();
|
||||
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true)
|
||||
.build();
|
||||
|
||||
final CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
|
||||
final CloseableHttpClient client = HttpClients.custom()
|
||||
.setSSLContext(sslContext)
|
||||
.setSSLHostnameVerifier(new NoopHostnameVerifier())
|
||||
.build();
|
||||
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
|
||||
httpGet.setHeader("Accept", "application/xml");
|
||||
|
||||
final HttpResponse response = client.execute(httpGet);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
assertThat(response.getStatusLine()
|
||||
.getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Working with Images in Java](http://www.baeldung.com/java-images)
|
|
@ -24,3 +24,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [XML Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-xml-serialization-and-deserialization)
|
||||
- [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations)
|
||||
- [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance)
|
||||
- [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat)
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.jackson.enums;
|
||||
|
||||
import com.baeldung.jackson.serialization.DistanceSerializer;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
/**
|
||||
* Use @JsonFormat to handle representation of Enum as JSON (available since Jackson 2.1.2)
|
||||
* Use @JsonSerialize to configure a custom Jackson serializer
|
||||
*/
|
||||
// @JsonFormat(shape = JsonFormat.Shape.OBJECT)
|
||||
@JsonSerialize(using = DistanceSerializer.class)
|
||||
public enum Distance {
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private final double meters;
|
||||
|
||||
private Distance(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use @JsonValue to control marshalling output for an enum
|
||||
*/
|
||||
// @JsonValue
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage example: Distance.MILE.convertFromMeters(1205.5);
|
||||
*/
|
||||
public double convertFromMeters(double distanceInMeters) {
|
||||
return distanceInMeters / meters;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage example: Distance.MILE.convertToMeters(0.5);
|
||||
*/
|
||||
public double convertToMeters(double distanceInMeters) {
|
||||
return distanceInMeters * meters;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.jackson.inheritance;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "eventType")
|
||||
abstract public class Event {
|
||||
private final String id;
|
||||
private final Long timestamp;
|
||||
|
||||
@JsonCreator
|
||||
public Event(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp) {
|
||||
this.id = id;
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public Long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.jackson.inheritance;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
|
||||
@JsonTypeName("itemIdAddedToUser")
|
||||
@JsonIgnoreProperties("id")
|
||||
public class ItemIdAddedToUser extends Event {
|
||||
private final String itemId;
|
||||
private final Long quantity;
|
||||
|
||||
@JsonCreator
|
||||
public ItemIdAddedToUser(@JsonProperty("id") String id,
|
||||
@JsonProperty("timestamp") Long timestamp,
|
||||
@JsonProperty("itemId") String itemId,
|
||||
@JsonProperty("quantity") Long quantity) {
|
||||
super(id, timestamp);
|
||||
this.itemId = itemId;
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public String getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
public Long getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.jackson.inheritance;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
|
||||
@JsonTypeName("itemIdRemovedFromUser")
|
||||
public class ItemIdRemovedFromUser extends Event {
|
||||
private final String itemId;
|
||||
private final Long quantity;
|
||||
|
||||
@JsonCreator
|
||||
public ItemIdRemovedFromUser(@JsonProperty("id") String id,
|
||||
@JsonProperty("timestamp") Long timestamp,
|
||||
@JsonProperty("itemId") String itemId,
|
||||
@JsonProperty("quantity") Long quantity) {
|
||||
super(id, timestamp);
|
||||
this.itemId = itemId;
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public String getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
public Long getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.jackson.serialization;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.enums.Distance;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class DistanceSerializer extends StdSerializer<Distance> {
|
||||
|
||||
private static final long serialVersionUID = 1376504304439963619L;
|
||||
|
||||
public DistanceSerializer() {
|
||||
super(Distance.class);
|
||||
}
|
||||
|
||||
public DistanceSerializer(Class<Distance> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
public void serialize(Distance distance, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
generator.writeStartObject();
|
||||
generator.writeFieldName("name");
|
||||
generator.writeNumber(distance.name());
|
||||
generator.writeFieldName("unit");
|
||||
generator.writeString(distance.getUnit());
|
||||
generator.writeFieldName("meters");
|
||||
generator.writeNumber(distance.getMeters());
|
||||
generator.writeEndObject();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.jackson.dtos.withEnum;
|
||||
|
||||
public enum DistanceEnumSimple {
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private final double meters;
|
||||
|
||||
private DistanceEnumSimple(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.jackson.dtos.withEnum;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
|
||||
public enum DistanceEnumWithJsonFormat {
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private final double meters;
|
||||
|
||||
private DistanceEnumWithJsonFormat(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue