Merge branch 'master' into pr/997-stephen

This commit is contained in:
slavisa-baeldung 2017-01-15 15:08:31 +01:00
commit dabdd5d397
229 changed files with 5856 additions and 1545 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,6 +1,5 @@
<?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">
<parent>
<artifactId>parent-modules</artifactId>

View File

@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-fop</artifactId>

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

@ -45,6 +45,36 @@
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
@ -81,18 +111,8 @@
<Xlint>ignore</Xlint>
<encoding>${project.build.sourceEncoding}</encoding>
<!-- Post-compile weaving -->
<!--
<weaveDependencies>
<weaveDependency>
<groupId>org.agroup</groupId>
<artifactId>to-weave</artifactId>
</weaveDependency>
<weaveDependency>
<groupId>org.anothergroup</groupId>
<artifactId>gen</artifactId>
</weaveDependency>
</weaveDependencies>
-->
<!-- <weaveDependencies> <weaveDependency> <groupId>org.agroup</groupId> <artifactId>to-weave</artifactId> </weaveDependency>
<weaveDependency> <groupId>org.anothergroup</groupId> <artifactId>gen</artifactId> </weaveDependency> </weaveDependencies> -->
</configuration>
<executions>
<execution>
@ -104,18 +124,9 @@
</executions>
</plugin>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.10</version>
<configuration>
<argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
<useSystemClassLoader>true</useSystemClassLoader>
<forkMode>always</forkMode>
</configuration>
</plugin>
-->
<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.10</version>
<configuration> <argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
<useSystemClassLoader>true</useSystemClassLoader> <forkMode>always</forkMode> </configuration> </plugin> -->
</plugins>
</build>

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

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

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.lambda;
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.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.RequestHandler;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import org.apache.commons.io.IOUtils;

View File

@ -1,5 +1,4 @@
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
@ -23,8 +22,6 @@
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>

View File

@ -46,3 +46,10 @@
- [Grep in Java](http://www.baeldung.com/grep-in-java)
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [Simulated Annealing for Travelling Salesman Problem](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
- [Slope One Algorithm: Collaborative Filtering Recommendation Systems](http://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library)
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding)
- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size)
- [The Basics of Java Generics](http://www.baeldung.com/java-generics)
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)

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,2 @@
### Relevant Articles:
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)

View File

@ -1,3 +1,11 @@
### Relevant Articles:
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel)
- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng)
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)

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,2 @@
### Relevant Articles:
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)

View File

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

View File

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

View File

@ -2,14 +2,19 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>ejb-client</artifactId>
<name>ejb-client</name>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-client</artifactId>
<name>EJB3 Client Maven</name>
<description>EJB3 Client Maven</description>
<properties>
<junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19</maven-surefire-plugin.version>
</properties>
<dependencies>
<dependency>
@ -45,10 +50,4 @@
</plugin>
</plugins>
</build>
<properties>
<junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>

View File

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

View File

@ -2,15 +2,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-remote</artifactId>
<packaging>ejb</packaging>
<!-- <name>ejb-remote</name> -->
<dependencies>
<dependency>
<groupId>javax</groupId>
@ -20,12 +21,56 @@
</dependency>
</dependencies>
<profiles>
<!-- mvn clean package cargo:run -->
<profile>
<id>wildfly-standalone</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<container>
<containerId>wildfly10x</containerId>
<zipUrlInstaller>
<url>http://download.jboss.org/wildfly/10.1.0.Final/wildfly-10.1.0.Final.zip</url>
</zipUrlInstaller>
</container>
<configuration>
<properties>
<cargo.hostname>127.0.0.1</cargo.hostname>
<cargo.jboss.management-http.port>9990</cargo.jboss.management-http.port>
<cargo.servlet.users>testUser:admin1234!</cargo.servlet.users>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<!--mvn clean install wildfly:deploy -Pwildfly-runtime-->
<profile>
<id>wildfly-runtime</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>${wildfly-maven-plugin.version}</version>
<version>1.1.0.Alpha5</version>
<configuration>
<hostname>127.0.0.1</hostname>
<port>9990</port>
@ -35,11 +80,16 @@
</configuration>
</plugin>
</plugins>
<!-- <finalName>ejb-remote</finalName> -->
</build>
</profile>
</profiles>
<properties>
<javaee-api.version>7.0</javaee-api.version>
<wildfly-maven-plugin.version>1.1.0.Beta1</wildfly-maven-plugin.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -38,14 +38,14 @@
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<version>${wildfly.version}</version>
<version>10.1.0.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -57,7 +57,7 @@
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -66,7 +66,7 @@
<plugin>
<artifactId>maven-ejb-plugin</artifactId>
<version>${maven-ejb-plugin.version}</version>
<version>2.4</version>
<configuration>
<ejbVersion>3.2</ejbVersion>
</configuration>
@ -79,11 +79,4 @@
<module>ejb-remote</module>
<module>ejb-client</module>
</modules>
<properties>
<javaee-api.version>7.0</javaee-api.version>
<wildfly.version>10.1.0.Final</wildfly.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-ejb-plugin.version>2.5.1</maven-ejb-plugin.version>
</properties>
</project>

