Merge branch 'master' into pr/1014-stephen

This commit is contained in:
slavisa-baeldung 2017-01-20 08:21:36 +01:00
commit 444c475d7c
319 changed files with 8386 additions and 1351 deletions

63
JGit/pom.xml Normal file
View File

@ -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>

View File

@ -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);
}
}

View File

@ -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();
}
}
}

View File

@ -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;
}
}

View File

@ -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());
}
}
}
}

View File

@ -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());
}
}
}
}

View File

@ -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();
}
}
}
}
}

View File

@ -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");
}
}
}
}

View File

@ -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);
}
}
}
}
}

View File

@ -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);
}
}

44
algorithms/pom.xml Normal file
View File

@ -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>

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}
}
}

View File

@ -1,7 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -5,20 +5,20 @@
<artifactId>apache-cxf</artifactId> <artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<modules> <modules>
<module>cxf-introduction</module> <module>cxf-introduction</module>
<module>cxf-spring</module> <module>cxf-spring</module>
<module>cxf-jaxrs-implementation</module> <module>cxf-jaxrs-implementation</module>
<module>cxf-aegis</module> <module>cxf-aegis</module>
</modules> </modules>
<properties> <properties>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version> <exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
@ -27,7 +27,7 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<defaultGoal>install</defaultGoal> <defaultGoal>install</defaultGoal>
<pluginManagement> <pluginManagement>

View File