View File

@ -1,6 +1,5 @@
<?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">
<modelVersion>4.0.0</modelVersion>

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>
<!-- util -->
<guava.version>19.0</guava.version>
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>

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.CharsetEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.*;
import com.google.common.collect.*;
import org.junit.Test;
import com.google.common.base.CharMatcher;
@ -19,9 +18,6 @@ import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class GuavaStringTest {

View File

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

View File

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

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

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,33 @@
package com.baeldung.jackson.serialization;
import java.io.IOException;
import com.baeldung.jackson.enums.Distance;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class DistanceSerializer extends StdSerializer<Distance> {
private static final long serialVersionUID = 1376504304439963619L;
public DistanceSerializer() {
super(Distance.class);
}
public DistanceSerializer(Class<Distance> t) {
super(t);
}
public void serialize(Distance distance, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException {
generator.writeStartObject();
generator.writeFieldName("name");
generator.writeNumber(distance.name());
generator.writeFieldName("unit");
generator.writeString(distance.getUnit());
generator.writeFieldName("meters");
generator.writeNumber(distance.getMeters());
generator.writeEndObject();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.jackson.dtos.withEnum;
public enum DistanceEnumSimple {
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
private String unit;
private final double meters;
private DistanceEnumSimple(String unit, double meters) {
this.unit = unit;
this.meters = meters;
}
public double getMeters() {
return meters;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jackson.dtos.withEnum;
import com.fasterxml.jackson.annotation.JsonFormat;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum DistanceEnumWithJsonFormat {
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
private String unit;
private final double meters;
private DistanceEnumWithJsonFormat(String unit, double meters) {
this.unit = unit;
this.meters = meters;
}
public double getMeters() {
return meters;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jackson.dtos.withEnum;
import com.fasterxml.jackson.annotation.JsonValue;
public enum DistanceEnumWithValue {
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 DistanceEnumWithValue(String unit, double meters) {
this.unit = unit;
this.meters = meters;
}
@JsonValue
public double getMeters() {
return meters;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}

View File

@ -1,17 +1,19 @@
package com.baeldung.jackson.dtos.withEnum;
import com.baeldung.jackson.enums.Distance;
public class MyDtoWithEnumCustom {
private String stringValue;
private int intValue;
private boolean booleanValue;
private TypeEnumWithCustomSerializer type;
private Distance type;
public MyDtoWithEnumCustom() {
super();
}
public MyDtoWithEnumCustom(final String stringValue, final int intValue, final boolean booleanValue, final TypeEnumWithCustomSerializer type) {
public MyDtoWithEnumCustom(final String stringValue, final int intValue, final boolean booleanValue, final Distance type) {
super();
this.stringValue = stringValue;
@ -46,11 +48,11 @@ public class MyDtoWithEnumCustom {
this.booleanValue = booleanValue;
}
public TypeEnumWithCustomSerializer getType() {
public Distance getType() {
return type;
}
public void setType(final TypeEnumWithCustomSerializer type) {
public void setType(final Distance type) {
this.type = type;
}

View File

@ -1,23 +1,23 @@
package com.baeldung.jackson.dtos.withEnum;
public class MyDtoWithEnum {
public class MyDtoWithEnumJsonFormat {
private String stringValue;
private int intValue;
private boolean booleanValue;
private TypeEnum type;
private DistanceEnumWithJsonFormat distanceType;
public MyDtoWithEnum() {
public MyDtoWithEnumJsonFormat() {
super();
}
public MyDtoWithEnum(final String stringValue, final int intValue, final boolean booleanValue, final TypeEnum type) {
public MyDtoWithEnumJsonFormat(final String stringValue, final int intValue, final boolean booleanValue, final DistanceEnumWithJsonFormat type) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
this.type = type;
this.distanceType = type;
}
// API
@ -46,12 +46,12 @@ public class MyDtoWithEnum {
this.booleanValue = booleanValue;
}
public TypeEnum getType() {
return type;
public DistanceEnumWithJsonFormat getDistanceType() {
return distanceType;
}
public void setType(final TypeEnum type) {
this.type = type;
public void setDistanceType(final DistanceEnumWithJsonFormat type) {
this.distanceType = type;
}
}

View File

@ -1,35 +0,0 @@
package com.baeldung.jackson.dtos.withEnum;
import com.fasterxml.jackson.annotation.JsonFormat;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum TypeEnum {
TYPE1(1, "Type A"), TYPE2(2, "Type 2");
private Integer id;
private String name;
private TypeEnum(final Integer id, final String name) {
this.id = id;
this.name = name;
}
// API
public Integer getId() {
return id;
}
public void setId(final Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}

View File

@ -1,32 +0,0 @@
package com.baeldung.jackson.dtos.withEnum;
public enum TypeEnumSimple {
TYPE1(1, "Type A"), TYPE2(2, "Type 2");
private Integer id;
private String name;
private TypeEnumSimple(final Integer id, final String name) {
this.id = id;
this.name = name;
}
// API
public Integer getId() {
return id;
}
public void setId(final Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}

View File

@ -1,35 +0,0 @@
package com.baeldung.jackson.dtos.withEnum;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(using = TypeSerializer.class)
public enum TypeEnumWithCustomSerializer {
TYPE1(1, "Type A"), TYPE2(2, "Type 2");
private Integer id;
private String name;
private TypeEnumWithCustomSerializer(final Integer id, final String name) {
this.id = id;
this.name = name;
}
// API
public Integer getId() {
return id;
}
public void setId(final Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}

View File

@ -1,36 +0,0 @@
package com.baeldung.jackson.dtos.withEnum;
import com.fasterxml.jackson.annotation.JsonValue;
public enum TypeEnumWithValue {
TYPE1(1, "Type A"), TYPE2(2, "Type 2");
private Integer id;
private String name;
private TypeEnumWithValue(final Integer id, final String name) {
this.id = id;
this.name = name;
}
// API
public Integer getId() {
return id;
}
public void setId(final Integer id) {
this.id = id;
}
@JsonValue
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}

View File

@ -1,32 +0,0 @@
package com.baeldung.jackson.dtos.withEnum;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class TypeSerializer extends StdSerializer<TypeEnumWithCustomSerializer> {
private static final long serialVersionUID = -7650668914169390772L;
public TypeSerializer() {
this(null);
}
public TypeSerializer(final Class<TypeEnumWithCustomSerializer> t) {
super(t);
}
@Override
public void serialize(final TypeEnumWithCustomSerializer value, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
generator.writeStartObject();
generator.writeFieldName("id");
generator.writeNumber(value.getId());
generator.writeFieldName("name");
generator.writeString(value.getName());
generator.writeEndObject();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.jackson.enums;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonEnumSerializationTest {
@Test
public final void givenEnum_whenSerializingJson_thenCorrectRepresentation() throws JsonParseException, IOException {
final String dtoAsString = new ObjectMapper().writeValueAsString(Distance.MILE);
assertThat(dtoAsString, containsString("1609.34"));
}
}

View File

@ -34,11 +34,10 @@ import com.baeldung.jackson.bidirection.UserWithRef;
import com.baeldung.jackson.date.EventWithFormat;
import com.baeldung.jackson.date.EventWithSerializer;
import com.baeldung.jackson.dtos.MyMixInForIgnoreType;
import com.baeldung.jackson.dtos.withEnum.TypeEnumWithValue;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.exception.UserWithRoot;
import com.baeldung.jackson.jsonview.Item;
import com.baeldung.jackson.jsonview.Views;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.MapperFeature;
@ -101,10 +100,10 @@ public class JacksonAnnotationTest {
}
@Test
public void whenSerializingUsingJsonValue_thenCorrect() throws JsonParseException, IOException {
final String enumAsString = new ObjectMapper().writeValueAsString(TypeEnumWithValue.TYPE1);
public void whenSerializingUsingJsonValue_thenCorrect() throws IOException {
final String enumAsString = new ObjectMapper().writeValueAsString(DistanceEnumWithValue.MILE);
assertThat(enumAsString, is("\"Type A\""));
assertThat(enumAsString, is("1609.34"));
}
@Test
@ -122,7 +121,7 @@ public class JacksonAnnotationTest {
// ========================= Deserializing annotations ============================
@Test
public void whenDeserializingUsingJsonCreator_thenCorrect() throws JsonProcessingException, IOException {
public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException {
final String json = "{\"id\":1,\"theName\":\"My bean\"}";
final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class).readValue(json);
@ -130,7 +129,7 @@ public class JacksonAnnotationTest {
}
@Test
public void whenDeserializingUsingJsonInject_thenCorrect() throws JsonProcessingException, IOException {
public void whenDeserializingUsingJsonInject_thenCorrect() throws IOException {
final String json = "{\"name\":\"My bean\"}";
final InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1);
@ -140,7 +139,7 @@ public class JacksonAnnotationTest {
}
@Test
public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws JsonProcessingException, IOException {
public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException {
final String json = "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\"}";
final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class).readValue(json);
@ -149,7 +148,7 @@ public class JacksonAnnotationTest {
}
@Test
public void whenDeserializingUsingJsonSetter_thenCorrect() throws JsonProcessingException, IOException {
public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException {
final String json = "{\"id\":1,\"name\":\"My bean\"}";
final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(json);
@ -157,7 +156,7 @@ public class JacksonAnnotationTest {
}
@Test
public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws JsonProcessingException, IOException {
public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOException {
final String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014 02:30:00\"}";
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
@ -169,7 +168,7 @@ public class JacksonAnnotationTest {
// ========================= Inclusion annotations ============================
@Test
public void whenSerializingUsingJsonIgnoreProperties_thenCorrect() throws JsonProcessingException, IOException {
public void whenSerializingUsingJsonIgnoreProperties_thenCorrect() throws JsonProcessingException {
final BeanWithIgnore bean = new BeanWithIgnore(1, "My bean");
final String result = new ObjectMapper().writeValueAsString(bean);
@ -178,7 +177,7 @@ public class JacksonAnnotationTest {
}
@Test
public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException, IOException {
public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException {
final BeanWithIgnore bean = new BeanWithIgnore(1, "My bean");
final String result = new ObjectMapper().writeValueAsString(bean);
@ -199,7 +198,7 @@ public class JacksonAnnotationTest {
}
@Test
public void whenSerializingUsingJsonInclude_thenCorrect() throws JsonProcessingException, IOException {
public void whenSerializingUsingJsonInclude_thenCorrect() throws JsonProcessingException {
final MyBean bean = new MyBean(1, null);
final String result = new ObjectMapper().writeValueAsString(bean);
@ -208,7 +207,7 @@ public class JacksonAnnotationTest {
}
@Test
public void whenSerializingUsingJsonAutoDetect_thenCorrect() throws JsonProcessingException, IOException {
public void whenSerializingUsingJsonAutoDetect_thenCorrect() throws JsonProcessingException {
final PrivateBean bean = new PrivateBean(1, "My bean");
final String result = new ObjectMapper().writeValueAsString(bean);
@ -219,7 +218,7 @@ public class JacksonAnnotationTest {
// ========================= Polymorphic annotations ============================
@Test
public void whenSerializingPolymorphic_thenCorrect() throws JsonProcessingException, IOException {
public void whenSerializingPolymorphic_thenCorrect() throws JsonProcessingException {
final Zoo.Dog dog = new Zoo.Dog("lacy");
final Zoo zoo = new Zoo(dog);
@ -230,7 +229,7 @@ public class JacksonAnnotationTest {
}
@Test
public void whenDeserializingPolymorphic_thenCorrect() throws JsonProcessingException, IOException {
public void whenDeserializingPolymorphic_thenCorrect() throws IOException {
final String json = "{\"animal\":{\"name\":\"lacy\",\"type\":\"cat\"}}";
final Zoo zoo = new ObjectMapper().readerFor(Zoo.class).readValue(json);
@ -276,7 +275,7 @@ public class JacksonAnnotationTest {
}
@Test
public void whenSerializingUsingJsonView_thenCorrect() throws JsonProcessingException {
public void whenSerializingUsingJsonView_thenCorrect() throws JsonProcessingException, JsonProcessingException {
final Item item = new Item(2, "book", "John");
final String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(item);
@ -352,7 +351,7 @@ public class JacksonAnnotationTest {
}
@Test
public void whenDisablingAllAnnotations_thenAllDisabled() throws JsonProcessingException, IOException {
public void whenDisablingAllAnnotations_thenAllDisabled() throws JsonProcessingException {
final MyBean bean = new MyBean(1, null);
final ObjectMapper mapper = new ObjectMapper();

View File

@ -6,14 +6,14 @@ import static org.junit.Assert.assertThat;
import java.io.IOException;
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnum;
import com.baeldung.jackson.dtos.withEnum.TypeEnum;
import com.baeldung.jackson.dtos.withEnum.TypeEnumSimple;
import com.baeldung.jackson.dtos.withEnum.TypeEnumWithValue;
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumCustom;
import com.baeldung.jackson.dtos.withEnum.TypeEnumWithCustomSerializer;
import org.junit.Test;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumSimple;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithJsonFormat;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumCustom;
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumJsonFormat;
import com.baeldung.jackson.enums.Distance;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -24,10 +24,9 @@ public class JacksonSerializationEnumsUnitTest {
@Test
public final void whenSerializingASimpleEnum_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String enumAsString = mapper.writeValueAsString(TypeEnumSimple.TYPE1);
System.out.println(enumAsString);
final String enumAsString = mapper.writeValueAsString(DistanceEnumSimple.MILE);
assertThat(enumAsString, containsString("TYPE1"));
assertThat(enumAsString, containsString("MILE"));
}
// tests - enum with main value
@ -35,10 +34,9 @@ public class JacksonSerializationEnumsUnitTest {
@Test
public final void whenSerializingAEnumWithValue_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String enumAsString = mapper.writeValueAsString(TypeEnumWithValue.TYPE1);
System.out.println(enumAsString);
final String enumAsString = mapper.writeValueAsString(DistanceEnumWithValue.MILE);
assertThat(enumAsString, is("\"Type A\""));
assertThat(enumAsString, is("1609.34"));
}
// tests - enum
@ -46,28 +44,25 @@ public class JacksonSerializationEnumsUnitTest {
@Test
public final void whenSerializingAnEnum_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String enumAsString = mapper.writeValueAsString(TypeEnum.TYPE1);
final String enumAsString = mapper.writeValueAsString(DistanceEnumWithJsonFormat.MILE);
System.out.println(enumAsString);
assertThat(enumAsString, containsString("\"name\":\"Type A\""));
assertThat(enumAsString, containsString("\"meters\":1609.34"));
}
@Test
public final void whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnum("a", 1, true, TypeEnum.TYPE1));
final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumJsonFormat("a", 1, true, DistanceEnumWithJsonFormat.MILE));
System.out.println(enumAsString);
assertThat(enumAsString, containsString("\"name\":\"Type A\""));
assertThat(enumAsString, containsString("\"meters\":1609.34"));
}
@Test
public final void whenSerializingArrayOfEnums_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String json = mapper.writeValueAsString(new TypeEnum[] { TypeEnum.TYPE1, TypeEnum.TYPE2 });
final String json = mapper.writeValueAsString(new DistanceEnumWithJsonFormat[] { DistanceEnumWithJsonFormat.MILE, DistanceEnumWithJsonFormat.KILOMETER });
System.out.println(json);
assertThat(json, containsString("\"name\":\"Type A\""));
assertThat(json, containsString("\"meters\":1609.34"));
}
// tests - enum with custom serializer
@ -75,10 +70,9 @@ public class JacksonSerializationEnumsUnitTest {
@Test
public final void givenCustomSerializer_whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumCustom("a", 1, true, TypeEnumWithCustomSerializer.TYPE1));
final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumCustom("a", 1, true, Distance.MILE));
System.out.println(enumAsString);
assertThat(enumAsString, containsString("\"name\":\"Type A\""));
assertThat(enumAsString, containsString("\"meters\":1609.34"));
}
}

5
java-mongodb/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.classpath
.project
.settings
target
build

44
java-mongodb/pom.xml Normal file
View File

@ -0,0 +1,44 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>java-mongodb</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>4.12</junit.version>
<mongo.version>3.4.1</mongo.version>
<flapdoodle.version>1.11</flapdoodle.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.flapdoodle.embedmongo</groupId>
<artifactId>de.flapdoodle.embedmongo</artifactId>
<version>${flapdoodle.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>${mongo.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,53 @@
package com.baeldung;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
public class MongoExample {
public static void main( String[] args ) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB database = mongoClient.getDB("myMongoDb");
// print existing databases
mongoClient.getDatabaseNames().forEach(System.out::println);
database.createCollection("customers", null);
// print all collections in customers database
database.getCollectionNames().forEach(System.out::println);
// create data
DBCollection collection = database.getCollection("customers");
BasicDBObject document = new BasicDBObject();
document.put("name", "Shubham");
document.put("company", "Baeldung");
collection.insert(document);
// update data
BasicDBObject query = new BasicDBObject();
query.put("name", "Shubham");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "John");
BasicDBObject updateObject = new BasicDBObject();
updateObject.put("$set", newDocument);
collection.update(query, updateObject);
// read data
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "John");
DBCursor cursor = collection.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
// delete data
BasicDBObject deleteQuery = new BasicDBObject();
deleteQuery.put("name", "John");
collection.remove(deleteQuery);
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import de.flapdoodle.embedmongo.MongoDBRuntime;
import de.flapdoodle.embedmongo.MongodExecutable;
import de.flapdoodle.embedmongo.MongodProcess;
import de.flapdoodle.embedmongo.config.MongodConfig;
import de.flapdoodle.embedmongo.distribution.Version;
import de.flapdoodle.embedmongo.runtime.Network;
public class AppTest {
private static final String DB_NAME = "myMongoDb";
private MongodExecutable mongodExe;
private MongodProcess mongod;
private Mongo mongo;
private DB db;
private DBCollection collection;
@Before
public void setup() throws Exception {
// Creating Mongodbruntime instance
MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance();
// Creating MongodbExecutable
mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345,
Network.localhostIsIPv6()));
// Starting Mongodb
mongod = mongodExe.start();
mongo = new Mongo("localhost", 12345);
// Creating DB
db = mongo.getDB(DB_NAME);
// Creating collection Object and adding values
collection = db.getCollection("customers");
}
@After
public void teardown() throws Exception {
mongod.stop();
mongodExe.cleanup();
}
@Test
public void testAddressPersistance() {
BasicDBObject contact = new BasicDBObject();
contact.put("name", "John");
contact.put("company", "Baeldung");
// Inserting document
collection.insert(contact);
DBCursor cursorDoc = collection.find();
BasicDBObject contact1 = new BasicDBObject();
while (cursorDoc.hasNext()) {
contact1 = (BasicDBObject) cursorDoc.next();
System.out.println(contact1);
}
assertEquals(contact1.get("name"), "John");
}
}

2
javaslang/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to Javaslang](http://www.baeldung.com/javaslang)

2
jaxb/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Guide to JAXB](http://www.baeldung.com/jaxb)

10
jsoup/README.md Normal file
View File

@ -0,0 +1,10 @@
=========
## jsoup Example Project
### Relevant Articles:
- [Parsing HTML in Java with Jsoup](http://www.baeldung.com/java-with-jsoup)
### Build the Project
mvn clean install

View File

@ -15,15 +15,16 @@
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<commons.io.version>2.5</commons.io.version>
<jsoup.version>1.10.1</jsoup.version>
<jsoup.version>1.10.2</jsoup.version>
</properties>
</project>

View File

@ -1,47 +1,52 @@
package com.baeldung.jsoup;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import org.junit.Before;
import org.junit.Test;
public class JsoupExample {
import java.io.IOException;
public static void main(String[] args) throws IOException {
scrapeSpringBlog();
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JsoupParserTest {
Document doc;
@Before
public void setUp() throws IOException {
doc = Jsoup.connect("https://spring.io/blog").get();
}
static void scrapeSpringBlog() throws IOException {
String blogUrl = "https://spring.io/blog";
Document doc = Jsoup.connect(blogUrl).get();
@Test
public void loadDocument404() throws IOException {
try {
Document doc404 = Jsoup.connect("https://spring.io/will-not-be-found").get();
doc = Jsoup.connect("https://spring.io/will-not-be-found").get();
} catch (HttpStatusException ex) {
System.out.println(ex.getMessage());
assertEquals(404, ex.getStatusCode());
}
}
Document docCustomConn = Jsoup.connect(blogUrl).userAgent("Mozilla").get();
docCustomConn = Jsoup.connect(blogUrl).timeout(5000).get();
docCustomConn = Jsoup.connect(blogUrl).cookie("cookiename", "val234").get();
// docCustomConn = Jsoup.connect(blogUrl).data("datakey", "datavalue").post();
docCustomConn = Jsoup.connect(blogUrl).header("headersecurity", "xyz123").get();
docCustomConn = Jsoup.connect(blogUrl)
@Test
public void loadDocumentCustomized() throws IOException {
doc = Jsoup.connect("https://spring.io/blog")
.userAgent("Mozilla")
.timeout(5000)
.cookie("cookiename", "val234")
.cookie("anothercookie", "ilovejsoup")
.referrer("http://google.com")
.header("headersecurity", "xyz123")
.get();
}
@Test
public void examplesSelectors() {
Elements links = doc.select("a");
Elements sections = doc.select("section");
Elements logo = doc.select(".spring-logo--container");
Elements pagination = doc.select("#pagination_control");
Elements divsDescendant = doc.select("header div");
@ -50,6 +55,15 @@ public class JsoupExample {
Element pag = doc.getElementById("pagination_control");
Elements desktopOnly = doc.getElementsByClass("desktopOnly");
Elements sections = doc.select("section");
Element firstSection = sections.first();
Elements sectionParagraphs = firstSection.select(".paragraph");
}
@Test
public void examplesTraversing() {
Elements sections = doc.select("section");
Element firstSection = sections.first();
Element lastSection = sections.last();
Element secondSection = sections.get(2);
@ -58,10 +72,11 @@ public class JsoupExample {
Elements children = firstSection.children();
Elements siblings = firstSection.siblingElements();
sections.stream().forEach(el -> System.out.println("section: " + el));
Elements sectionParagraphs = firstSection.select(".paragraph");
sections.forEach(el -> System.out.println("section: " + el));
}
@Test
public void examplesExtracting() {
Element firstArticle = doc.select("article").first();
Element timeElement = firstArticle.select("time").first();
String dateTimeOfFirstArticle = timeElement.attr("datetime");
@ -69,7 +84,15 @@ public class JsoupExample {
String sectionDivText = sectionDiv.text();
String articleHtml = firstArticle.html();
String outerHtml = firstArticle.outerHtml();
}
@Test
public void examplesModifying() {
Element firstArticle = doc.select("article").first();
Element timeElement = firstArticle.select("time").first();
Element sectionDiv = firstArticle.select("section div").first();
String dateTimeOfFirstArticle = timeElement.attr("datetime");
timeElement.attr("datetime", "2016-12-16 15:19:54.3");
sectionDiv.text("foo bar");
firstArticle.select("h2").html("<div><span></span></div>");
@ -83,7 +106,6 @@ public class JsoupExample {
doc.select("li.navbar-link").remove();
firstArticle.select("img").remove();
File indexFile = new File("/tmp", "spring_blog_home.html");
FileUtils.writeStringToFile(indexFile, doc.html(), doc.charset());
assertTrue(doc.html().contains("http://baeldung.com"));
}
}

View File

@ -1,6 +1,7 @@
### Relevant Articles:
- TBD
- [Improved Java Logging with Mapped Diagnostic Context (MDC)](http://www.baeldung.com/mdc-in-log4j-2-logback)
- [Java Logging with Nested Diagnostic Context (NDC)](http://www.baeldung.com/java-logging-ndc-log4j)
### References

View File

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
@ -15,6 +14,8 @@
</properties>
<modules>
<module>aws</module>
<module>algorithms</module>
<module>annotations</module>
<module>apache-cxf</module>
<module>apache-fop</module>
@ -91,6 +92,7 @@
<module>selenium-junit-testng</module>
<module>spring-akka</module>
<module>spring-amqp</module>
<module>spring-all</module>
<module>spring-apache-camel</module>
<module>spring-autowire</module>
@ -115,6 +117,7 @@
<module>spring-hibernate3</module>
<module>spring-hibernate4</module>
<module>spring-integration</module>
<module>spring-jersey</module>
<module>spring-jms</module>
<module>spring-jooq</module>
<module>spring-jpa</module>
@ -158,6 +161,7 @@
<module>spring-security-rest</module>
<module>spring-security-x509</module>
<module>spring-session</module>
<module>spring-sleuth</module>
<module>spring-social-login</module>
<module>spring-spel</module>
<module>spring-thymeleaf</module>
@ -172,6 +176,7 @@
<module>xml</module>
<module>xmlunit2</module>
<module>xstream</module>
<module>java-mongodb</module>
</modules>
</project>

View File

@ -38,6 +38,11 @@
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>${springretry.version}</version>
</dependency>
<!-- aspectj -->
@ -166,7 +171,6 @@
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
@ -275,6 +279,7 @@
<!-- Spring -->
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>
<org.springframework.security.version>4.2.0.RELEASE</org.springframework.security.version>
<springretry.version>1.1.5.RELEASE</springretry.version>
<!-- persistence -->
<hibernate.version>5.2.5.Final</hibernate.version>

View File

@ -0,0 +1,34 @@
package org.baeldung.springretry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
@Configuration
@ComponentScan(basePackages = "org.baeldung.springretry")
@EnableRetry
//Uncomment this two lines if we need XML configuration
//@EnableAspectJAutoProxy
//@ImportResource("classpath:/retryadvice.xml")
public class AppConfig {
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(2000l);
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(2);
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.registerListener(new DefaultListenerSupport());
return retryTemplate;
}
}

View File

@ -0,0 +1,31 @@
package org.baeldung.springretry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.listener.RetryListenerSupport;
public class DefaultListenerSupport extends RetryListenerSupport {
private static final Logger logger = LoggerFactory.getLogger(DefaultListenerSupport.class);
@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
logger.info("onClose");
super.close(context, callback, throwable);
}
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
logger.info("onError");
super.onError(context, callback, throwable);
}
@Override
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
logger.info("onOpen");
return super.open(context, callback);
}
}

View File

@ -0,0 +1,21 @@
package org.baeldung.springretry;
import java.sql.SQLException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
public interface MyService {
@Retryable
void retryService();
@Retryable(value = { SQLException.class }, maxAttempts = 2, backoff = @Backoff(delay = 5000))
void retryServiceWithRecovery(String sql) throws SQLException;
@Recover
void recover(SQLException e, String sql);
void templateRetryService();
}

View File

@ -0,0 +1,39 @@
package org.baeldung.springretry;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class MyServiceImpl implements MyService {
private static final Logger logger = LoggerFactory.getLogger(MyServiceImpl.class);
@Override
public void retryService() {
logger.info("throw RuntimeException in method retryService()");
throw new RuntimeException();
}
@Override
public void retryServiceWithRecovery(String sql) throws SQLException {
if (StringUtils.isEmpty(sql)) {
logger.info("throw SQLException in method retryServiceWithRecovery()");
throw new SQLException();
}
}
@Override
public void recover(SQLException e, String sql) {
logger.info("In recover method");
}
@Override
public void templateRetryService() {
logger.info("throw RuntimeException in method templateRetryService()");
throw new RuntimeException();
}
}

View File

@ -0,0 +1,41 @@
package org.baeldung.taskscheduler;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;
@Configuration
@ComponentScan(basePackages = "org.baeldung.taskscheduler", basePackageClasses = { ThreadPoolTaskSchedulerExamples.class })
public class ThreadPoolTaskSchedulerConfig {
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
@Bean
public CronTrigger cronTrigger() {
return new CronTrigger("10 * * * * ?");
}
@Bean
public PeriodicTrigger periodicTrigger() {
return new PeriodicTrigger(2000, TimeUnit.MICROSECONDS);
}
@Bean
public PeriodicTrigger periodicFixedDelayTrigger() {
PeriodicTrigger periodicTrigger = new PeriodicTrigger(2000, TimeUnit.MICROSECONDS);
periodicTrigger.setFixedRate(true);
periodicTrigger.setInitialDelay(1000);
return periodicTrigger;
}
}

View File

@ -0,0 +1,47 @@
package org.baeldung.taskscheduler;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;
@Component
public class ThreadPoolTaskSchedulerExamples {
@Autowired
private ThreadPoolTaskScheduler taskScheduler;
@Autowired
private CronTrigger cronTrigger;
@Autowired
private PeriodicTrigger periodicTrigger;
@PostConstruct
public void scheduleRunnableWithCronTrigger(){
taskScheduler.schedule(new RunnableTask("Current Date"), new Date());
taskScheduler.scheduleWithFixedDelay(new RunnableTask("Fixed 1 second Delay"), 1000);
taskScheduler.scheduleWithFixedDelay(new RunnableTask("Current Date Fixed 1 second Delay"),new Date() , 1000);
taskScheduler.scheduleAtFixedRate(new RunnableTask("Fixed Rate of 2 seconds"),new Date(), 2000);
taskScheduler.scheduleAtFixedRate(new RunnableTask("Fixed Rate of 2 seconds"), 2000);
taskScheduler.schedule(new RunnableTask("Cron Trigger"), cronTrigger);
taskScheduler.schedule(new RunnableTask("Periodic Trigger"), periodicTrigger);
}
class RunnableTask implements Runnable{
private String message;
public RunnableTask(String message){
this.message = message;
}
@Override
public void run() {
System.out.println("Runnable Task with "+message+" on thread "+Thread.currentThread().getName());
}
}
}

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