@ -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"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<modelVersion>4.0.0</modelVersion> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>com.baeldung</groupId> <modelVersion>4.0.0</modelVersion>
<artifactId>apache-fop</artifactId> <groupId>com.baeldung</groupId>
<version>0.1-SNAPSHOT</version> <artifactId>apache-fop</artifactId>
<version>0.1-SNAPSHOT</version>
<name>apache-fop</name> <name>apache-fop</name>
<dependencies> <dependencies>
<!-- logging --> <!-- logging -->
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version> <version>${org.slf4j.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>ch.qos.logback</groupId> <groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId> <artifactId>logback-classic</artifactId>
<version>${logback.version}</version> <version>${logback.version}</version>
<!-- <scope>runtime</scope> --> <!-- <scope>runtime</scope> -->
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId> <artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version> <version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl --> <!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency> </dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly --> <dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId> <artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version> <version>${org.slf4j.version}</version>
</dependency> </dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${junit.version}</version> <version>${junit.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId> <artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version> <version>${org.hamcrest.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId> <artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version> <version>${org.hamcrest.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>
<version>${mockito.version}</version> <version>${mockito.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- new dependencies --> <!-- new dependencies -->
<dependency> <dependency>
<groupId>org.apache.xmlgraphics</groupId> <groupId>org.apache.xmlgraphics</groupId>
<artifactId>fop</artifactId> <artifactId>fop</artifactId>
<version>${fop.version}</version> <version>${fop.version}</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>org.apache.avalon.framework</groupId> <groupId>org.apache.avalon.framework</groupId>
<artifactId>avalon-framework-api</artifactId> <artifactId>avalon-framework-api</artifactId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<groupId>org.apache.avalon.framework</groupId> <groupId>org.apache.avalon.framework</groupId>
<artifactId>avalon-framework-impl</artifactId> <artifactId>avalon-framework-impl</artifactId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>avalon-framework</groupId> <groupId>avalon-framework</groupId>
<artifactId>avalon-framework-api</artifactId> <artifactId>avalon-framework-api</artifactId>
<version>${avalon-framework.version}</version> <version>${avalon-framework.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>avalon-framework</groupId> <groupId>avalon-framework</groupId>
<artifactId>avalon-framework-impl</artifactId> <artifactId>avalon-framework-impl</artifactId>
<version>${avalon-framework.version}</version> <version>${avalon-framework.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.dbdoclet</groupId> <groupId>org.dbdoclet</groupId>
<artifactId>dbdoclet</artifactId> <artifactId>dbdoclet</artifactId>
<version>${dbdoclet.version}</version> <version>${dbdoclet.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.dbdoclet</groupId> <groupId>org.dbdoclet</groupId>
<artifactId>herold</artifactId> <artifactId>herold</artifactId>
<version>6.1.0</version> <version>6.1.0</version>
<scope>system</scope> <scope>system</scope>
<systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath> <systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath>
</dependency> </dependency>
<dependency>
<groupId>net.sf.jtidy</groupId>
<artifactId>jtidy</artifactId>
<version>${jtidy.version}</version>
</dependency>
</dependencies> <dependency>
<groupId>net.sf.jtidy</groupId>
<artifactId>jtidy</artifactId>
<version>${jtidy.version}</version>
</dependency>
<build> </dependencies>
<finalName>apache-fop</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins> <build>
<finalName>apache-fop</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugin> <plugins>
<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> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version> <version>${maven-compiler-plugin.version}</version>
<configuration> <configuration>
<excludes> <source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude> <exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude> <exclude>**/*LiveTest.java</exclude>
</excludes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles> <profiles>
<profile> <profile>
@ -170,7 +171,7 @@
</excludes> </excludes>
<includes> <includes>
<include>**/*IntegrationTest.java</include> <include>**/*IntegrationTest.java</include>
<exclude>**/*LiveTest.java</exclude> <exclude>**/*LiveTest.java</exclude>
</includes> </includes>
</configuration> </configuration>
</execution> </execution>
@ -185,25 +186,25 @@
</build> </build>
</profile> </profile>
</profiles> </profiles>
<properties>
<fop.version>1.1</fop.version>
<avalon-framework.version>4.3</avalon-framework.version>
<dbdoclet.version>8.0.2</dbdoclet.version>
<jtidy.version>r938</jtidy.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- testing --> <properties>
<org.hamcrest.version>1.3</org.hamcrest.version> <fop.version>1.1</fop.version>
<junit.version>4.12</junit.version> <avalon-framework.version>4.3</avalon-framework.version>
<mockito.version>1.10.19</mockito.version> <dbdoclet.version>8.0.2</dbdoclet.version>
<jtidy.version>r938</jtidy.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- maven plugins --> <!-- testing -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> <org.hamcrest.version>1.3</org.hamcrest.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version> <junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
</properties> <!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project> </project>

2
apache-poi/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)

3
aspectj/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Intro to AspectJ](http://www.baeldung.com/aspectj)
- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging)

View File

@ -12,39 +12,69 @@
<artifactId>aspectjrt</artifactId> <artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version> <version>${aspectj.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.aspectj</groupId> <groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId> <artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version> <version>${aspectj.version}</version>
</dependency> </dependency>
<!-- utils --> <!-- utils -->
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version> <version>${org.slf4j.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>ch.qos.logback</groupId> <groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId> <artifactId>logback-classic</artifactId>
<version>${logback.version}</version> <version>${logback.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>ch.qos.logback</groupId> <groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId> <artifactId>logback-core</artifactId>
<version>${logback.version}</version> <version>${logback.version}</version>
</dependency> </dependency>
<!-- unit test --> <!-- unit test -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${junit.version}</version> <version>${junit.version}</version>
</dependency> </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> </dependencies>
<build> <build>
@ -65,9 +95,9 @@
<source>${source.version}</source> <source>${source.version}</source>
<target>${source.version}</target> <target>${source.version}</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId> <artifactId>aspectj-maven-plugin</artifactId>
@ -81,41 +111,22 @@
<Xlint>ignore</Xlint> <Xlint>ignore</Xlint>
<encoding>${project.build.sourceEncoding}</encoding> <encoding>${project.build.sourceEncoding}</encoding>
<!-- Post-compile weaving --> <!-- Post-compile weaving -->
<!-- <!-- <weaveDependencies> <weaveDependency> <groupId>org.agroup</groupId> <artifactId>to-weave</artifactId> </weaveDependency>
<weaveDependencies> <weaveDependency> <groupId>org.anothergroup</groupId> <artifactId>gen</artifactId> </weaveDependency> </weaveDependencies> -->
<weaveDependency> </configuration>
<groupId>org.agroup</groupId>
<artifactId>to-weave</artifactId>
</weaveDependency>
<weaveDependency>
<groupId>org.anothergroup</groupId>
<artifactId>gen</artifactId>
</weaveDependency>
</weaveDependencies>
-->
</configuration>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>compile</goal> <goal>compile</goal>
<goal>test-compile</goal> <goal>test-compile</goal>
</goals> </goals>
</execution> </execution>
</executions> </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>
-->
<!-- <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> </plugins>
</build> </build>

View File

@ -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());
}
}

View File

@ -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!");
}
}
}
}

View File

@ -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));
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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

View File

@ -54,8 +54,8 @@
<assertj-guava.version>3.1.0</assertj-guava.version> <assertj-guava.version>3.1.0</assertj-guava.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<assertj-core.version>3.6.1</assertj-core.version> <assertj-core.version>3.6.1</assertj-core.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -41,5 +41,5 @@
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties> </properties>
</project> </project>

1
aws/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target/

View File

@ -2,10 +2,10 @@
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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>aws-lambda</artifactId> <artifactId>aws</artifactId>
<version>0.1.0-SNAPSHOT</version> <version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>aws-lambda</name> <name>aws</name>
<dependencies> <dependencies>
<dependency> <dependency>

View File

@ -1,4 +1,4 @@
package com.baeldung; package com.baeldung.lambda;
import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.Context;

View File

@ -1,4 +1,4 @@
package com.baeldung; package com.baeldung.lambda;
import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.RequestHandler;

View File

@ -1,7 +1,6 @@
package com.baeldung; package com.baeldung.lambda;
import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler; import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;

View File

@ -45,7 +45,7 @@
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@ -61,7 +61,7 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles> <profiles>
<profile> <profile>
<id>integration</id> <id>integration</id>
@ -101,7 +101,7 @@
<aspectjweaver.version>1.8.9</aspectjweaver.version> <aspectjweaver.version>1.8.9</aspectjweaver.version>
<weld-se-core.version>2.4.1.Final</weld-se-core.version> <weld-se-core.version>2.4.1.Final</weld-se-core.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -1,91 +1,88 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
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>
<modelVersion>4.0.0</modelVersion> <groupId>com.baeldung</groupId>
<groupId>com.baeldung</groupId> <artifactId>core-java9</artifactId>
<artifactId>core-java9</artifactId> <version>0.2-SNAPSHOT</version>
<version>0.2-SNAPSHOT</version>
<name>core-java9</name> <name>core-java9</name>
<pluginRepositories> <pluginRepositories>
<pluginRepository> <pluginRepository>
<id>apache.snapshots</id> <id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url> <url>http://repository.apache.org/snapshots/</url>
</pluginRepository> </pluginRepository>
</pluginRepositories> </pluginRepositories>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version> <version>${org.slf4j.version}</version>
</dependency> </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> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.mockito</groupId>
<artifactId>hamcrest-library</artifactId> <artifactId>mockito-core</artifactId>
<version>${org.hamcrest.version}</version> <version>${mockito.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> </dependencies>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency> <build>
<groupId>org.mockito</groupId> <finalName>core-java-9</finalName>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies> <plugins>
<build> <plugin>
<finalName>core-java-9</finalName> <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> </plugins>
<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>
<plugin> </build>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</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> <!-- testing -->
<!-- logging --> <org.hamcrest.version>1.3</org.hamcrest.version>
<org.slf4j.version>1.7.21</org.slf4j.version> <junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<!-- maven plugins --> </properties>
<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>
</project> </project>

View File

@ -16,3 +16,7 @@
*.txt *.txt
/bin/ /bin/
/temp /temp
#IntelliJ specific
.idea
*.iml

View File

@ -46,3 +46,11 @@
- [Grep in Java](http://www.baeldung.com/grep-in-java) - [Grep in Java](http://www.baeldung.com/grep-in-java)
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections) - [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) - [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)

View File

@ -63,6 +63,12 @@
<artifactId>grep4j</artifactId> <artifactId>grep4j</artifactId>
<version>${grep4j.version}</version> <version>${grep4j.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>${disruptor.version}</version>
</dependency>
<!-- web --> <!-- web -->
<!-- marshalling --> <!-- marshalling -->
@ -352,7 +358,7 @@
<logback.version>1.1.7</logback.version> <logback.version>1.1.7</logback.version>
<!-- util --> <!-- util -->
<guava.version>19.0</guava.version> <guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version> <bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version> <commons-codec.version>1.10</commons-codec.version>
@ -363,6 +369,7 @@
<unix4j.version>0.4</unix4j.version> <unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version> <grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.16.12</lombok.version> <lombok.version>1.16.12</lombok.version>
<disruptor.version>3.3.6</disruptor.version>
<!-- testing --> <!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version> <org.hamcrest.version>1.3</org.hamcrest.version>

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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
}
}
}

View File

@ -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();
}

View File

@ -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);
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}
};
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.java8.lambda.exceptions;
@FunctionalInterface
public interface ThrowingConsumer<T, E extends Exception> {
void accept(T t) throws E;
}

View File

@ -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);
}
}

View File

@ -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);

View File

@ -0,0 +1 @@
print(__FILE__, __LINE__, __DIR__);

View File

@ -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;

View File

@ -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;

View File

@ -0,0 +1 @@
function increment(num) ++num;

View File

@ -0,0 +1,2 @@
print(" hello world".trimLeft());
print("hello world ".trimRight());

View File

@ -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]);

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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));
}
}

View File

@ -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"));
}
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)

View File

@ -1,3 +1,11 @@
### Relevant Articles: ### Relevant Articles:
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api) - [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) - [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)

View File

@ -7,8 +7,10 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.anyOf;
import static org.junit.Assert.*; import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class Java8FindAnyFindFirstTest { public class Java8FindAnyFindFirstTest {

View File

@ -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
}
}
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)

View File

@ -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);
}
}

View File

@ -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)

View File

@ -1,38 +1,26 @@
package org.baeldung.java.io; package org.baeldung.java.io;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.common.io.ByteSource; import com.google.common.io.ByteSource;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams; import com.google.common.io.CharStreams;
import com.google.common.io.Files; import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class JavaInputStreamToXUnitTest { public class JavaInputStreamToXUnitTest {
@ -163,7 +151,7 @@ public class JavaInputStreamToXUnitTest {
// tests - InputStream to File // tests - InputStream to File
@Test @Test
public final void givenUsingPlainJava_whenConvertingAnFullInputStreamToAFile_thenCorrect() throws IOException { public final void whenConvertingToFile_thenCorrect() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
final byte[] buffer = new byte[initialStream.available()]; final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer); initialStream.read(buffer);
@ -177,7 +165,7 @@ public class JavaInputStreamToXUnitTest {
} }
@Test @Test
public final void givenUsingPlainJava_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException { public final void whenConvertingInProgressToFile_thenCorrect() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
final File targetFile = new File("src/main/resources/targetFile.tmp"); final File targetFile = new File("src/main/resources/targetFile.tmp");
final OutputStream outStream = new FileOutputStream(targetFile); final OutputStream outStream = new FileOutputStream(targetFile);
@ -193,7 +181,7 @@ public class JavaInputStreamToXUnitTest {
} }
@Test @Test
public final void givenUsingPlainJava8_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException { public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
final File targetFile = new File("src/main/resources/targetFile.tmp"); final File targetFile = new File("src/main/resources/targetFile.tmp");
@ -203,7 +191,7 @@ public class JavaInputStreamToXUnitTest {
} }
@Test @Test
public final void givenUsingGuava_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException { public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
final byte[] buffer = new byte[initialStream.available()]; final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer); initialStream.read(buffer);
@ -215,7 +203,7 @@ public class JavaInputStreamToXUnitTest {
} }
@Test @Test
public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException { public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException {
final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt")); final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
final File targetFile = new File("src/main/resources/targetFile.tmp"); final File targetFile = new File("src/main/resources/targetFile.tmp");

View File

@ -1,91 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <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"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>couchbase-sdk</artifactId> <artifactId>couchbase-sdk</artifactId>
<version>0.1-SNAPSHOT</version> <version>0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>couchbase-sdk</name> <name>couchbase-sdk</name>
<description>Couchbase SDK Tutorials</description> <description>Couchbase SDK Tutorials</description>
<dependencies> <dependencies>
<!-- Couchbase SDK --> <!-- Couchbase SDK -->
<dependency> <dependency>
<groupId>com.couchbase.client</groupId> <groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId> <artifactId>java-client</artifactId>
<version>${couchbase.client.version}</version> <version>${couchbase.client.version}</version>
</dependency> </dependency>
<!-- Spring Context for Dependency Injection --> <!-- Spring Context for Dependency Injection -->
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId> <artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version> <version>${spring-framework.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId> <artifactId>spring-context-support</artifactId>
<version>${spring-framework.version}</version> <version>${spring-framework.version}</version>
</dependency> </dependency>
<!-- Logging with SLF4J & LogBack --> <!-- Logging with SLF4J & LogBack -->
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version> <version>${org.slf4j.version}</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>ch.qos.logback</groupId> <groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId> <artifactId>logback-classic</artifactId>
<version>${logback.version}</version> <version>${logback.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId> <artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version> <version>${org.slf4j.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId> <artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version> <version>${org.slf4j.version}</version>
</dependency> </dependency>
<!-- Test-Scoped Dependencies --> <!-- Test-Scoped Dependencies -->
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId> <artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version> <version>${spring-framework.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${junit.version}</version> <version>${junit.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </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>
<build> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<plugins> <dependency>
<plugin> <groupId>org.apache.commons</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>commons-lang3</artifactId>
<version>${maven-compiler-plugin.version}</version> <version>${commons-lang3.version}</version>
<configuration> <scope>test</scope>
<source>${java.version}</source> </dependency>
<target>${java.version}</target> </dependencies>
</configuration>
</plugin> <build>
<plugin> <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> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version> <version>${maven-surefire-plugin.version}</version>
@ -96,20 +96,20 @@
</excludes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<properties> <properties>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<couchbase.client.version>2.3.6</couchbase.client.version> <couchbase.client.version>2.3.6</couchbase.client.version>
<spring-framework.version>4.3.4.RELEASE</spring-framework.version> <spring-framework.version>4.3.4.RELEASE</spring-framework.version>
<logback.version>1.1.7</logback.version> <logback.version>1.1.7</logback.version>
<org.slf4j.version>1.7.21</org.slf4j.version> <org.slf4j.version>1.7.21</org.slf4j.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>deltaspike</artifactId> <artifactId>deltaspike</artifactId>
@ -19,21 +19,19 @@
</licenses> </licenses>
<properties> <properties>
<!-- Explicitly declaring the source encoding eliminates the following <!-- Explicitly declaring the source encoding eliminates the following message: -->
message: --> <!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! -->
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered <project.build.sourceEncoding>
resources, i.e. build is platform dependent! --> UTF-8</project.build.sourceEncoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<slf4j.version>1.7.21</slf4j.version> <slf4j.version>1.7.21</slf4j.version>
<querydsl.version>3.7.4</querydsl.version> <querydsl.version>3.7.4</querydsl.version>
<deltaspike.version>1.7.2</deltaspike.version> <deltaspike.version>1.7.2</deltaspike.version>
<!-- JBoss dependency versions --> <!-- JBoss dependency versions -->
<wildfly.maven.plugin.version>1.0.2.Final</wildfly.maven.plugin.version> <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 <!-- Define the version of the JBoss BOMs we want to import to specify tested stacks. -->
tested stacks. -->
<jboss.bom.version>8.2.2.Final</jboss.bom.version> <jboss.bom.version>8.2.2.Final</jboss.bom.version>
<!-- other plugin versions --> <!-- other plugin versions -->
@ -50,14 +48,11 @@
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill <!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill of Materials (BOM). A BOM specifies the versions of a "stack"
of Materials (BOM). A BOM specifies the versions of a "stack" (or a collection) (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
of artifacts. We use this here so that we always get the correct versions 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
of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you can 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
read this as the JBoss stack of the Java EE 7 APIs, with some extras tools projects) -->
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> <dependency>
<groupId>org.wildfly.bom</groupId> <groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-tools</artifactId> <artifactId>jboss-javaee-7.0-with-tools</artifactId>
@ -77,43 +72,37 @@
<dependencies> <dependencies>
<!-- First declare the APIs we depend on and need for compilation. All <!-- First declare the APIs we depend on and need for compilation. All of them are provided by JBoss WildFly -->
of them are provided by JBoss WildFly -->
<!-- Import the CDI API, we use provided scope as the API is included in <!-- Import the CDI API, we use provided scope as the API is included in JBoss WildFly -->
JBoss WildFly -->
<dependency> <dependency>
<groupId>javax.enterprise</groupId> <groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId> <artifactId>cdi-api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- Import the Common Annotations API (JSR-250), we use provided scope <!-- Import the Common Annotations API (JSR-250), we use provided scope as the API is included in JBoss WildFly -->
as the API is included in JBoss WildFly -->
<dependency> <dependency>
<groupId>org.jboss.spec.javax.annotation</groupId> <groupId>org.jboss.spec.javax.annotation</groupId>
<artifactId>jboss-annotations-api_1.2_spec</artifactId> <artifactId>jboss-annotations-api_1.2_spec</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- Import the JAX-RS API, we use provided scope as the API is included <!-- Import the JAX-RS API, we use provided scope as the API is included in JBoss WildFly -->
in JBoss WildFly -->
<dependency> <dependency>
<groupId>org.jboss.resteasy</groupId> <groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId> <artifactId>jaxrs-api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- Import the JPA API, we use provided scope as the API is included in <!-- Import the JPA API, we use provided scope as the API is included in JBoss WildFly -->
JBoss WildFly -->
<dependency> <dependency>
<groupId>org.hibernate.javax.persistence</groupId> <groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId> <artifactId>hibernate-jpa-2.1-api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- Import the EJB API, we use provided scope as the API is included in <!-- Import the EJB API, we use provided scope as the API is included in JBoss WildFly -->
JBoss WildFly -->
<dependency> <dependency>
<groupId>org.jboss.spec.javax.ejb</groupId> <groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId> <artifactId>jboss-ejb-api_3.2_spec</artifactId>
@ -135,8 +124,7 @@
</exclusions> </exclusions>
</dependency> </dependency>
<!-- Import the JSF API, we use provided scope as the API is included in <!-- Import the JSF API, we use provided scope as the API is included in JBoss WildFly -->
JBoss WildFly -->
<dependency> <dependency>
<groupId>org.jboss.spec.javax.faces</groupId> <groupId>org.jboss.spec.javax.faces</groupId>
<artifactId>jboss-jsf-api_2.2_spec</artifactId> <artifactId>jboss-jsf-api_2.2_spec</artifactId>
@ -145,16 +133,14 @@
<!-- Now we declare any tools needed --> <!-- Now we declare any tools needed -->
<!-- Annotation processor to generate the JPA 2.0 metamodel classes for <!-- Annotation processor to generate the JPA 2.0 metamodel classes for typesafe criteria queries -->
typesafe criteria queries -->
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId> <artifactId>hibernate-jpamodelgen</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- Annotation processor that raising compilation errors whenever constraint <!-- Annotation processor that raising compilation errors whenever constraint annotations are incorrectly used. -->
annotations are incorrectly used. -->
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId> <artifactId>hibernate-validator-annotation-processor</artifactId>
@ -169,8 +155,7 @@
</dependency> </dependency>
<!-- Optional, but highly recommended --> <!-- Optional, but highly recommended -->
<!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA) <!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA) JPA from JUnit/TestNG -->
JPA from JUnit/TestNG -->
<dependency> <dependency>
<groupId>org.jboss.arquillian.junit</groupId> <groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId> <artifactId>arquillian-junit-container</artifactId>
@ -225,8 +210,7 @@
</dependencies> </dependencies>
<build> <build>
<!-- Maven will append the version to the finalName (which is the name <!-- Maven will append the version to the finalName (which is the name given to the generated war, and hence the context root) -->
given to the generated war, and hence the context root) -->
<finalName>${project.artifactId}</finalName> <finalName>${project.artifactId}</finalName>
<plugins> <plugins>
<plugin> <plugin>
@ -265,10 +249,8 @@
<profiles> <profiles>
<profile> <profile>
<!-- The default profile skips all tests, though you can tune it to run <!-- The default profile skips all tests, though you can tune it to run just unit tests based on a custom pattern -->
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 -->
<!-- Seperate profiles are provided for running all tests, including Arquillian
tests that execute in the specified container -->
<id>default</id> <id>default</id>
<activation> <activation>
<activeByDefault>true</activeByDefault> <activeByDefault>true</activeByDefault>
@ -288,10 +270,8 @@
<profile> <profile>
<!-- An optional Arquillian testing profile that executes tests <!-- An optional Arquillian testing profile that executes tests in your WildFly instance -->
in your WildFly instance --> <!-- This profile will start a new WildFly instance, and execute the test, shutting it down when done -->
<!-- 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 --> <!-- Run with: mvn clean test -Parq-wildfly-managed -->
<id>arq-wildfly-managed</id> <id>arq-wildfly-managed</id>
<dependencies> <dependencies>

View File

@ -1,11 +1,11 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>dozer</artifactId> <artifactId>dozer</artifactId>
<version>1.0</version> <version>1.0</version>
<name>dozer</name> <name>dozer</name>
<build> <build>
@ -54,7 +54,7 @@
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<slf4j.version>1.7.21</slf4j.version> <slf4j.version>1.7.21</slf4j.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
@ -62,5 +62,5 @@
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -1,16 +1,21 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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> <modelVersion>4.0.0</modelVersion>
<artifactId>ejb-client</artifactId> <parent>
<name>ejb-client</name> <groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<parent> <version>1.0-SNAPSHOT</version>
<groupId>com.baeldung.ejb</groupId> </parent>
<artifactId>ejb</artifactId> <artifactId>ejb-client</artifactId>
<version>1.0-SNAPSHOT</version> <name>EJB3 Client Maven</name>
</parent> <description>EJB3 Client Maven</description>
<properties>
<junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19</maven-surefire-plugin.version>
</properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.wildfly</groupId> <groupId>org.wildfly</groupId>
@ -45,10 +50,4 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<properties>
<junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project> </project>

View File

@ -1,16 +1,18 @@
package com.baeldung.ejb.setup.test; 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.client.EJBClient;
import com.baeldung.ejb.tutorial.HelloWorldBean; import com.baeldung.ejb.tutorial.HelloWorldBean;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class EJBSetupTest { public class EJBSetupTest {
@Test @Test
public void testEJBClient() { public void EJBClientTest() {
EJBClient ejbClient = new EJBClient(); EJBClient ejbClient = new EJBClient();
HelloWorldBean bean = new HelloWorldBean(); HelloWorldBean bean = new HelloWorldBean();
assertEquals(bean.getHelloWorld(), ejbClient.getEJBRemoteMessage()); assertEquals(bean.getHelloWorld(), ejbClient.getEJBRemoteMessage());
} }
} }

View File

@ -1,45 +1,95 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <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"> 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> <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>
<!-- <name>ejb-remote</name> --> <parent>
<dependencies> <groupId>com.baeldung.ejb</groupId>
<dependency> <artifactId>ejb</artifactId>
<groupId>javax</groupId> <version>1.0-SNAPSHOT</version>
<artifactId>javaee-api</artifactId> </parent>
<version>${javaee-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build> <artifactId>ejb-remote</artifactId>
<plugins> <packaging>ejb</packaging>
<plugin>
<groupId>org.wildfly.plugins</groupId> <dependencies>
<artifactId>wildfly-maven-plugin</artifactId> <dependency>
<version>${wildfly-maven-plugin.version}</version> <groupId>javax</groupId>
<configuration> <artifactId>javaee-api</artifactId>
<hostname>127.0.0.1</hostname> <version>${javaee-api.version}</version>
<port>9990</port> <scope>provided</scope>
<username>testUser</username> </dependency>
<password>admin1234!</password> </dependencies>
<filename>${build.finalName}.jar</filename>
</configuration>
</plugin> <profiles>
</plugins> <!-- mvn clean package cargo:run -->
<!-- <finalName>ejb-remote</finalName> --> <profile>
</build> <id>wildfly-standalone</id>
<activation>
<properties> <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> <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> </properties>
</project>
</project>

View File

@ -1,89 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <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"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.ejb</groupId> <groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId> <artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>ejb</name> <name>ejb</name>
<description>EJB Tutorial</description> <description>EJB Tutorial</description>
<repositories> <repositories>
<repository> <repository>
<id>jboss-public-repository-group</id> <id>jboss-public-repository-group</id>
<name>JBoss Public Maven Repository Group</name> <name>JBoss Public Maven Repository Group</name>
<url>http://repository.jboss.org/nexus/content/groups/public/</url> <url>http://repository.jboss.org/nexus/content/groups/public/</url>
<layout>default</layout> <layout>default</layout>
<releases> <releases>
<enabled>true</enabled> <enabled>true</enabled>
<updatePolicy>never</updatePolicy> <updatePolicy>never</updatePolicy>
</releases> </releases>
<snapshots> <snapshots>
<enabled>true</enabled> <enabled>true</enabled>
<updatePolicy>never</updatePolicy> <updatePolicy>never</updatePolicy>
</snapshots> </snapshots>
</repository> </repository>
</repositories> </repositories>
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.baeldung.ejb</groupId> <groupId>com.baeldung.ejb</groupId>
<artifactId>ejb-remote</artifactId> <artifactId>ejb-remote</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<type>ejb</type> <type>ejb</type>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax</groupId> <groupId>javax</groupId>
<artifactId>javaee-api</artifactId> <artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version> <version>7.0</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wildfly</groupId> <groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId> <artifactId>wildfly-ejb-client-bom</artifactId>
<version>${wildfly.version}</version> <version>10.1.0.Final</version>
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
<build> <build>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version> <version>3.1</version>
<configuration> <configuration>
<source>1.8</source> <source>1.8</source>
<target>1.8</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-ejb-plugin</artifactId> <artifactId>maven-ejb-plugin</artifactId>
<version>${maven-ejb-plugin.version}</version> <version>2.4</version>
<configuration> <configuration>
<ejbVersion>3.2</ejbVersion> <ejbVersion>3.2</ejbVersion>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</pluginManagement> </pluginManagement>
</build> </build>
<modules> <modules>
<module>ejb-remote</module> <module>ejb-remote</module>
<module>ejb-client</module> <module>ejb-client</module>
</modules> </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>
</project> </project>

View File

@ -1,7 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.enterprise.patterns</groupId> <groupId>com.baeldung.enterprise.patterns</groupId>
@ -32,7 +31,7 @@
</plugins> </plugins>
</pluginManagement> </pluginManagement>
</build> </build>
<properties> <properties>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties> </properties>

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.feign</groupId> <groupId>com.baeldung.feign</groupId>

25
gradle/build.gradle Normal file
View File

@ -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');
}
}
}
}

3
gradle/gradle.properties Normal file
View File

@ -0,0 +1,3 @@
awesomeness=awesome
group=com.baeldung.tutorial
version=1.0.1

BIN
gradle/gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -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

160
gradle/gradlew vendored Normal file
View File

@ -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 "$@"

90
gradle/gradlew.bat vendored Normal file
View File

@ -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

View File

@ -0,0 +1,5 @@
public class Main{
public static void main(String[] args){
System.out.println("Baeldung Rocks");
}
}

View File

@ -92,7 +92,7 @@
<properties> <properties>
<!-- util --> <!-- util -->
<guava.version>19.0</guava.version> <guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version> <commons-collections4.version>4.1</commons-collections4.version>

View File

@ -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());
}
}

View File

@ -8,10 +8,9 @@ import static org.junit.Assert.assertTrue;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder; import java.nio.charset.CharsetEncoder;
import java.util.ArrayList; import java.util.*;
import java.util.List;
import java.util.Map;
import com.google.common.collect.*;
import org.junit.Test; import org.junit.Test;
import com.google.common.base.CharMatcher; 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.Joiner;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Splitter; 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 { public class GuavaStringTest {

View File

@ -28,13 +28,14 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
@Ignore("Server is not available")
public class HttpClientMultipartLiveTest { 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 TEXTFILENAME = "temp.txt";
private static final String IMAGEFILENAME = "image.jpg"; private static final String IMAGEFILENAME = "image.jpg";
private static final String ZIPFILENAME = "zipFile.zip"; private static final String ZIPFILENAME = "zipFile.zip";
@ -46,7 +47,8 @@ public class HttpClientMultipartLiveTest {
@Before @Before
public final void before() { public final void before() {
client = HttpClientBuilder.create().build(); client = HttpClientBuilder.create()
.build();
post = new HttpPost(SERVER); post = new HttpPost(SERVER);
} }
@ -80,7 +82,9 @@ public class HttpClientMultipartLiveTest {
@Test @Test
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { 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 File file = new File(url.getPath());
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
@ -97,11 +101,12 @@ public class HttpClientMultipartLiveTest {
post.setEntity(entity); post.setEntity(entity);
response = client.execute(post); response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode(); final int statusCode = response.getStatusLine()
.getStatusCode();
final String responseString = getContent(); final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); 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;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString); System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader); System.out.println("POST Content Type: " + contentTypeInHeader);
@ -109,7 +114,9 @@ public class HttpClientMultipartLiveTest {
@Test @Test
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException { 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 File file = new File(url.getPath());
final String message = "This is a multipart post"; final String message = "This is a multipart post";
final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
@ -119,11 +126,12 @@ public class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
response = client.execute(post); response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode(); final int statusCode = response.getStatusLine()
.getStatusCode();
final String responseString = getContent(); final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); 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;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString); System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader); System.out.println("POST Content Type: " + contentTypeInHeader);
@ -131,8 +139,12 @@ public class HttpClientMultipartLiveTest {
@Test @Test
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + ZIPFILENAME); final URL url = Thread.currentThread()
final URL url2 = Thread.currentThread().getContextClassLoader().getResource("uploads/" + IMAGEFILENAME); .getContextClassLoader()
.getResource("uploads/" + ZIPFILENAME);
final URL url2 = Thread.currentThread()
.getContextClassLoader()
.getResource("uploads/" + IMAGEFILENAME);
final InputStream inputStream = new FileInputStream(url.getPath()); final InputStream inputStream = new FileInputStream(url.getPath());
final File file = new File(url2.getPath()); final File file = new File(url2.getPath());
final String message = "This is a multipart post"; final String message = "This is a multipart post";
@ -144,11 +156,12 @@ public class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
response = client.execute(post); response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode(); final int statusCode = response.getStatusLine()
.getStatusCode();
final String responseString = getContent(); final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); 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;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString); System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader); System.out.println("POST Content Type: " + contentTypeInHeader);
@ -166,11 +179,12 @@ public class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
response = client.execute(post); response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode(); final int statusCode = response.getStatusLine()
.getStatusCode();
final String responseString = getContent(); final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); 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;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString); System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader); System.out.println("POST Content Type: " + contentTypeInHeader);
@ -179,7 +193,8 @@ public class HttpClientMultipartLiveTest {
// UTIL // UTIL
final String getContent() throws IOException { final String getContent() throws IOException {
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); rd = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
String body = ""; String body = "";
String content = ""; String content = "";
while ((body = rd.readLine()) != null) { while ((body = rd.readLine()) != null) {
@ -189,7 +204,9 @@ public class HttpClientMultipartLiveTest {
} }
final String getContentTypeHeader() throws IOException { final String getContentTypeHeader() throws IOException {
return post.getEntity().getContentType().toString(); return post.getEntity()
.getContentType()
.toString();
} }
} }

View File

@ -1,11 +1,24 @@
package org.baeldung.httpclient; 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.HttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry; 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.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; 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.apache.http.ssl.SSLContexts;
import org.junit.Test; 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> * This test requires a localhost server over HTTPS <br>
* It should only be manually run, not part of the automated build * It should only be manually run, not part of the automated build
@ -35,13 +40,15 @@ public class HttpsClientSslLiveTest {
// tests // tests
@Test(expected = SSLException.class) @Test(expected = SSLHandshakeException.class)
public final void whenHttpsUrlIsConsumed_thenException() throws IOException { 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 HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod); final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -57,7 +64,8 @@ public class HttpsClientSslLiveTest {
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod); final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close(); httpClient.close();
} }
@ -65,44 +73,62 @@ public class HttpsClientSslLiveTest {
@Test @Test
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; 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 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 HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod); final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close(); httpClient.close();
} }
@Test @Test
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final SSLContextBuilder builder = new SSLContextBuilder(); final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); .build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(hostnameVerifier)
.setSSLSocketFactory(sslsf)
.build();
// new // new
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod); final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
} }
@Test @Test
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception { public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
SSLContext sslContext = new SSLContextBuilder() final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true)
.loadTrustMaterial(null, (certificate, authType) -> true).build(); .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); final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
httpGet.setHeader("Accept", "application/xml"); httpGet.setHeader("Accept", "application/xml");
final HttpResponse response = client.execute(httpGet); final HttpResponse response = client.execute(httpGet);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
} }
} }

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Working with Images in Java](http://www.baeldung.com/java-images)

View File

@ -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) - [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) - [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations)
- [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance) - [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance)
- [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat)

View File

@ -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;
}
}

View File

@ -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;
}
}

Some files were not shown because too many files have changed in this diff Show More