commit
5b8f662e86
63
JGit/pom.xml
Normal file
63
JGit/pom.xml
Normal 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>
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
65
JGit/src/main/java/com/baeldung/jgit/OpenRepository.java
Normal file
65
JGit/src/main/java/com/baeldung/jgit/OpenRepository.java
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
33
JGit/src/main/java/com/baeldung/jgit/helper/Helper.java
Normal file
33
JGit/src/main/java/com/baeldung/jgit/helper/Helper.java
Normal 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
36
JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java
Normal file
36
JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java
Normal 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.jgit.porcelain;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import com.baeldung.jgit.helper.Helper;
|
||||||
|
import org.eclipse.jgit.api.Git;
|
||||||
|
import org.eclipse.jgit.api.errors.GitAPIException;
|
||||||
|
import org.eclipse.jgit.lib.Repository;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simple snippet which shows how to commit all files
|
||||||
|
*
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class CommitAll {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException, GitAPIException {
|
||||||
|
// prepare a new test-repository
|
||||||
|
try (Repository repository = Helper.createNewRepository()) {
|
||||||
|
try (Git git = new Git(repository)) {
|
||||||
|
// create the file
|
||||||
|
File myfile = new File(repository.getDirectory().getParent(), "testfile");
|
||||||
|
if(!myfile.createNewFile()) {
|
||||||
|
throw new IOException("Could not create file " + myfile);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stage all files in the repo including new files
|
||||||
|
git.add().addFilepattern(".").call();
|
||||||
|
|
||||||
|
// and then commit the changes.
|
||||||
|
git.commit()
|
||||||
|
.setMessage("Commit all changes including additions")
|
||||||
|
.call();
|
||||||
|
|
||||||
|
try(PrintWriter writer = new PrintWriter(myfile)) {
|
||||||
|
writer.append("Hello, world!");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stage all changed files, omitting new files, and commit with one command
|
||||||
|
git.commit()
|
||||||
|
.setAll(true)
|
||||||
|
.setMessage("Commit changes to all files")
|
||||||
|
.call();
|
||||||
|
|
||||||
|
|
||||||
|
System.out.println("Committed all changes to repository at " + repository.getDirectory());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.jgit.porcelain;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import com.baeldung.jgit.helper.Helper;
|
||||||
|
import org.eclipse.jgit.api.Git;
|
||||||
|
import org.eclipse.jgit.api.errors.GitAPIException;
|
||||||
|
import org.eclipse.jgit.lib.ObjectId;
|
||||||
|
import org.eclipse.jgit.lib.Ref;
|
||||||
|
import org.eclipse.jgit.lib.Repository;
|
||||||
|
import org.eclipse.jgit.revwalk.RevCommit;
|
||||||
|
import org.eclipse.jgit.revwalk.RevWalk;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simple snippet which shows how to create a tag
|
||||||
|
*
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class CreateAndDeleteTag {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException, GitAPIException {
|
||||||
|
// prepare test-repository
|
||||||
|
try (Repository repository = Helper.openJGitRepository()) {
|
||||||
|
try (Git git = new Git(repository)) {
|
||||||
|
// remove the tag before creating it
|
||||||
|
git.tagDelete().setTags("tag_for_testing").call();
|
||||||
|
|
||||||
|
// set it on the current HEAD
|
||||||
|
Ref tag = git.tag().setName("tag_for_testing").call();
|
||||||
|
System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
|
||||||
|
|
||||||
|
// remove the tag again
|
||||||
|
git.tagDelete().setTags("tag_for_testing").call();
|
||||||
|
|
||||||
|
// read some other commit and set the tag on it
|
||||||
|
ObjectId id = repository.resolve("HEAD^");
|
||||||
|
try (RevWalk walk = new RevWalk(repository)) {
|
||||||
|
RevCommit commit = walk.parseCommit(id);
|
||||||
|
tag = git.tag().setObjectId(commit).setName("tag_for_testing").call();
|
||||||
|
System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
|
||||||
|
|
||||||
|
// remove the tag again
|
||||||
|
git.tagDelete().setTags("tag_for_testing").call();
|
||||||
|
|
||||||
|
// create an annotated tag
|
||||||
|
tag = git.tag().setName("tag_for_testing").setAnnotated(true).call();
|
||||||
|
System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
|
||||||
|
|
||||||
|
// remove the tag again
|
||||||
|
git.tagDelete().setTags("tag_for_testing").call();
|
||||||
|
|
||||||
|
walk.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
74
JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java
Normal file
74
JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java
Normal 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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
31
JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java
Normal file
31
JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>parent-modules</artifactId>
|
||||||
|
@ -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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>apache-fop</artifactId>
|
<artifactId>apache-fop</artifactId>
|
||||||
|
@ -1,2 +1,3 @@
|
|||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Intro to AspectJ](http://www.baeldung.com/aspectj)
|
- [Intro to AspectJ](http://www.baeldung.com/aspectj)
|
||||||
|
- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging)
|
||||||
|
@ -111,18 +111,8 @@
|
|||||||
<Xlint>ignore</Xlint>
|
<Xlint>ignore</Xlint>
|
||||||
<encoding>${project.build.sourceEncoding}</encoding>
|
<encoding>${project.build.sourceEncoding}</encoding>
|
||||||
<!-- Post-compile weaving -->
|
<!-- Post-compile weaving -->
|
||||||
<!--
|
<!-- <weaveDependencies> <weaveDependency> <groupId>org.agroup</groupId> <artifactId>to-weave</artifactId> </weaveDependency>
|
||||||
<weaveDependencies>
|
<weaveDependency> <groupId>org.anothergroup</groupId> <artifactId>gen</artifactId> </weaveDependency> </weaveDependencies> -->
|
||||||
<weaveDependency>
|
|
||||||
<groupId>org.agroup</groupId>
|
|
||||||
<artifactId>to-weave</artifactId>
|
|
||||||
</weaveDependency>
|
|
||||||
<weaveDependency>
|
|
||||||
<groupId>org.anothergroup</groupId>
|
|
||||||
<artifactId>gen</artifactId>
|
|
||||||
</weaveDependency>
|
|
||||||
</weaveDependencies>
|
|
||||||
-->
|
|
||||||
</configuration>
|
</configuration>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
@ -134,18 +124,9 @@
|
|||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<!--
|
<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.10</version>
|
||||||
<plugin>
|
<configuration> <argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<useSystemClassLoader>true</useSystemClassLoader> <forkMode>always</forkMode> </configuration> </plugin> -->
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>2.10</version>
|
|
||||||
<configuration>
|
|
||||||
<argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
|
|
||||||
<useSystemClassLoader>true</useSystemClassLoader>
|
|
||||||
<forkMode>always</forkMode>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
-->
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
@ -23,8 +22,6 @@
|
|||||||
<version>${org.slf4j.version}</version>
|
<version>${org.slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hamcrest</groupId>
|
<groupId>org.hamcrest</groupId>
|
||||||
<artifactId>hamcrest-library</artifactId>
|
<artifactId>hamcrest-library</artifactId>
|
||||||
|
4
core-java/.gitignore
vendored
4
core-java/.gitignore
vendored
@ -16,3 +16,7 @@
|
|||||||
*.txt
|
*.txt
|
||||||
/bin/
|
/bin/
|
||||||
/temp
|
/temp
|
||||||
|
|
||||||
|
#IntelliJ specific
|
||||||
|
.idea
|
||||||
|
*.iml
|
@ -53,3 +53,4 @@
|
|||||||
- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size)
|
- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size)
|
||||||
- [The Basics of Java Generics](http://www.baeldung.com/java-generics)
|
- [The Basics of Java Generics](http://www.baeldung.com/java-generics)
|
||||||
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||||
|
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
|
||||||
|
@ -63,6 +63,12 @@
|
|||||||
<artifactId>grep4j</artifactId>
|
<artifactId>grep4j</artifactId>
|
||||||
<version>${grep4j.version}</version>
|
<version>${grep4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.lmax</groupId>
|
||||||
|
<artifactId>disruptor</artifactId>
|
||||||
|
<version>${disruptor.version}</version>
|
||||||
|
</dependency>
|
||||||
<!-- web -->
|
<!-- web -->
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
@ -352,7 +358,7 @@
|
|||||||
<logback.version>1.1.7</logback.version>
|
<logback.version>1.1.7</logback.version>
|
||||||
|
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>19.0</guava.version>
|
<guava.version>21.0</guava.version>
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
<bouncycastle.version>1.55</bouncycastle.version>
|
<bouncycastle.version>1.55</bouncycastle.version>
|
||||||
<commons-codec.version>1.10</commons-codec.version>
|
<commons-codec.version>1.10</commons-codec.version>
|
||||||
@ -363,6 +369,7 @@
|
|||||||
<unix4j.version>0.4</unix4j.version>
|
<unix4j.version>0.4</unix4j.version>
|
||||||
<grep4j.version>1.8.7</grep4j.version>
|
<grep4j.version>1.8.7</grep4j.version>
|
||||||
<lombok.version>1.16.12</lombok.version>
|
<lombok.version>1.16.12</lombok.version>
|
||||||
|
<disruptor.version>3.3.6</disruptor.version>
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||||
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.chainedexception;
|
||||||
|
|
||||||
|
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
|
||||||
|
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
|
||||||
|
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
|
||||||
|
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
|
||||||
|
|
||||||
|
public class LogWithChain {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
getLeave();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void getLeave() throws NoLeaveGrantedException {
|
||||||
|
try {
|
||||||
|
howIsTeamLead();
|
||||||
|
} catch (TeamLeadUpsetException e) {
|
||||||
|
throw new NoLeaveGrantedException("Leave not sanctioned.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void howIsTeamLead() throws TeamLeadUpsetException {
|
||||||
|
try {
|
||||||
|
howIsManager();
|
||||||
|
} catch (ManagerUpsetException e) {
|
||||||
|
throw new TeamLeadUpsetException(
|
||||||
|
"Team lead is not in good mood", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void howIsManager() throws ManagerUpsetException {
|
||||||
|
try {
|
||||||
|
howIsGirlFriendOfManager();
|
||||||
|
} catch (GirlFriendOfManagerUpsetException e) {
|
||||||
|
throw new ManagerUpsetException("Manager is in bad mood", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void howIsGirlFriendOfManager()
|
||||||
|
throws GirlFriendOfManagerUpsetException {
|
||||||
|
throw new GirlFriendOfManagerUpsetException(
|
||||||
|
"Girl friend of manager is in bad mood");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.chainedexception;
|
||||||
|
|
||||||
|
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
|
||||||
|
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
|
||||||
|
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
|
||||||
|
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
|
||||||
|
|
||||||
|
public class LogWithoutChain {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
getLeave();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void getLeave() throws NoLeaveGrantedException {
|
||||||
|
try {
|
||||||
|
howIsTeamLead();
|
||||||
|
} catch (TeamLeadUpsetException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
throw new NoLeaveGrantedException("Leave not sanctioned.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void howIsTeamLead() throws TeamLeadUpsetException {
|
||||||
|
try {
|
||||||
|
howIsManager();
|
||||||
|
} catch (ManagerUpsetException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
throw new TeamLeadUpsetException(
|
||||||
|
"Team lead is not in good mood");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void howIsManager() throws ManagerUpsetException {
|
||||||
|
try {
|
||||||
|
howIsGirlFriendOfManager();
|
||||||
|
} catch (GirlFriendOfManagerUpsetException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
throw new ManagerUpsetException("Manager is in bad mood");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void howIsGirlFriendOfManager()
|
||||||
|
throws GirlFriendOfManagerUpsetException {
|
||||||
|
throw new GirlFriendOfManagerUpsetException(
|
||||||
|
"Girl friend of manager is in bad mood");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.chainedexception.exceptions;
|
||||||
|
|
||||||
|
public class GirlFriendOfManagerUpsetException extends Exception {
|
||||||
|
|
||||||
|
public GirlFriendOfManagerUpsetException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public GirlFriendOfManagerUpsetException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.chainedexception.exceptions;
|
||||||
|
|
||||||
|
public class ManagerUpsetException extends Exception {
|
||||||
|
|
||||||
|
public ManagerUpsetException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ManagerUpsetException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.chainedexception.exceptions;
|
||||||
|
|
||||||
|
public class NoLeaveGrantedException extends Exception {
|
||||||
|
|
||||||
|
public NoLeaveGrantedException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public NoLeaveGrantedException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.chainedexception.exceptions;
|
||||||
|
|
||||||
|
public class TeamLeadUpsetException extends Exception {
|
||||||
|
|
||||||
|
public TeamLeadUpsetException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TeamLeadUpsetException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.disruptor;
|
||||||
|
|
||||||
|
import com.lmax.disruptor.RingBuffer;
|
||||||
|
|
||||||
|
public class DelayedMultiEventProducer implements EventProducer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void startProducing(final RingBuffer<ValueEvent> ringBuffer, final int count) {
|
||||||
|
final Runnable simpleProducer = () -> produce(ringBuffer, count, false);
|
||||||
|
final Runnable delayedProducer = () -> produce(ringBuffer, count, true);
|
||||||
|
new Thread(simpleProducer).start();
|
||||||
|
new Thread(delayedProducer).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void produce(final RingBuffer<ValueEvent> ringBuffer, final int count, final boolean addDelay) {
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
final long seq = ringBuffer.next();
|
||||||
|
final ValueEvent valueEvent = ringBuffer.get(seq);
|
||||||
|
valueEvent.setValue(i);
|
||||||
|
ringBuffer.publish(seq);
|
||||||
|
if (addDelay) {
|
||||||
|
addDelay();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addDelay() {
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException interruptedException) {
|
||||||
|
// No-Op lets swallow it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.disruptor;
|
||||||
|
|
||||||
|
import com.lmax.disruptor.EventHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Consumer that consumes event from ring buffer.
|
||||||
|
*/
|
||||||
|
public interface EventConsumer {
|
||||||
|
/**
|
||||||
|
* One or more event handler to handle event from ring buffer.
|
||||||
|
*/
|
||||||
|
public EventHandler<ValueEvent>[] getEventHandler();
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.disruptor;
|
||||||
|
|
||||||
|
import com.lmax.disruptor.RingBuffer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Producer that produces event for ring buffer.
|
||||||
|
*/
|
||||||
|
public interface EventProducer {
|
||||||
|
/**
|
||||||
|
* Start the producer that would start producing the values.
|
||||||
|
* @param ringBuffer
|
||||||
|
* @param count
|
||||||
|
*/
|
||||||
|
public void startProducing(final RingBuffer<ValueEvent> ringBuffer, final int count);
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.disruptor;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.lmax.disruptor.EventHandler;
|
||||||
|
|
||||||
|
public class MultiEventPrintConsumer implements EventConsumer {
|
||||||
|
|
||||||
|
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public EventHandler<ValueEvent>[] getEventHandler() {
|
||||||
|
final EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> print(event.getValue(), sequence);
|
||||||
|
final EventHandler<ValueEvent> otherEventHandler = (event, sequence, endOfBatch) -> print(event.getValue(), sequence);
|
||||||
|
return new EventHandler[] { eventHandler, otherEventHandler };
|
||||||
|
}
|
||||||
|
|
||||||
|
private void print(final int id, final long sequenceId) {
|
||||||
|
logger.info("Id is " + id + " sequence id that was used is " + sequenceId);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.disruptor;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.lmax.disruptor.EventHandler;
|
||||||
|
|
||||||
|
public class SingleEventPrintConsumer implements EventConsumer {
|
||||||
|
|
||||||
|
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public EventHandler<ValueEvent>[] getEventHandler() {
|
||||||
|
final EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> print(event.getValue(), sequence);
|
||||||
|
return new EventHandler[] { eventHandler };
|
||||||
|
}
|
||||||
|
|
||||||
|
private void print(final int id, final long sequenceId) {
|
||||||
|
logger.info("Id is " + id + " sequence id that was used is " + sequenceId);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.disruptor;
|
||||||
|
|
||||||
|
import com.lmax.disruptor.RingBuffer;
|
||||||
|
|
||||||
|
public class SingleEventProducer implements EventProducer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void startProducing(RingBuffer<ValueEvent> ringBuffer, int count) {
|
||||||
|
final Runnable producer = () -> produce(ringBuffer, count);
|
||||||
|
new Thread(producer).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void produce(final RingBuffer<ValueEvent> ringBuffer, final int count) {
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
final long seq = ringBuffer.next();
|
||||||
|
final ValueEvent valueEvent = ringBuffer.get(seq);
|
||||||
|
valueEvent.setValue(i);
|
||||||
|
ringBuffer.publish(seq);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.disruptor;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||||
|
|
||||||
|
import com.lmax.disruptor.EventFactory;
|
||||||
|
|
||||||
|
public final class ValueEvent {
|
||||||
|
|
||||||
|
private int value;
|
||||||
|
|
||||||
|
public int getValue() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setValue(int value) {
|
||||||
|
this.value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final static EventFactory<ValueEvent> EVENT_FACTORY = () -> new ValueEvent();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return ToStringBuilder.reflectionToString(this);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,57 @@
|
|||||||
|
package com.baeldung.java8.lambda.exceptions;
|
||||||
|
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public class LambdaExceptionWrappers {
|
||||||
|
|
||||||
|
public static Consumer<Integer> lambdaWrapper(Consumer<Integer> consumer) {
|
||||||
|
return i -> {
|
||||||
|
try {
|
||||||
|
consumer.accept(i);
|
||||||
|
} catch (ArithmeticException e) {
|
||||||
|
System.err.println("Arithmetic Exception occured : " + e.getMessage());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static <T, E extends Exception> Consumer<T> consumerWrapper(Consumer<T> consumer, Class<E> clazz) {
|
||||||
|
return i -> {
|
||||||
|
try {
|
||||||
|
consumer.accept(i);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
try {
|
||||||
|
E exCast = clazz.cast(ex);
|
||||||
|
System.err.println("Exception occured : " + exCast.getMessage());
|
||||||
|
} catch (ClassCastException ccEx) {
|
||||||
|
throw ex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> Consumer<T> throwingConsumerWrapper(ThrowingConsumer<T, Exception> throwingConsumer) {
|
||||||
|
return i -> {
|
||||||
|
try {
|
||||||
|
throwingConsumer.accept(i);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException(ex);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T, E extends Exception> Consumer<T> handlingConsumerWrapper(ThrowingConsumer<T, E> throwingConsumer, Class<E> exceptionClass) {
|
||||||
|
return i -> {
|
||||||
|
try {
|
||||||
|
throwingConsumer.accept(i);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
try {
|
||||||
|
E exCast = exceptionClass.cast(ex);
|
||||||
|
System.err.println("Exception occured : " + exCast.getMessage());
|
||||||
|
} catch (ClassCastException ccEx) {
|
||||||
|
throw new RuntimeException(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.java8.lambda.exceptions;
|
||||||
|
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface ThrowingConsumer<T, E extends Exception> {
|
||||||
|
|
||||||
|
void accept(T t) throws E;
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,83 @@
|
|||||||
|
package com.baeldung.disruptor;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadFactory;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import com.lmax.disruptor.BusySpinWaitStrategy;
|
||||||
|
import com.lmax.disruptor.RingBuffer;
|
||||||
|
import com.lmax.disruptor.WaitStrategy;
|
||||||
|
import com.lmax.disruptor.dsl.Disruptor;
|
||||||
|
import com.lmax.disruptor.dsl.ProducerType;
|
||||||
|
import com.lmax.disruptor.util.DaemonThreadFactory;
|
||||||
|
|
||||||
|
public class DisruptorTest {
|
||||||
|
private Disruptor<ValueEvent> disruptor;
|
||||||
|
private WaitStrategy waitStrategy;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
waitStrategy = new BusySpinWaitStrategy();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createDisruptor(final ProducerType producerType, final EventConsumer eventConsumer) {
|
||||||
|
final ThreadFactory threadFactory = DaemonThreadFactory.INSTANCE;
|
||||||
|
disruptor = new Disruptor<ValueEvent>(ValueEvent.EVENT_FACTORY, 16, threadFactory, producerType, waitStrategy);
|
||||||
|
disruptor.handleEventsWith(eventConsumer.getEventHandler());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void startProducing(final RingBuffer<ValueEvent> ringBuffer, final int count, final EventProducer eventProducer) {
|
||||||
|
eventProducer.startProducing(ringBuffer, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMultipleProducerSingleConsumer_thenOutputInFifoOrder() {
|
||||||
|
final EventConsumer eventConsumer = new SingleEventPrintConsumer();
|
||||||
|
final EventProducer eventProducer = new DelayedMultiEventProducer();
|
||||||
|
createDisruptor(ProducerType.MULTI, eventConsumer);
|
||||||
|
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
|
||||||
|
|
||||||
|
startProducing(ringBuffer, 32, eventProducer);
|
||||||
|
|
||||||
|
disruptor.halt();
|
||||||
|
disruptor.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSingleProducerSingleConsumer_thenOutputInFifoOrder() {
|
||||||
|
final EventConsumer eventConsumer = new SingleEventConsumer();
|
||||||
|
final EventProducer eventProducer = new SingleEventProducer();
|
||||||
|
createDisruptor(ProducerType.SINGLE, eventConsumer);
|
||||||
|
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
|
||||||
|
|
||||||
|
startProducing(ringBuffer, 32, eventProducer);
|
||||||
|
|
||||||
|
disruptor.halt();
|
||||||
|
disruptor.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSingleProducerMultipleConsumer_thenOutputInFifoOrder() {
|
||||||
|
final EventConsumer eventConsumer = new MultiEventConsumer();
|
||||||
|
final EventProducer eventProducer = new SingleEventProducer();
|
||||||
|
createDisruptor(ProducerType.SINGLE, eventConsumer);
|
||||||
|
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
|
||||||
|
|
||||||
|
startProducing(ringBuffer, 32, eventProducer);
|
||||||
|
|
||||||
|
disruptor.halt();
|
||||||
|
disruptor.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMultipleProducerMultipleConsumer_thenOutputInFifoOrder() {
|
||||||
|
final EventConsumer eventConsumer = new MultiEventPrintConsumer();
|
||||||
|
final EventProducer eventProducer = new DelayedMultiEventProducer();
|
||||||
|
createDisruptor(ProducerType.MULTI, eventConsumer);
|
||||||
|
final RingBuffer<ValueEvent> ringBuffer = disruptor.start();
|
||||||
|
|
||||||
|
startProducing(ringBuffer, 32, eventProducer);
|
||||||
|
|
||||||
|
disruptor.halt();
|
||||||
|
disruptor.shutdown();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.disruptor;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import com.lmax.disruptor.EventHandler;
|
||||||
|
|
||||||
|
public class MultiEventConsumer implements EventConsumer {
|
||||||
|
|
||||||
|
private int expectedValue = -1;
|
||||||
|
private int otherExpectedValue = -1;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public EventHandler<ValueEvent>[] getEventHandler() {
|
||||||
|
final EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> assertExpectedValue(event.getValue());
|
||||||
|
final EventHandler<ValueEvent> otherEventHandler = (event, sequence, endOfBatch) -> assertOtherExpectedValue(event.getValue());
|
||||||
|
return new EventHandler[] { eventHandler, otherEventHandler };
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertExpectedValue(final int id) {
|
||||||
|
assertEquals(++expectedValue, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertOtherExpectedValue(final int id) {
|
||||||
|
assertEquals(++otherExpectedValue, id);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.disruptor;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import com.lmax.disruptor.EventHandler;
|
||||||
|
|
||||||
|
public class SingleEventConsumer implements EventConsumer {
|
||||||
|
|
||||||
|
private int expectedValue = -1;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public EventHandler<ValueEvent>[] getEventHandler() {
|
||||||
|
final EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> assertExpectedValue(event.getValue());
|
||||||
|
return new EventHandler[] { eventHandler };
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertExpectedValue(final int id) {
|
||||||
|
assertEquals(++expectedValue, id);
|
||||||
|
}
|
||||||
|
}
|
120
core-java/src/test/java/com/baeldung/guava/GuavaBiMapTest.java
Normal file
120
core-java/src/test/java/com/baeldung/guava/GuavaBiMapTest.java
Normal file
@ -0,0 +1,120 @@
|
|||||||
|
package com.baeldung.guava;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.Test;
|
||||||
|
import com.google.common.collect.BiMap;
|
||||||
|
import com.google.common.collect.EnumHashBiMap;
|
||||||
|
import com.google.common.collect.HashBiMap;
|
||||||
|
import com.google.common.collect.ImmutableBiMap;
|
||||||
|
|
||||||
|
public class GuavaBiMapTest {
|
||||||
|
@Test
|
||||||
|
public void whenQueryByValue_returnsKey() {
|
||||||
|
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
|
||||||
|
capitalCountryBiMap.put("New Delhi", "India");
|
||||||
|
capitalCountryBiMap.put("Washingon, D.C.", "USA");
|
||||||
|
capitalCountryBiMap.put("Moscow", "Russia");
|
||||||
|
|
||||||
|
final String countryCapitalName = capitalCountryBiMap.inverse().get("India");
|
||||||
|
|
||||||
|
assertEquals("New Delhi", countryCapitalName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCreateBiMapFromExistingMap_returnsKey() {
|
||||||
|
final Map<String, String> capitalCountryMap = new HashMap<>();
|
||||||
|
capitalCountryMap.put("New Delhi", "India");
|
||||||
|
capitalCountryMap.put("Washingon, D.C.", "USA");
|
||||||
|
capitalCountryMap.put("Moscow", "Russia");
|
||||||
|
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create(capitalCountryMap);
|
||||||
|
|
||||||
|
final String countryCapitalName = capitalCountryBiMap.inverse().get("India");
|
||||||
|
|
||||||
|
assertEquals("New Delhi", countryCapitalName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenQueryByKey_returnsValue() {
|
||||||
|
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
|
||||||
|
|
||||||
|
capitalCountryBiMap.put("New Delhi", "India");
|
||||||
|
capitalCountryBiMap.put("Washingon, D.C.", "USA");
|
||||||
|
capitalCountryBiMap.put("Moscow", "Russia");
|
||||||
|
|
||||||
|
assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C."));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void whenSameValueIsPresent_throwsException() {
|
||||||
|
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
|
||||||
|
|
||||||
|
capitalCountryBiMap.put("New Delhi", "India");
|
||||||
|
capitalCountryBiMap.put("Washingon, D.C.", "USA");
|
||||||
|
capitalCountryBiMap.put("Moscow", "Russia");
|
||||||
|
capitalCountryBiMap.put("Trump", "USA");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSameValueIsPresent_whenForcePut_completesSuccessfully() {
|
||||||
|
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
|
||||||
|
|
||||||
|
capitalCountryBiMap.put("New Delhi", "India");
|
||||||
|
capitalCountryBiMap.put("Washingon, D.C.", "USA");
|
||||||
|
capitalCountryBiMap.put("Moscow", "Russia");
|
||||||
|
capitalCountryBiMap.forcePut("Trump", "USA");
|
||||||
|
|
||||||
|
assertEquals("USA", capitalCountryBiMap.get("Trump"));
|
||||||
|
assertEquals("Trump", capitalCountryBiMap.inverse().get("USA"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSameKeyIsPresent_replacesAlreadyPresent() {
|
||||||
|
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
|
||||||
|
|
||||||
|
capitalCountryBiMap.put("New Delhi", "India");
|
||||||
|
capitalCountryBiMap.put("Washingon, D.C.", "USA");
|
||||||
|
capitalCountryBiMap.put("Moscow", "Russia");
|
||||||
|
capitalCountryBiMap.put("Washingon, D.C.", "HongKong");
|
||||||
|
|
||||||
|
assertEquals("HongKong", capitalCountryBiMap.get("Washingon, D.C."));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingImmutableBiMap_allowsPutSuccessfully() {
|
||||||
|
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
|
||||||
|
|
||||||
|
assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C."));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = UnsupportedOperationException.class)
|
||||||
|
public void whenUsingImmutableBiMap_doesntAllowRemove() {
|
||||||
|
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
|
||||||
|
|
||||||
|
capitalCountryBiMap.remove("New Delhi");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = UnsupportedOperationException.class)
|
||||||
|
public void whenUsingImmutableBiMap_doesntAllowPut() {
|
||||||
|
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
|
||||||
|
|
||||||
|
capitalCountryBiMap.put("New York", "USA");
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum Operation {
|
||||||
|
ADD, SUBTRACT, MULTIPLY, DIVIDE
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingEnumAsKeyInMap_replacesAlreadyPresent() {
|
||||||
|
final BiMap<Operation, String> operationStringBiMap = EnumHashBiMap.create(Operation.class);
|
||||||
|
|
||||||
|
operationStringBiMap.put(Operation.ADD, "Add");
|
||||||
|
operationStringBiMap.put(Operation.SUBTRACT, "Subtract");
|
||||||
|
operationStringBiMap.put(Operation.MULTIPLY, "Multiply");
|
||||||
|
operationStringBiMap.put(Operation.DIVIDE, "Divide");
|
||||||
|
|
||||||
|
assertEquals("Divide", operationStringBiMap.get(Operation.DIVIDE));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.java.conversion;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.StreamSupport;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
|
||||||
|
|
||||||
|
public class IterableStreamConversionTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIterable_whenConvertedToStream_thenNotNull() {
|
||||||
|
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||||
|
|
||||||
|
Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConvertedToList_thenCorrect() {
|
||||||
|
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||||
|
|
||||||
|
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
|
||||||
|
.map(String::toUpperCase).collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.java8;
|
||||||
|
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.anyOf;
|
||||||
|
import static org.hamcrest.Matchers.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class Java8FindAnyFindFirstTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void createStream_whenFindAnyResultIsPresent_thenCorrect() {
|
||||||
|
|
||||||
|
List<String> list = Arrays.asList("A","B","C","D");
|
||||||
|
|
||||||
|
Optional<String> result = list.stream().findAny();
|
||||||
|
|
||||||
|
assertTrue(result.isPresent());
|
||||||
|
assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void createStream_whenFindFirstResultIsPresent_thenCorrect() {
|
||||||
|
|
||||||
|
List<String> list = Arrays.asList("A","B","C","D");
|
||||||
|
|
||||||
|
Optional<String> result = list.stream().findFirst();
|
||||||
|
|
||||||
|
assertTrue(result.isPresent());
|
||||||
|
assertThat(result.get(),is("A"));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.java8.lambda.exceptions;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*;
|
||||||
|
|
||||||
|
public class LambdaExceptionWrappersTest {
|
||||||
|
|
||||||
|
private List<Integer> integers;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
integers = Arrays.asList(3, 9, 7, 0, 10, 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoExceptionFromLambdaWrapper_thenSuccess() {
|
||||||
|
integers.forEach(lambdaWrapper(i -> System.out.println(50 / i)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoExceptionFromConsumerWrapper_thenSuccess() {
|
||||||
|
integers.forEach(consumerWrapper(i -> System.out.println(50 / i), ArithmeticException.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = RuntimeException.class)
|
||||||
|
public void whenExceptionFromThrowingConsumerWrapper_thenSuccess() {
|
||||||
|
integers.forEach(throwingConsumerWrapper(i -> writeToFile(i)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoExceptionFromHandlingConsumerWrapper_thenSuccess() {
|
||||||
|
integers.forEach(handlingConsumerWrapper(i -> writeToFile(i), IOException.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writeToFile(Integer i) throws IOException {
|
||||||
|
if (i == 0) {
|
||||||
|
throw new IOException(); // mock IOException
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,2 +1,3 @@
|
|||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
||||||
|
- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
|
||||||
|
@ -1,38 +1,26 @@
|
|||||||
package org.baeldung.java.io;
|
package org.baeldung.java.io;
|
||||||
|
|
||||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileInputStream;
|
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.io.InputStreamReader;
|
|
||||||
import java.io.OutputStream;
|
|
||||||
import java.io.Reader;
|
|
||||||
import java.io.StringWriter;
|
|
||||||
import java.nio.charset.Charset;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
import java.util.Scanner;
|
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
|
||||||
import org.apache.commons.io.IOUtils;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import com.google.common.base.Charsets;
|
import com.google.common.base.Charsets;
|
||||||
import com.google.common.io.ByteSource;
|
import com.google.common.io.ByteSource;
|
||||||
import com.google.common.io.ByteStreams;
|
import com.google.common.io.ByteStreams;
|
||||||
import com.google.common.io.CharStreams;
|
import com.google.common.io.CharStreams;
|
||||||
import com.google.common.io.Files;
|
import com.google.common.io.Files;
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.apache.commons.io.IOUtils;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
public class JavaInputStreamToXUnitTest {
|
public class JavaInputStreamToXUnitTest {
|
||||||
@ -163,7 +151,7 @@ public class JavaInputStreamToXUnitTest {
|
|||||||
// tests - InputStream to File
|
// tests - InputStream to File
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingPlainJava_whenConvertingAnFullInputStreamToAFile_thenCorrect() throws IOException {
|
public final void whenConvertingToFile_thenCorrect() throws IOException {
|
||||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||||
final byte[] buffer = new byte[initialStream.available()];
|
final byte[] buffer = new byte[initialStream.available()];
|
||||||
initialStream.read(buffer);
|
initialStream.read(buffer);
|
||||||
@ -177,7 +165,7 @@ public class JavaInputStreamToXUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingPlainJava_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException {
|
public final void whenConvertingInProgressToFile_thenCorrect() throws IOException {
|
||||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||||
final OutputStream outStream = new FileOutputStream(targetFile);
|
final OutputStream outStream = new FileOutputStream(targetFile);
|
||||||
@ -193,7 +181,7 @@ public class JavaInputStreamToXUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingPlainJava8_whenConvertingAnInProgressInputStreamToAFile_thenCorrect() throws IOException {
|
public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException {
|
||||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||||
|
|
||||||
@ -203,7 +191,7 @@ public class JavaInputStreamToXUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingGuava_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException {
|
public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException {
|
||||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||||
final byte[] buffer = new byte[initialStream.available()];
|
final byte[] buffer = new byte[initialStream.available()];
|
||||||
initialStream.read(buffer);
|
initialStream.read(buffer);
|
||||||
@ -215,7 +203,7 @@ public class JavaInputStreamToXUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAFile_thenCorrect() throws IOException {
|
public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException {
|
||||||
final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
|
final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
|
||||||
|
|
||||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||||
|
@ -19,11 +19,10 @@
|
|||||||
</licenses>
|
</licenses>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- Explicitly declaring the source encoding eliminates the following
|
<!-- Explicitly declaring the source encoding eliminates the following message: -->
|
||||||
message: -->
|
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! -->
|
||||||
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
|
<project.build.sourceEncoding>
|
||||||
resources, i.e. build is platform dependent! -->
|
UTF-8</project.build.sourceEncoding>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
|
|
||||||
<slf4j.version>1.7.21</slf4j.version>
|
<slf4j.version>1.7.21</slf4j.version>
|
||||||
<querydsl.version>3.7.4</querydsl.version>
|
<querydsl.version>3.7.4</querydsl.version>
|
||||||
@ -32,8 +31,7 @@
|
|||||||
<!-- JBoss dependency versions -->
|
<!-- JBoss dependency versions -->
|
||||||
<wildfly.maven.plugin.version>1.0.2.Final</wildfly.maven.plugin.version>
|
<wildfly.maven.plugin.version>1.0.2.Final</wildfly.maven.plugin.version>
|
||||||
|
|
||||||
<!-- Define the version of the JBoss BOMs we want to import to specify
|
<!-- Define the version of the JBoss BOMs we want to import to specify tested stacks. -->
|
||||||
tested stacks. -->
|
|
||||||
<jboss.bom.version>8.2.2.Final</jboss.bom.version>
|
<jboss.bom.version>8.2.2.Final</jboss.bom.version>
|
||||||
|
|
||||||
<!-- other plugin versions -->
|
<!-- other plugin versions -->
|
||||||
@ -50,14 +48,11 @@
|
|||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill
|
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill of Materials (BOM). A BOM specifies the versions of a "stack"
|
||||||
of Materials (BOM). A BOM specifies the versions of a "stack" (or a collection)
|
(or a collection) of artifacts. We use this here so that we always get the correct versions of artifacts. Here we use the jboss-javaee-7.0-with-tools
|
||||||
of artifacts. We use this here so that we always get the correct versions
|
stack (you can read this as the JBoss stack of the Java EE 7 APIs, with some extras tools for your project, such as Arquillian for testing) and
|
||||||
of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you can
|
the jboss-javaee-7.0-with-hibernate stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras from the Hibernate family of
|
||||||
read this as the JBoss stack of the Java EE 7 APIs, with some extras tools
|
projects) -->
|
||||||
for your project, such as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate
|
|
||||||
stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras
|
|
||||||
from the Hibernate family of projects) -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.wildfly.bom</groupId>
|
<groupId>org.wildfly.bom</groupId>
|
||||||
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
|
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
|
||||||
@ -77,43 +72,37 @@
|
|||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
||||||
<!-- First declare the APIs we depend on and need for compilation. All
|
<!-- First declare the APIs we depend on and need for compilation. All of them are provided by JBoss WildFly -->
|
||||||
of them are provided by JBoss WildFly -->
|
|
||||||
|
|
||||||
<!-- Import the CDI API, we use provided scope as the API is included in
|
<!-- Import the CDI API, we use provided scope as the API is included in JBoss WildFly -->
|
||||||
JBoss WildFly -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.enterprise</groupId>
|
<groupId>javax.enterprise</groupId>
|
||||||
<artifactId>cdi-api</artifactId>
|
<artifactId>cdi-api</artifactId>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Import the Common Annotations API (JSR-250), we use provided scope
|
<!-- Import the Common Annotations API (JSR-250), we use provided scope as the API is included in JBoss WildFly -->
|
||||||
as the API is included in JBoss WildFly -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jboss.spec.javax.annotation</groupId>
|
<groupId>org.jboss.spec.javax.annotation</groupId>
|
||||||
<artifactId>jboss-annotations-api_1.2_spec</artifactId>
|
<artifactId>jboss-annotations-api_1.2_spec</artifactId>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Import the JAX-RS API, we use provided scope as the API is included
|
<!-- Import the JAX-RS API, we use provided scope as the API is included in JBoss WildFly -->
|
||||||
in JBoss WildFly -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jboss.resteasy</groupId>
|
<groupId>org.jboss.resteasy</groupId>
|
||||||
<artifactId>jaxrs-api</artifactId>
|
<artifactId>jaxrs-api</artifactId>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Import the JPA API, we use provided scope as the API is included in
|
<!-- Import the JPA API, we use provided scope as the API is included in JBoss WildFly -->
|
||||||
JBoss WildFly -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hibernate.javax.persistence</groupId>
|
<groupId>org.hibernate.javax.persistence</groupId>
|
||||||
<artifactId>hibernate-jpa-2.1-api</artifactId>
|
<artifactId>hibernate-jpa-2.1-api</artifactId>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Import the EJB API, we use provided scope as the API is included in
|
<!-- Import the EJB API, we use provided scope as the API is included in JBoss WildFly -->
|
||||||
JBoss WildFly -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jboss.spec.javax.ejb</groupId>
|
<groupId>org.jboss.spec.javax.ejb</groupId>
|
||||||
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
|
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
|
||||||
@ -135,8 +124,7 @@
|
|||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Import the JSF API, we use provided scope as the API is included in
|
<!-- Import the JSF API, we use provided scope as the API is included in JBoss WildFly -->
|
||||||
JBoss WildFly -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jboss.spec.javax.faces</groupId>
|
<groupId>org.jboss.spec.javax.faces</groupId>
|
||||||
<artifactId>jboss-jsf-api_2.2_spec</artifactId>
|
<artifactId>jboss-jsf-api_2.2_spec</artifactId>
|
||||||
@ -145,16 +133,14 @@
|
|||||||
|
|
||||||
<!-- Now we declare any tools needed -->
|
<!-- Now we declare any tools needed -->
|
||||||
|
|
||||||
<!-- Annotation processor to generate the JPA 2.0 metamodel classes for
|
<!-- Annotation processor to generate the JPA 2.0 metamodel classes for typesafe criteria queries -->
|
||||||
typesafe criteria queries -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hibernate</groupId>
|
<groupId>org.hibernate</groupId>
|
||||||
<artifactId>hibernate-jpamodelgen</artifactId>
|
<artifactId>hibernate-jpamodelgen</artifactId>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Annotation processor that raising compilation errors whenever constraint
|
<!-- Annotation processor that raising compilation errors whenever constraint annotations are incorrectly used. -->
|
||||||
annotations are incorrectly used. -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hibernate</groupId>
|
<groupId>org.hibernate</groupId>
|
||||||
<artifactId>hibernate-validator-annotation-processor</artifactId>
|
<artifactId>hibernate-validator-annotation-processor</artifactId>
|
||||||
@ -169,8 +155,7 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Optional, but highly recommended -->
|
<!-- Optional, but highly recommended -->
|
||||||
<!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA)
|
<!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA) JPA from JUnit/TestNG -->
|
||||||
JPA from JUnit/TestNG -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jboss.arquillian.junit</groupId>
|
<groupId>org.jboss.arquillian.junit</groupId>
|
||||||
<artifactId>arquillian-junit-container</artifactId>
|
<artifactId>arquillian-junit-container</artifactId>
|
||||||
@ -225,8 +210,7 @@
|
|||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<!-- Maven will append the version to the finalName (which is the name
|
<!-- Maven will append the version to the finalName (which is the name given to the generated war, and hence the context root) -->
|
||||||
given to the generated war, and hence the context root) -->
|
|
||||||
<finalName>${project.artifactId}</finalName>
|
<finalName>${project.artifactId}</finalName>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
@ -265,10 +249,8 @@
|
|||||||
|
|
||||||
<profiles>
|
<profiles>
|
||||||
<profile>
|
<profile>
|
||||||
<!-- The default profile skips all tests, though you can tune it to run
|
<!-- The default profile skips all tests, though you can tune it to run just unit tests based on a custom pattern -->
|
||||||
just unit tests based on a custom pattern -->
|
<!-- Seperate profiles are provided for running all tests, including Arquillian tests that execute in the specified container -->
|
||||||
<!-- Seperate profiles are provided for running all tests, including Arquillian
|
|
||||||
tests that execute in the specified container -->
|
|
||||||
<id>default</id>
|
<id>default</id>
|
||||||
<activation>
|
<activation>
|
||||||
<activeByDefault>true</activeByDefault>
|
<activeByDefault>true</activeByDefault>
|
||||||
@ -288,10 +270,8 @@
|
|||||||
|
|
||||||
<profile>
|
<profile>
|
||||||
|
|
||||||
<!-- An optional Arquillian testing profile that executes tests
|
<!-- An optional Arquillian testing profile that executes tests in your WildFly instance -->
|
||||||
in your WildFly instance -->
|
<!-- This profile will start a new WildFly instance, and execute the test, shutting it down when done -->
|
||||||
<!-- This profile will start a new WildFly instance, and execute the
|
|
||||||
test, shutting it down when done -->
|
|
||||||
<!-- Run with: mvn clean test -Parq-wildfly-managed -->
|
<!-- Run with: mvn clean test -Parq-wildfly-managed -->
|
||||||
<id>arq-wildfly-managed</id>
|
<id>arq-wildfly-managed</id>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
25
gradle/build.gradle
Normal file
25
gradle/build.gradle
Normal 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
3
gradle/gradle.properties
Normal 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
BIN
gradle/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
6
gradle/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
6
gradle/gradle/wrapper/gradle-wrapper.properties
vendored
Normal 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
160
gradle/gradlew
vendored
Normal 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
90
gradle/gradlew.bat
vendored
Normal 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
|
5
gradle/src/main/java/Main.java
Normal file
5
gradle/src/main/java/Main.java
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
public class Main{
|
||||||
|
public static void main(String[] args){
|
||||||
|
System.out.println("Baeldung Rocks");
|
||||||
|
}
|
||||||
|
}
|
@ -92,7 +92,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>19.0</guava.version>
|
<guava.version>21.0</guava.version>
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
<commons-collections4.version>4.1</commons-collections4.version>
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
|
|
||||||
|
@ -0,0 +1,63 @@
|
|||||||
|
package org.baeldung.guava;
|
||||||
|
|
||||||
|
import com.google.common.collect.ArrayListMultimap;
|
||||||
|
import com.google.common.collect.Multimap;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
|
||||||
|
public class GuavaMultiMapTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMap_whenAddTwoValuesForSameKey_shouldOverridePreviousKey() {
|
||||||
|
//given
|
||||||
|
String key = "a-key";
|
||||||
|
Map<String, String> map = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
//when
|
||||||
|
map.put(key, "firstValue");
|
||||||
|
map.put(key, "secondValue");
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertEquals(1, map.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiMap_whenAddTwoValuesForSameKey_shouldHaveTwoEntriesInMap() {
|
||||||
|
//given
|
||||||
|
String key = "a-key";
|
||||||
|
Multimap<String, String> map = ArrayListMultimap.create();
|
||||||
|
|
||||||
|
//when
|
||||||
|
map.put(key, "firstValue");
|
||||||
|
map.put(key, "secondValue");
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertEquals(2, map.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMapOfListValues_whenAddTwoValuesForSameKey_shouldHaveTwoElementsInList() {
|
||||||
|
//given
|
||||||
|
String key = "a-key";
|
||||||
|
Map<String, List<String>> map = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
//when
|
||||||
|
List<String> values = map.get(key);
|
||||||
|
if(values == null){
|
||||||
|
values = new LinkedList<>();
|
||||||
|
values.add("firstValue");
|
||||||
|
values.add("secondValue");
|
||||||
|
}
|
||||||
|
map.put(key, values);
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertEquals(1, map.size());
|
||||||
|
}
|
||||||
|
}
|
@ -8,10 +8,9 @@ import static org.junit.Assert.assertTrue;
|
|||||||
|
|
||||||
import java.nio.charset.Charset;
|
import java.nio.charset.Charset;
|
||||||
import java.nio.charset.CharsetEncoder;
|
import java.nio.charset.CharsetEncoder;
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
|
import com.google.common.collect.*;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.google.common.base.CharMatcher;
|
import com.google.common.base.CharMatcher;
|
||||||
@ -19,9 +18,6 @@ import com.google.common.base.Function;
|
|||||||
import com.google.common.base.Joiner;
|
import com.google.common.base.Joiner;
|
||||||
import com.google.common.base.Predicate;
|
import com.google.common.base.Predicate;
|
||||||
import com.google.common.base.Splitter;
|
import com.google.common.base.Splitter;
|
||||||
import com.google.common.collect.Iterables;
|
|
||||||
import com.google.common.collect.Lists;
|
|
||||||
import com.google.common.collect.Maps;
|
|
||||||
|
|
||||||
public class GuavaStringTest {
|
public class GuavaStringTest {
|
||||||
|
|
||||||
|
@ -28,13 +28,14 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
|||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Ignore;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
@Ignore("Server is not available")
|
|
||||||
public class HttpClientMultipartLiveTest {
|
public class HttpClientMultipartLiveTest {
|
||||||
|
|
||||||
private static final String SERVER = "http://echo.200please.com";
|
// No longer available
|
||||||
|
// private static final String SERVER = "http://echo.200please.com";
|
||||||
|
|
||||||
|
private static final String SERVER = "http://posttestserver.com/post.php";
|
||||||
private static final String TEXTFILENAME = "temp.txt";
|
private static final String TEXTFILENAME = "temp.txt";
|
||||||
private static final String IMAGEFILENAME = "image.jpg";
|
private static final String IMAGEFILENAME = "image.jpg";
|
||||||
private static final String ZIPFILENAME = "zipFile.zip";
|
private static final String ZIPFILENAME = "zipFile.zip";
|
||||||
@ -46,7 +47,8 @@ public class HttpClientMultipartLiveTest {
|
|||||||
|
|
||||||
@Before
|
@Before
|
||||||
public final void before() {
|
public final void before() {
|
||||||
client = HttpClientBuilder.create().build();
|
client = HttpClientBuilder.create()
|
||||||
|
.build();
|
||||||
post = new HttpPost(SERVER);
|
post = new HttpPost(SERVER);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -80,7 +82,9 @@ public class HttpClientMultipartLiveTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
|
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
|
||||||
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME);
|
final URL url = Thread.currentThread()
|
||||||
|
.getContextClassLoader()
|
||||||
|
.getResource("uploads/" + TEXTFILENAME);
|
||||||
|
|
||||||
final File file = new File(url.getPath());
|
final File file = new File(url.getPath());
|
||||||
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
|
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
|
||||||
@ -97,11 +101,12 @@ public class HttpClientMultipartLiveTest {
|
|||||||
post.setEntity(entity);
|
post.setEntity(entity);
|
||||||
response = client.execute(post);
|
response = client.execute(post);
|
||||||
|
|
||||||
final int statusCode = response.getStatusLine().getStatusCode();
|
final int statusCode = response.getStatusLine()
|
||||||
|
.getStatusCode();
|
||||||
final String responseString = getContent();
|
final String responseString = getContent();
|
||||||
final String contentTypeInHeader = getContentTypeHeader();
|
final String contentTypeInHeader = getContentTypeHeader();
|
||||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||||
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||||
System.out.println(responseString);
|
System.out.println(responseString);
|
||||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||||
@ -109,7 +114,9 @@ public class HttpClientMultipartLiveTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException {
|
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException {
|
||||||
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME);
|
final URL url = Thread.currentThread()
|
||||||
|
.getContextClassLoader()
|
||||||
|
.getResource("uploads/" + TEXTFILENAME);
|
||||||
final File file = new File(url.getPath());
|
final File file = new File(url.getPath());
|
||||||
final String message = "This is a multipart post";
|
final String message = "This is a multipart post";
|
||||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||||
@ -119,11 +126,12 @@ public class HttpClientMultipartLiveTest {
|
|||||||
final HttpEntity entity = builder.build();
|
final HttpEntity entity = builder.build();
|
||||||
post.setEntity(entity);
|
post.setEntity(entity);
|
||||||
response = client.execute(post);
|
response = client.execute(post);
|
||||||
final int statusCode = response.getStatusLine().getStatusCode();
|
final int statusCode = response.getStatusLine()
|
||||||
|
.getStatusCode();
|
||||||
final String responseString = getContent();
|
final String responseString = getContent();
|
||||||
final String contentTypeInHeader = getContentTypeHeader();
|
final String contentTypeInHeader = getContentTypeHeader();
|
||||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||||
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||||
System.out.println(responseString);
|
System.out.println(responseString);
|
||||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||||
@ -131,8 +139,12 @@ public class HttpClientMultipartLiveTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
|
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
|
||||||
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + ZIPFILENAME);
|
final URL url = Thread.currentThread()
|
||||||
final URL url2 = Thread.currentThread().getContextClassLoader().getResource("uploads/" + IMAGEFILENAME);
|
.getContextClassLoader()
|
||||||
|
.getResource("uploads/" + ZIPFILENAME);
|
||||||
|
final URL url2 = Thread.currentThread()
|
||||||
|
.getContextClassLoader()
|
||||||
|
.getResource("uploads/" + IMAGEFILENAME);
|
||||||
final InputStream inputStream = new FileInputStream(url.getPath());
|
final InputStream inputStream = new FileInputStream(url.getPath());
|
||||||
final File file = new File(url2.getPath());
|
final File file = new File(url2.getPath());
|
||||||
final String message = "This is a multipart post";
|
final String message = "This is a multipart post";
|
||||||
@ -144,11 +156,12 @@ public class HttpClientMultipartLiveTest {
|
|||||||
final HttpEntity entity = builder.build();
|
final HttpEntity entity = builder.build();
|
||||||
post.setEntity(entity);
|
post.setEntity(entity);
|
||||||
response = client.execute(post);
|
response = client.execute(post);
|
||||||
final int statusCode = response.getStatusLine().getStatusCode();
|
final int statusCode = response.getStatusLine()
|
||||||
|
.getStatusCode();
|
||||||
final String responseString = getContent();
|
final String responseString = getContent();
|
||||||
final String contentTypeInHeader = getContentTypeHeader();
|
final String contentTypeInHeader = getContentTypeHeader();
|
||||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||||
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||||
System.out.println(responseString);
|
System.out.println(responseString);
|
||||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||||
@ -166,11 +179,12 @@ public class HttpClientMultipartLiveTest {
|
|||||||
final HttpEntity entity = builder.build();
|
final HttpEntity entity = builder.build();
|
||||||
post.setEntity(entity);
|
post.setEntity(entity);
|
||||||
response = client.execute(post);
|
response = client.execute(post);
|
||||||
final int statusCode = response.getStatusLine().getStatusCode();
|
final int statusCode = response.getStatusLine()
|
||||||
|
.getStatusCode();
|
||||||
final String responseString = getContent();
|
final String responseString = getContent();
|
||||||
final String contentTypeInHeader = getContentTypeHeader();
|
final String contentTypeInHeader = getContentTypeHeader();
|
||||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||||
assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
|
||||||
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
|
||||||
System.out.println(responseString);
|
System.out.println(responseString);
|
||||||
System.out.println("POST Content Type: " + contentTypeInHeader);
|
System.out.println("POST Content Type: " + contentTypeInHeader);
|
||||||
@ -179,7 +193,8 @@ public class HttpClientMultipartLiveTest {
|
|||||||
// UTIL
|
// UTIL
|
||||||
|
|
||||||
final String getContent() throws IOException {
|
final String getContent() throws IOException {
|
||||||
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
|
rd = new BufferedReader(new InputStreamReader(response.getEntity()
|
||||||
|
.getContent()));
|
||||||
String body = "";
|
String body = "";
|
||||||
String content = "";
|
String content = "";
|
||||||
while ((body = rd.readLine()) != null) {
|
while ((body = rd.readLine()) != null) {
|
||||||
@ -189,7 +204,9 @@ public class HttpClientMultipartLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final String getContentTypeHeader() throws IOException {
|
final String getContentTypeHeader() throws IOException {
|
||||||
return post.getEntity().getContentType().toString();
|
return post.getEntity()
|
||||||
|
.getContentType()
|
||||||
|
.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,24 @@
|
|||||||
package org.baeldung.httpclient;
|
package org.baeldung.httpclient;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.security.GeneralSecurityException;
|
||||||
|
|
||||||
|
import javax.net.ssl.SSLContext;
|
||||||
|
import javax.net.ssl.SSLHandshakeException;
|
||||||
|
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
import org.apache.http.conn.ClientConnectionManager;
|
import org.apache.http.conn.ClientConnectionManager;
|
||||||
import org.apache.http.conn.scheme.Scheme;
|
import org.apache.http.conn.scheme.Scheme;
|
||||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||||
import org.apache.http.conn.ssl.*;
|
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||||
|
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||||
|
import org.apache.http.conn.ssl.SSLSocketFactory;
|
||||||
|
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
|
||||||
|
import org.apache.http.conn.ssl.TrustStrategy;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.DefaultHttpClient;
|
import org.apache.http.impl.client.DefaultHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
@ -15,14 +28,6 @@ import org.apache.http.ssl.SSLContextBuilder;
|
|||||||
import org.apache.http.ssl.SSLContexts;
|
import org.apache.http.ssl.SSLContexts;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import javax.net.ssl.SSLContext;
|
|
||||||
import javax.net.ssl.SSLException;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.security.GeneralSecurityException;
|
|
||||||
|
|
||||||
import static org.hamcrest.CoreMatchers.equalTo;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This test requires a localhost server over HTTPS <br>
|
* This test requires a localhost server over HTTPS <br>
|
||||||
* It should only be manually run, not part of the automated build
|
* It should only be manually run, not part of the automated build
|
||||||
@ -35,13 +40,15 @@ public class HttpsClientSslLiveTest {
|
|||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
||||||
@Test(expected = SSLException.class)
|
@Test(expected = SSLHandshakeException.class)
|
||||||
public final void whenHttpsUrlIsConsumed_thenException() throws IOException {
|
public final void whenHttpsUrlIsConsumed_thenException() throws IOException {
|
||||||
final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
|
final CloseableHttpClient httpClient = HttpClientBuilder.create()
|
||||||
|
.build();
|
||||||
|
|
||||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||||
final HttpResponse response = httpClient.execute(getMethod);
|
final HttpResponse response = httpClient.execute(getMethod);
|
||||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
assertThat(response.getStatusLine()
|
||||||
|
.getStatusCode(), equalTo(200));
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
@ -57,7 +64,8 @@ public class HttpsClientSslLiveTest {
|
|||||||
|
|
||||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||||
final HttpResponse response = httpClient.execute(getMethod);
|
final HttpResponse response = httpClient.execute(getMethod);
|
||||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
assertThat(response.getStatusLine()
|
||||||
|
.getStatusCode(), equalTo(200));
|
||||||
|
|
||||||
httpClient.close();
|
httpClient.close();
|
||||||
}
|
}
|
||||||
@ -65,44 +73,62 @@ public class HttpsClientSslLiveTest {
|
|||||||
@Test
|
@Test
|
||||||
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
|
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
|
||||||
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||||
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
|
final SSLContext sslContext = SSLContexts.custom()
|
||||||
|
.loadTrustMaterial(null, acceptingTrustStrategy)
|
||||||
|
.build();
|
||||||
|
|
||||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
|
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
|
||||||
|
|
||||||
final CloseableHttpClient httpClient = HttpClients.custom().setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLSocketFactory(sslsf).build();
|
final CloseableHttpClient httpClient = HttpClients.custom()
|
||||||
|
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
|
||||||
|
.setSSLSocketFactory(sslsf)
|
||||||
|
.build();
|
||||||
|
|
||||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||||
final HttpResponse response = httpClient.execute(getMethod);
|
final HttpResponse response = httpClient.execute(getMethod);
|
||||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
assertThat(response.getStatusLine()
|
||||||
|
.getStatusCode(), equalTo(200));
|
||||||
|
|
||||||
httpClient.close();
|
httpClient.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
|
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
|
||||||
final SSLContextBuilder builder = new SSLContextBuilder();
|
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
|
||||||
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
|
.build();
|
||||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
|
final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
|
||||||
final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
|
|
||||||
|
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
|
||||||
|
final CloseableHttpClient httpClient = HttpClients.custom()
|
||||||
|
.setSSLHostnameVerifier(hostnameVerifier)
|
||||||
|
.setSSLSocketFactory(sslsf)
|
||||||
|
.build();
|
||||||
|
|
||||||
// new
|
// new
|
||||||
|
|
||||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||||
final HttpResponse response = httpClient.execute(getMethod);
|
final HttpResponse response = httpClient.execute(getMethod);
|
||||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
assertThat(response.getStatusLine()
|
||||||
|
.getStatusCode(), equalTo(200));
|
||||||
|
httpClient.close();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
|
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
|
||||||
SSLContext sslContext = new SSLContextBuilder()
|
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true)
|
||||||
.loadTrustMaterial(null, (certificate, authType) -> true).build();
|
.build();
|
||||||
|
|
||||||
final CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
|
final CloseableHttpClient client = HttpClients.custom()
|
||||||
|
.setSSLContext(sslContext)
|
||||||
|
.setSSLHostnameVerifier(new NoopHostnameVerifier())
|
||||||
|
.build();
|
||||||
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
|
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
|
||||||
httpGet.setHeader("Accept", "application/xml");
|
httpGet.setHeader("Accept", "application/xml");
|
||||||
|
|
||||||
final HttpResponse response = client.execute(httpGet);
|
final HttpResponse response = client.execute(httpGet);
|
||||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
assertThat(response.getStatusLine()
|
||||||
|
.getStatusCode(), equalTo(200));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.jackson.inheritance;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||||
|
|
||||||
|
@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "eventType")
|
||||||
|
abstract public class Event {
|
||||||
|
private final String id;
|
||||||
|
private final Long timestamp;
|
||||||
|
|
||||||
|
@JsonCreator
|
||||||
|
public Event(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp) {
|
||||||
|
this.id = id;
|
||||||
|
this.timestamp = timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getTimestamp() {
|
||||||
|
return timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.jackson.inheritance;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||||
|
|
||||||
|
@JsonTypeName("itemIdAddedToUser")
|
||||||
|
@JsonIgnoreProperties("id")
|
||||||
|
public class ItemIdAddedToUser extends Event {
|
||||||
|
private final String itemId;
|
||||||
|
private final Long quantity;
|
||||||
|
|
||||||
|
@JsonCreator
|
||||||
|
public ItemIdAddedToUser(@JsonProperty("id") String id,
|
||||||
|
@JsonProperty("timestamp") Long timestamp,
|
||||||
|
@JsonProperty("itemId") String itemId,
|
||||||
|
@JsonProperty("quantity") Long quantity) {
|
||||||
|
super(id, timestamp);
|
||||||
|
this.itemId = itemId;
|
||||||
|
this.quantity = quantity;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getItemId() {
|
||||||
|
return itemId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getQuantity() {
|
||||||
|
return quantity;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.jackson.inheritance;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||||
|
|
||||||
|
@JsonTypeName("itemIdRemovedFromUser")
|
||||||
|
public class ItemIdRemovedFromUser extends Event {
|
||||||
|
private final String itemId;
|
||||||
|
private final Long quantity;
|
||||||
|
|
||||||
|
@JsonCreator
|
||||||
|
public ItemIdRemovedFromUser(@JsonProperty("id") String id,
|
||||||
|
@JsonProperty("timestamp") Long timestamp,
|
||||||
|
@JsonProperty("itemId") String itemId,
|
||||||
|
@JsonProperty("quantity") Long quantity) {
|
||||||
|
super(id, timestamp);
|
||||||
|
this.itemId = itemId;
|
||||||
|
this.quantity = quantity;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getItemId() {
|
||||||
|
return itemId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getQuantity() {
|
||||||
|
return quantity;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.jackson.dtos.withEnum;
|
||||||
|
|
||||||
|
public enum DistanceEnumSimple {
|
||||||
|
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||||
|
|
||||||
|
private String unit;
|
||||||
|
private final double meters;
|
||||||
|
|
||||||
|
private DistanceEnumSimple(String unit, double meters) {
|
||||||
|
this.unit = unit;
|
||||||
|
this.meters = meters;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getMeters() {
|
||||||
|
return meters;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUnit() {
|
||||||
|
return unit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUnit(String unit) {
|
||||||
|
this.unit = unit;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.jackson.dtos.withEnum;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||||
|
|
||||||
|
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
|
||||||
|
public enum DistanceEnumWithJsonFormat {
|
||||||
|
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||||
|
|
||||||
|
private String unit;
|
||||||
|
private final double meters;
|
||||||
|
|
||||||
|
private DistanceEnumWithJsonFormat(String unit, double meters) {
|
||||||
|
this.unit = unit;
|
||||||
|
this.meters = meters;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getMeters() {
|
||||||
|
return meters;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUnit() {
|
||||||
|
return unit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUnit(String unit) {
|
||||||
|
this.unit = unit;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,59 @@
|
|||||||
|
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 Distance type;
|
||||||
|
|
||||||
|
public MyDtoWithEnumCustom() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public MyDtoWithEnumCustom(final String stringValue, final int intValue, final boolean booleanValue, final Distance type) {
|
||||||
|
super();
|
||||||
|
|
||||||
|
this.stringValue = stringValue;
|
||||||
|
this.intValue = intValue;
|
||||||
|
this.booleanValue = booleanValue;
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
// API
|
||||||
|
|
||||||
|
public String getStringValue() {
|
||||||
|
return stringValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStringValue(final String stringValue) {
|
||||||
|
this.stringValue = stringValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getIntValue() {
|
||||||
|
return intValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIntValue(final int intValue) {
|
||||||
|
this.intValue = intValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isBooleanValue() {
|
||||||
|
return booleanValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBooleanValue(final boolean booleanValue) {
|
||||||
|
this.booleanValue = booleanValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Distance getType() {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setType(final Distance type) {
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,57 @@
|
|||||||
|
package com.baeldung.jackson.dtos.withEnum;
|
||||||
|
|
||||||
|
public class MyDtoWithEnumJsonFormat {
|
||||||
|
|
||||||
|
private String stringValue;
|
||||||
|
private int intValue;
|
||||||
|
private boolean booleanValue;
|
||||||
|
private DistanceEnumWithJsonFormat distanceType;
|
||||||
|
|
||||||
|
public MyDtoWithEnumJsonFormat() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
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.distanceType = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
// API
|
||||||
|
|
||||||
|
public String getStringValue() {
|
||||||
|
return stringValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStringValue(final String stringValue) {
|
||||||
|
this.stringValue = stringValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getIntValue() {
|
||||||
|
return intValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIntValue(final int intValue) {
|
||||||
|
this.intValue = intValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isBooleanValue() {
|
||||||
|
return booleanValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBooleanValue(final boolean booleanValue) {
|
||||||
|
this.booleanValue = booleanValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public DistanceEnumWithJsonFormat getDistanceType() {
|
||||||
|
return distanceType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDistanceType(final DistanceEnumWithJsonFormat type) {
|
||||||
|
this.distanceType = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.jackson.inheritance;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class ItemIdRemovedFromUserTest {
|
||||||
|
@Test
|
||||||
|
public void givenRemoveItemJson_whenDeserialize_shouldHaveProperClassType() throws IOException {
|
||||||
|
//given
|
||||||
|
Event event = new ItemIdRemovedFromUser("1", 12345567L, "item_1", 2L);
|
||||||
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
String eventJson = objectMapper.writeValueAsString(event);
|
||||||
|
|
||||||
|
//when
|
||||||
|
Event result = new ObjectMapper().readValue(eventJson, Event.class);
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertTrue(result instanceof ItemIdRemovedFromUser);
|
||||||
|
assertEquals("item_1", ((ItemIdRemovedFromUser) result).getItemId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAdddItemJson_whenSerialize_shouldIgnoreIdPropertyFromSuperclass() throws IOException {
|
||||||
|
//given
|
||||||
|
Event event = new ItemIdAddedToUser("1", 12345567L, "item_1", 2L);
|
||||||
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
|
//when
|
||||||
|
String eventJson = objectMapper.writeValueAsString(event);
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertFalse(eventJson.contains("id"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,6 +1,32 @@
|
|||||||
package com.baeldung.jackson.test;
|
package com.baeldung.jackson.test;
|
||||||
|
|
||||||
import com.baeldung.jackson.annotation.*;
|
import static org.hamcrest.Matchers.containsString;
|
||||||
|
import static org.hamcrest.Matchers.is;
|
||||||
|
import static org.hamcrest.Matchers.not;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.jackson.annotation.BeanWithCreator;
|
||||||
|
import com.baeldung.jackson.annotation.BeanWithCustomAnnotation;
|
||||||
|
import com.baeldung.jackson.annotation.BeanWithFilter;
|
||||||
|
import com.baeldung.jackson.annotation.BeanWithGetter;
|
||||||
|
import com.baeldung.jackson.annotation.BeanWithIgnore;
|
||||||
|
import com.baeldung.jackson.annotation.BeanWithInject;
|
||||||
|
import com.baeldung.jackson.annotation.ExtendableBean;
|
||||||
|
import com.baeldung.jackson.annotation.MyBean;
|
||||||
|
import com.baeldung.jackson.annotation.PrivateBean;
|
||||||
|
import com.baeldung.jackson.annotation.RawBean;
|
||||||
|
import com.baeldung.jackson.annotation.UnwrappedUser;
|
||||||
|
import com.baeldung.jackson.annotation.UserWithIgnoreType;
|
||||||
|
import com.baeldung.jackson.annotation.Zoo;
|
||||||
import com.baeldung.jackson.bidirection.ItemWithIdentity;
|
import com.baeldung.jackson.bidirection.ItemWithIdentity;
|
||||||
import com.baeldung.jackson.bidirection.ItemWithRef;
|
import com.baeldung.jackson.bidirection.ItemWithRef;
|
||||||
import com.baeldung.jackson.bidirection.UserWithIdentity;
|
import com.baeldung.jackson.bidirection.UserWithIdentity;
|
||||||
@ -8,7 +34,7 @@ import com.baeldung.jackson.bidirection.UserWithRef;
|
|||||||
import com.baeldung.jackson.date.EventWithFormat;
|
import com.baeldung.jackson.date.EventWithFormat;
|
||||||
import com.baeldung.jackson.date.EventWithSerializer;
|
import com.baeldung.jackson.date.EventWithSerializer;
|
||||||
import com.baeldung.jackson.dtos.MyMixInForIgnoreType;
|
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.exception.UserWithRoot;
|
||||||
import com.baeldung.jackson.jsonview.Item;
|
import com.baeldung.jackson.jsonview.Item;
|
||||||
import com.baeldung.jackson.jsonview.Views;
|
import com.baeldung.jackson.jsonview.Views;
|
||||||
@ -20,17 +46,6 @@ import com.fasterxml.jackson.databind.SerializationFeature;
|
|||||||
import com.fasterxml.jackson.databind.ser.FilterProvider;
|
import com.fasterxml.jackson.databind.ser.FilterProvider;
|
||||||
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
|
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
|
||||||
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
|
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.text.ParseException;
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.TimeZone;
|
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.*;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
public class JacksonAnnotationTest {
|
public class JacksonAnnotationTest {
|
||||||
|
|
||||||
@ -85,10 +100,10 @@ public class JacksonAnnotationTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSerializingUsingJsonValue_thenCorrect() throws JsonProcessingException {
|
public void whenSerializingUsingJsonValue_thenCorrect() throws IOException {
|
||||||
final String enumAsString = new ObjectMapper().writeValueAsString(TypeEnumWithValue.TYPE1);
|
final String enumAsString = new ObjectMapper().writeValueAsString(DistanceEnumWithValue.MILE);
|
||||||
|
|
||||||
assertThat(enumAsString, is("\"Type A\""));
|
assertThat(enumAsString, is("1609.34"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -6,14 +6,14 @@ import static org.junit.Assert.assertThat;
|
|||||||
|
|
||||||
import java.io.IOException;
|
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 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.core.JsonParseException;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
@ -24,10 +24,9 @@ public class JacksonSerializationEnumsUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public final void whenSerializingASimpleEnum_thenCorrect() throws JsonParseException, IOException {
|
public final void whenSerializingASimpleEnum_thenCorrect() throws JsonParseException, IOException {
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
final String enumAsString = mapper.writeValueAsString(TypeEnumSimple.TYPE1);
|
final String enumAsString = mapper.writeValueAsString(DistanceEnumSimple.MILE);
|
||||||
System.out.println(enumAsString);
|
|
||||||
|
|
||||||
assertThat(enumAsString, containsString("TYPE1"));
|
assertThat(enumAsString, containsString("MILE"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests - enum with main value
|
// tests - enum with main value
|
||||||
@ -35,10 +34,9 @@ public class JacksonSerializationEnumsUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public final void whenSerializingAEnumWithValue_thenCorrect() throws JsonParseException, IOException {
|
public final void whenSerializingAEnumWithValue_thenCorrect() throws JsonParseException, IOException {
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
final String enumAsString = mapper.writeValueAsString(TypeEnumWithValue.TYPE1);
|
final String enumAsString = mapper.writeValueAsString(DistanceEnumWithValue.MILE);
|
||||||
System.out.println(enumAsString);
|
|
||||||
|
|
||||||
assertThat(enumAsString, is("\"Type A\""));
|
assertThat(enumAsString, is("1609.34"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests - enum
|
// tests - enum
|
||||||
@ -46,28 +44,25 @@ public class JacksonSerializationEnumsUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public final void whenSerializingAnEnum_thenCorrect() throws JsonParseException, IOException {
|
public final void whenSerializingAnEnum_thenCorrect() throws JsonParseException, IOException {
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
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("\"meters\":1609.34"));
|
||||||
assertThat(enumAsString, containsString("\"name\":\"Type A\""));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException {
|
public final void whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException {
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
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("\"meters\":1609.34"));
|
||||||
assertThat(enumAsString, containsString("\"name\":\"Type A\""));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenSerializingArrayOfEnums_thenCorrect() throws JsonParseException, IOException {
|
public final void whenSerializingArrayOfEnums_thenCorrect() throws JsonParseException, IOException {
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
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("\"meters\":1609.34"));
|
||||||
assertThat(json, containsString("\"name\":\"Type A\""));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests - enum with custom serializer
|
// tests - enum with custom serializer
|
||||||
@ -75,10 +70,9 @@ public class JacksonSerializationEnumsUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public final void givenCustomSerializer_whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException {
|
public final void givenCustomSerializer_whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException {
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
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("\"meters\":1609.34"));
|
||||||
assertThat(enumAsString, containsString("\"name\":\"Type A\""));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
5
java-mongodb/.gitignore
vendored
Normal file
5
java-mongodb/.gitignore
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
.classpath
|
||||||
|
.project
|
||||||
|
.settings
|
||||||
|
target
|
||||||
|
build
|
98
java-mongodb/pom.xml
Normal file
98
java-mongodb/pom.xml
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
<?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>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>${maven-surefire-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
|
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
<testFailureIgnore>true</testFailureIgnore>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<profile>
|
||||||
|
<id>integration</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>integration-test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>test</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
<includes>
|
||||||
|
<include>**/*IntegrationTest.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<systemPropertyVariables>
|
||||||
|
<test.mime>json</test.mime>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
53
java-mongodb/src/main/java/com/baeldung/MongoExample.java
Normal file
53
java-mongodb/src/main/java/com/baeldung/MongoExample.java
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
@ -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 AppIntegrationTest {
|
||||||
|
|
||||||
|
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
javax-servlets/README.md
Normal file
2
javax-servlets/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
|
@ -10,7 +10,7 @@
|
|||||||
<packaging>war</packaging>
|
<packaging>war</packaging>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<java.min.version>1.7</java.min.version>
|
<java.min.version>1.8</java.min.version>
|
||||||
<maven.min.version>3.0.0</maven.min.version>
|
<maven.min.version>3.0.0</maven.min.version>
|
||||||
|
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
|
43
jee7/src/main/java/com/baeldung/json/Person.java
Normal file
43
jee7/src/main/java/com/baeldung/json/Person.java
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.json;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
private String firstName;
|
||||||
|
private String lastName;
|
||||||
|
private Date birthdate;
|
||||||
|
private List<String> emails;
|
||||||
|
|
||||||
|
public String getFirstName() {
|
||||||
|
return firstName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFirstName(String firstName) {
|
||||||
|
this.firstName = firstName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLastName() {
|
||||||
|
return lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLastName(String lastName) {
|
||||||
|
this.lastName = lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Date getBirthdate() {
|
||||||
|
return birthdate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBirthdate(Date birthdate) {
|
||||||
|
this.birthdate = birthdate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getEmails() {
|
||||||
|
return emails;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmails(List<String> emails) {
|
||||||
|
this.emails = emails;
|
||||||
|
}
|
||||||
|
}
|
42
jee7/src/main/java/com/baeldung/json/PersonBuilder.java
Normal file
42
jee7/src/main/java/com/baeldung/json/PersonBuilder.java
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
package com.baeldung.json;
|
||||||
|
|
||||||
|
import javax.json.*;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.StringReader;
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
public class PersonBuilder {
|
||||||
|
private String jsonString;
|
||||||
|
|
||||||
|
private SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
|
||||||
|
|
||||||
|
public PersonBuilder(String jsonString) {
|
||||||
|
this.jsonString = jsonString;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Person build() throws IOException, ParseException {
|
||||||
|
JsonReader reader = Json.createReader(new StringReader(jsonString));
|
||||||
|
|
||||||
|
JsonObject jsonObject = reader.readObject();
|
||||||
|
|
||||||
|
Person person = new Person();
|
||||||
|
|
||||||
|
person.setFirstName(jsonObject.getString("firstName"));
|
||||||
|
person.setLastName(jsonObject.getString("lastName"));
|
||||||
|
person.setBirthdate(dateFormat.parse(jsonObject.getString("birthdate")));
|
||||||
|
|
||||||
|
JsonArray emailsJson = jsonObject.getJsonArray("emails");
|
||||||
|
|
||||||
|
List<String> emails = emailsJson.getValuesAs(JsonString.class).stream()
|
||||||
|
.map(JsonString::getString)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
person.setEmails(emails);
|
||||||
|
|
||||||
|
return person;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
60
jee7/src/main/java/com/baeldung/json/PersonWriter.java
Normal file
60
jee7/src/main/java/com/baeldung/json/PersonWriter.java
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
package com.baeldung.json;
|
||||||
|
|
||||||
|
import javax.json.*;
|
||||||
|
import javax.json.stream.JsonGenerator;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
import java.io.Writer;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class PersonWriter {
|
||||||
|
private Person person;
|
||||||
|
|
||||||
|
private SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
|
||||||
|
|
||||||
|
public PersonWriter(Person person) {
|
||||||
|
this.person = person;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String write() throws IOException {
|
||||||
|
JsonObjectBuilder objectBuilder = Json
|
||||||
|
.createObjectBuilder()
|
||||||
|
.add("firstName", person.getFirstName())
|
||||||
|
.add("lastName", person.getLastName())
|
||||||
|
.add("birthdate", dateFormat.format(person.getBirthdate()));
|
||||||
|
|
||||||
|
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
|
||||||
|
|
||||||
|
person.getEmails().forEach(arrayBuilder::add);
|
||||||
|
|
||||||
|
objectBuilder.add("emails", arrayBuilder);
|
||||||
|
|
||||||
|
JsonObject jsonObject = objectBuilder.build();
|
||||||
|
|
||||||
|
JsonWriterFactory writerFactory = createWriterFactory();
|
||||||
|
|
||||||
|
return writeToString(jsonObject, writerFactory);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private String writeToString(JsonObject jsonObject, JsonWriterFactory writerFactory) throws IOException {
|
||||||
|
String jsonString;
|
||||||
|
try (Writer writer = new StringWriter()) {
|
||||||
|
writerFactory
|
||||||
|
.createWriter(writer)
|
||||||
|
.write(jsonObject);
|
||||||
|
jsonString = writer.toString();
|
||||||
|
}
|
||||||
|
return jsonString;
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonWriterFactory createWriterFactory() {
|
||||||
|
Map<String, Boolean> config = new HashMap<>();
|
||||||
|
|
||||||
|
config.put(JsonGenerator.PRETTY_PRINTING, true);
|
||||||
|
|
||||||
|
return Json.createWriterFactory(config);
|
||||||
|
}
|
||||||
|
}
|
135
jee7/src/test/java/com/baeldug/json/JsonUnitTest.java
Normal file
135
jee7/src/test/java/com/baeldug/json/JsonUnitTest.java
Normal file
@ -0,0 +1,135 @@
|
|||||||
|
package com.baeldug.json;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.hasItems;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.StringReader;
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import javax.json.Json;
|
||||||
|
import javax.json.JsonObject;
|
||||||
|
import javax.json.JsonReader;
|
||||||
|
import javax.json.stream.JsonParser;
|
||||||
|
import javax.json.stream.JsonParser.Event;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.json.Person;
|
||||||
|
import com.baeldung.json.PersonBuilder;
|
||||||
|
import com.baeldung.json.PersonWriter;
|
||||||
|
|
||||||
|
public class JsonUnitTest {
|
||||||
|
private Person person;
|
||||||
|
|
||||||
|
private SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
|
||||||
|
private String personJson;
|
||||||
|
private String petshopJson;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPersonIsConvertedToString_thenAValidJsonStringIsReturned() throws IOException {
|
||||||
|
String generatedJsonString = new PersonWriter(person).write();
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"Generated String has the expected format and content",
|
||||||
|
personJson,
|
||||||
|
generatedJsonString);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenJsonStringIsConvertedToPerson_thenAValidObjectIsReturned(
|
||||||
|
) throws IOException, ParseException {
|
||||||
|
Person person = new PersonBuilder(personJson).build();
|
||||||
|
|
||||||
|
assertEquals("First name has expected value", "Michael", person.getFirstName());
|
||||||
|
assertEquals("Last name has expected value", "Scott", person.getLastName());
|
||||||
|
assertEquals(
|
||||||
|
"Birthdate has expected value",
|
||||||
|
dateFormat.parse("06/15/1978"),
|
||||||
|
person.getBirthdate());
|
||||||
|
assertThat(
|
||||||
|
"Email list has two items",
|
||||||
|
person.getEmails(),
|
||||||
|
hasItems("michael.scott@dd.com", "michael.scarn@gmail.com"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingObjectModelToQueryForSpecificProperty_thenExpectedValueIsReturned(
|
||||||
|
) throws IOException, ParseException {
|
||||||
|
JsonReader reader = Json.createReader(new StringReader(petshopJson));
|
||||||
|
|
||||||
|
JsonObject jsonObject = reader.readObject();
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"The query should return the 'name' property of the third pet from the list",
|
||||||
|
"Jake",
|
||||||
|
jsonObject.getJsonArray("pets").getJsonObject(2).getString("name"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingStreamingApiToQueryForSpecificProperty_thenExpectedValueIsReturned(
|
||||||
|
) throws IOException, ParseException {
|
||||||
|
JsonParser jsonParser = Json.createParser(new StringReader(petshopJson));
|
||||||
|
|
||||||
|
int count = 0;
|
||||||
|
String result = null;
|
||||||
|
|
||||||
|
while(jsonParser.hasNext()) {
|
||||||
|
Event e = jsonParser.next();
|
||||||
|
|
||||||
|
if (e == Event.KEY_NAME) {
|
||||||
|
if(jsonParser.getString().equals("name")) {
|
||||||
|
jsonParser.next();
|
||||||
|
|
||||||
|
if(++count == 3) {
|
||||||
|
result = jsonParser.getString();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"The query should return the 'name' property of the third pet from the list",
|
||||||
|
"Jake",
|
||||||
|
result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() throws ParseException {
|
||||||
|
// Creates a Person object
|
||||||
|
person = new Person();
|
||||||
|
|
||||||
|
person.setFirstName("Michael");
|
||||||
|
person.setLastName("Scott");
|
||||||
|
person.setBirthdate(dateFormat.parse("06/15/1978"));
|
||||||
|
person.setEmails(Arrays.asList("michael.scott@dd.com", "michael.scarn@gmail.com"));
|
||||||
|
|
||||||
|
// Initializes the Person Json
|
||||||
|
personJson = "\n" +
|
||||||
|
"{\n" +
|
||||||
|
" \"firstName\":\"Michael\",\n" +
|
||||||
|
" \"lastName\":\"Scott\",\n" +
|
||||||
|
" \"birthdate\":\"06/15/1978\",\n" +
|
||||||
|
" \"emails\":[\n" +
|
||||||
|
" \"michael.scott@dd.com\",\n" +
|
||||||
|
" \"michael.scarn@gmail.com\"\n" +
|
||||||
|
" ]\n" +
|
||||||
|
"}";
|
||||||
|
|
||||||
|
// Initializes the Pet Shop Json
|
||||||
|
petshopJson = "\n" +
|
||||||
|
"{\n" +
|
||||||
|
" \"ownerId\":\"1\", \n" +
|
||||||
|
" \"pets\":[ \n" +
|
||||||
|
" {\"name\": \"Kitty\", \"type\": \"cat\"}, \n" +
|
||||||
|
" {\"name\": \"Rex\", \"type\": \"dog\"}, \n" +
|
||||||
|
" {\"name\": \"Jake\", \"type\": \"dog\"} \n" +
|
||||||
|
" ]\n" +
|
||||||
|
"}";
|
||||||
|
}
|
||||||
|
}
|
10
jsoup/README.md
Normal file
10
jsoup/README.md
Normal 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
|
@ -15,15 +15,16 @@
|
|||||||
<version>${jsoup.version}</version>
|
<version>${jsoup.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>commons-io</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>${commons.io.version}</version>
|
<version>4.12</version>
|
||||||
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
<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>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
@ -1,47 +1,52 @@
|
|||||||
package com.baeldung.jsoup;
|
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.HttpStatusException;
|
||||||
import org.jsoup.Jsoup;
|
import org.jsoup.Jsoup;
|
||||||
import org.jsoup.nodes.Document;
|
import org.jsoup.nodes.Document;
|
||||||
import org.jsoup.nodes.Element;
|
import org.jsoup.nodes.Element;
|
||||||
import org.jsoup.parser.Tag;
|
import org.jsoup.parser.Tag;
|
||||||
import org.jsoup.select.Elements;
|
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 {
|
import static org.junit.Assert.assertEquals;
|
||||||
scrapeSpringBlog();
|
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 {
|
@Test
|
||||||
String blogUrl = "https://spring.io/blog";
|
public void loadDocument404() throws IOException {
|
||||||
Document doc = Jsoup.connect(blogUrl).get();
|
|
||||||
|
|
||||||
try {
|
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) {
|
} catch (HttpStatusException ex) {
|
||||||
System.out.println(ex.getMessage());
|
assertEquals(404, ex.getStatusCode());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Document docCustomConn = Jsoup.connect(blogUrl).userAgent("Mozilla").get();
|
@Test
|
||||||
docCustomConn = Jsoup.connect(blogUrl).timeout(5000).get();
|
public void loadDocumentCustomized() throws IOException {
|
||||||
docCustomConn = Jsoup.connect(blogUrl).cookie("cookiename", "val234").get();
|
doc = Jsoup.connect("https://spring.io/blog")
|
||||||
// docCustomConn = Jsoup.connect(blogUrl).data("datakey", "datavalue").post();
|
|
||||||
docCustomConn = Jsoup.connect(blogUrl).header("headersecurity", "xyz123").get();
|
|
||||||
|
|
||||||
docCustomConn = Jsoup.connect(blogUrl)
|
|
||||||
.userAgent("Mozilla")
|
.userAgent("Mozilla")
|
||||||
.timeout(5000)
|
.timeout(5000)
|
||||||
.cookie("cookiename", "val234")
|
.cookie("cookiename", "val234")
|
||||||
.cookie("anothercookie", "ilovejsoup")
|
.cookie("anothercookie", "ilovejsoup")
|
||||||
|
.referrer("http://google.com")
|
||||||
.header("headersecurity", "xyz123")
|
.header("headersecurity", "xyz123")
|
||||||
.get();
|
.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void examplesSelectors() {
|
||||||
Elements links = doc.select("a");
|
Elements links = doc.select("a");
|
||||||
Elements sections = doc.select("section");
|
|
||||||
Elements logo = doc.select(".spring-logo--container");
|
Elements logo = doc.select(".spring-logo--container");
|
||||||
Elements pagination = doc.select("#pagination_control");
|
Elements pagination = doc.select("#pagination_control");
|
||||||
Elements divsDescendant = doc.select("header div");
|
Elements divsDescendant = doc.select("header div");
|
||||||
@ -50,6 +55,15 @@ public class JsoupExample {
|
|||||||
Element pag = doc.getElementById("pagination_control");
|
Element pag = doc.getElementById("pagination_control");
|
||||||
Elements desktopOnly = doc.getElementsByClass("desktopOnly");
|
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 firstSection = sections.first();
|
||||||
Element lastSection = sections.last();
|
Element lastSection = sections.last();
|
||||||
Element secondSection = sections.get(2);
|
Element secondSection = sections.get(2);
|
||||||
@ -58,10 +72,11 @@ public class JsoupExample {
|
|||||||
Elements children = firstSection.children();
|
Elements children = firstSection.children();
|
||||||
Elements siblings = firstSection.siblingElements();
|
Elements siblings = firstSection.siblingElements();
|
||||||
|
|
||||||
sections.stream().forEach(el -> System.out.println("section: " + el));
|
sections.forEach(el -> System.out.println("section: " + el));
|
||||||
|
}
|
||||||
Elements sectionParagraphs = firstSection.select(".paragraph");
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void examplesExtracting() {
|
||||||
Element firstArticle = doc.select("article").first();
|
Element firstArticle = doc.select("article").first();
|
||||||
Element timeElement = firstArticle.select("time").first();
|
Element timeElement = firstArticle.select("time").first();
|
||||||
String dateTimeOfFirstArticle = timeElement.attr("datetime");
|
String dateTimeOfFirstArticle = timeElement.attr("datetime");
|
||||||
@ -69,7 +84,15 @@ public class JsoupExample {
|
|||||||
String sectionDivText = sectionDiv.text();
|
String sectionDivText = sectionDiv.text();
|
||||||
String articleHtml = firstArticle.html();
|
String articleHtml = firstArticle.html();
|
||||||
String outerHtml = firstArticle.outerHtml();
|
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");
|
timeElement.attr("datetime", "2016-12-16 15:19:54.3");
|
||||||
sectionDiv.text("foo bar");
|
sectionDiv.text("foo bar");
|
||||||
firstArticle.select("h2").html("<div><span></span></div>");
|
firstArticle.select("h2").html("<div><span></span></div>");
|
||||||
@ -83,7 +106,6 @@ public class JsoupExample {
|
|||||||
doc.select("li.navbar-link").remove();
|
doc.select("li.navbar-link").remove();
|
||||||
firstArticle.select("img").remove();
|
firstArticle.select("img").remove();
|
||||||
|
|
||||||
File indexFile = new File("/tmp", "spring_blog_home.html");
|
assertTrue(doc.html().contains("http://baeldung.com"));
|
||||||
FileUtils.writeStringToFile(indexFile, doc.html(), doc.charset());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
65
kotlin/pom.xml
Normal file
65
kotlin/pom.xml
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
<?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>kotlin</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jetbrains.kotlin</groupId>
|
||||||
|
<artifactId>kotlin-stdlib</artifactId>
|
||||||
|
<version>${kotlin-stdlib.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jetbrains.kotlin</groupId>
|
||||||
|
<artifactId>kotlin-test-junit</artifactId>
|
||||||
|
<version>${kotlin-test-junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
|
||||||
|
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>kotlin-maven-plugin</artifactId>
|
||||||
|
<groupId>org.jetbrains.kotlin</groupId>
|
||||||
|
<version>${kotlin-maven-plugin.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>compile</id>
|
||||||
|
<goals>
|
||||||
|
<goal>compile</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
|
||||||
|
<execution>
|
||||||
|
<id>test-compile</id>
|
||||||
|
<goals>
|
||||||
|
<goal>test-compile</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<kotlin-test-junit.version>1.0.4</kotlin-test-junit.version>
|
||||||
|
<kotlin-stdlib.version>1.0.4</kotlin-stdlib.version>
|
||||||
|
<kotlin-maven-plugin.version>1.0.4</kotlin-maven-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
5
kotlin/src/main/kotlin/com/baeldung/kotlin/Example1.kt
Normal file
5
kotlin/src/main/kotlin/com/baeldung/kotlin/Example1.kt
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
fun main(args: Array<String>){
|
||||||
|
println("hello word")
|
||||||
|
}
|
14
kotlin/src/main/kotlin/com/baeldung/kotlin/Item.kt
Normal file
14
kotlin/src/main/kotlin/com/baeldung/kotlin/Item.kt
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
open class Item(val id: String, val name: String = "unknown_name") {
|
||||||
|
open fun getIdOfItem(): String {
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ItemWithCategory(id: String, name: String, val categoryId: String) : Item(id, name) {
|
||||||
|
override fun getIdOfItem(): String {
|
||||||
|
return id + name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
66
kotlin/src/main/kotlin/com/baeldung/kotlin/ItemService.kt
Normal file
66
kotlin/src/main/kotlin/com/baeldung/kotlin/ItemService.kt
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
import java.util.*
|
||||||
|
|
||||||
|
class ItemService {
|
||||||
|
fun findItemNameForId(id: String): Item? {
|
||||||
|
val itemId = UUID.randomUUID().toString()
|
||||||
|
return Item(itemId, "name-$itemId")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ItemManager(val categoryId: String, val dbConnection: String) {
|
||||||
|
var email = ""
|
||||||
|
|
||||||
|
constructor(categoryId: String, dbConnection: String, email: String)
|
||||||
|
: this(categoryId, dbConnection) {
|
||||||
|
this.email = email
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isFromSpecificCategory(catId: String): Boolean {
|
||||||
|
return categoryId == catId
|
||||||
|
}
|
||||||
|
|
||||||
|
fun makeAnalyisOfCategory(catId: String): Unit {
|
||||||
|
val result = if (catId == "100") "Yes" else "No"
|
||||||
|
println(result)
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
val numbers = arrayOf("first", "second", "third", "fourth")
|
||||||
|
|
||||||
|
var concat = ""
|
||||||
|
for (n in numbers) {
|
||||||
|
concat += n
|
||||||
|
}
|
||||||
|
|
||||||
|
var sum = 0
|
||||||
|
for (i in 2..9) {
|
||||||
|
sum += i
|
||||||
|
}
|
||||||
|
|
||||||
|
val firstName = "Tom"
|
||||||
|
val secondName = "Mary"
|
||||||
|
val concatOfNames = "$firstName + $secondName"
|
||||||
|
println("Names: $concatOfNames")
|
||||||
|
|
||||||
|
val itemManager = ItemManager("cat_id", "db://connection")
|
||||||
|
val result = "function result: ${itemManager.isFromSpecificCategory("1")}"
|
||||||
|
println(result)
|
||||||
|
|
||||||
|
val number = 2
|
||||||
|
if (number < 10) {
|
||||||
|
println("number less that 10")
|
||||||
|
} else if (number > 10) {
|
||||||
|
println("number is greater that 10")
|
||||||
|
}
|
||||||
|
|
||||||
|
val name = "John"
|
||||||
|
when (name) {
|
||||||
|
"John" -> println("Hi man")
|
||||||
|
"Alice" -> println("Hi lady")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
14
kotlin/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt
Normal file
14
kotlin/src/main/kotlin/com/baeldung/kotlin/ListExtension.kt
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadLocalRandom
|
||||||
|
|
||||||
|
class ListExtension {
|
||||||
|
fun <T> List<T>.random(): T? {
|
||||||
|
if (this.isEmpty()) return null
|
||||||
|
return get(ThreadLocalRandom.current().nextInt(count()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun <T> getRandomElementOfList(list: List<T>): T? {
|
||||||
|
return list.random()
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
import kotlin.test.assertNotNull
|
||||||
|
|
||||||
|
class ItemServiceTest {
|
||||||
|
@Test
|
||||||
|
fun givenItemId_whenGetForOptionalItem_shouldMakeActionOnNonNullValue() {
|
||||||
|
//given
|
||||||
|
val id = "item_id"
|
||||||
|
val itemService = ItemService()
|
||||||
|
|
||||||
|
//when
|
||||||
|
val result = itemService.findItemNameForId(id)
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertNotNull(result?.let { it -> it.id })
|
||||||
|
assertNotNull(result!!.id)
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
import com.baeldung.kotlin.ListExtension
|
||||||
|
import org.junit.Test
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class ListExtensionTest {
|
||||||
|
@Test
|
||||||
|
fun givenList_whenExecuteExtensionFunctionOnList_shouldReturnRandomElementOfList(){
|
||||||
|
//given
|
||||||
|
val elements = listOf("a", "b", "c")
|
||||||
|
|
||||||
|
//when
|
||||||
|
val result = ListExtension().getRandomElementOfList(elements)
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertTrue(elements.contains(result))
|
||||||
|
}
|
||||||
|
}
|
75
metrics/pom.xml
Normal file
75
metrics/pom.xml
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>metrics</artifactId>
|
||||||
|
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<dep.ver.metrics>3.1.2</dep.ver.metrics>
|
||||||
|
<dep.ver.servlet>3.1.0</dep.ver.servlet>
|
||||||
|
<dep.ver.junit>4.12</dep.ver.junit>
|
||||||
|
|
||||||
|
<maven.compiler-plugin.version>3.6.0</maven.compiler-plugin.version>
|
||||||
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.dropwizard.metrics</groupId>
|
||||||
|
<artifactId>metrics-core</artifactId>
|
||||||
|
<version>${dep.ver.metrics}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.dropwizard.metrics</groupId>
|
||||||
|
<artifactId>metrics-healthchecks</artifactId>
|
||||||
|
<version>${dep.ver.metrics}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.dropwizard.metrics</groupId>
|
||||||
|
<artifactId>metrics-servlets</artifactId>
|
||||||
|
<version>${dep.ver.metrics}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.dropwizard.metrics</groupId>
|
||||||
|
<artifactId>metrics-servlet</artifactId>
|
||||||
|
<version>${dep.ver.metrics}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.servlet</groupId>
|
||||||
|
<artifactId>javax.servlet-api</artifactId>
|
||||||
|
<version>${dep.ver.servlet}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>${dep.ver.junit}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven.compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${maven.compiler.source}</source>
|
||||||
|
<target>${maven.compiler.target}</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.metrics.core;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.codahale.metrics.DerivativeGauge;
|
||||||
|
import com.codahale.metrics.Gauge;
|
||||||
|
|
||||||
|
public class ActiveUserCountGauge extends DerivativeGauge<List<Long>, Integer> {
|
||||||
|
public ActiveUserCountGauge(Gauge<List<Long>> base) {
|
||||||
|
super(base);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Integer transform(List<Long> value) {
|
||||||
|
return value.size();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.metrics.core;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import com.codahale.metrics.CachedGauge;
|
||||||
|
|
||||||
|
public class ActiveUsersGauge extends CachedGauge<List<Long>> {
|
||||||
|
public ActiveUsersGauge(long timeout, TimeUnit timeoutUnit) {
|
||||||
|
super(timeout, timeoutUnit);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected List<Long> loadValue() {
|
||||||
|
return getActiveUserCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Long> getActiveUserCount() {
|
||||||
|
// mock reading from database and count the active users, return a fixed value
|
||||||
|
List<Long> result = new ArrayList<Long>();
|
||||||
|
result.add(12L);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.metrics.core;
|
||||||
|
|
||||||
|
import com.codahale.metrics.RatioGauge;
|
||||||
|
|
||||||
|
public class AttendanceRatioGauge extends RatioGauge {
|
||||||
|
private int attendanceCount;
|
||||||
|
private int courseCount;
|
||||||
|
|
||||||
|
public AttendanceRatioGauge(int attendanceCount, int courseCount) {
|
||||||
|
this.attendanceCount = attendanceCount;
|
||||||
|
this.courseCount = courseCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Ratio getRatio() {
|
||||||
|
return Ratio.of(attendanceCount, courseCount);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.metrics.healthchecks;
|
||||||
|
|
||||||
|
import com.codahale.metrics.health.HealthCheck;
|
||||||
|
|
||||||
|
public class DatabaseHealthCheck extends HealthCheck {
|
||||||
|
@Override
|
||||||
|
protected Result check() throws Exception {
|
||||||
|
return Result.healthy();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.metrics.healthchecks;
|
||||||
|
|
||||||
|
import com.codahale.metrics.health.HealthCheck;
|
||||||
|
|
||||||
|
public class UserCenterHealthCheck extends HealthCheck {
|
||||||
|
@Override
|
||||||
|
protected Result check() throws Exception {
|
||||||
|
return Result.healthy();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.metrics.servlet;
|
||||||
|
|
||||||
|
import com.codahale.metrics.MetricRegistry;
|
||||||
|
import com.codahale.metrics.servlet.InstrumentedFilterContextListener;
|
||||||
|
|
||||||
|
public class MyInstrumentedFilterContextListener extends InstrumentedFilterContextListener {
|
||||||
|
public static final MetricRegistry REGISTRY = new MetricRegistry();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected MetricRegistry getMetricRegistry() {
|
||||||
|
return REGISTRY;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.metrics.servlets;
|
||||||
|
|
||||||
|
import com.baeldung.metrics.healthchecks.DatabaseHealthCheck;
|
||||||
|
import com.codahale.metrics.health.HealthCheckRegistry;
|
||||||
|
import com.codahale.metrics.servlets.HealthCheckServlet;
|
||||||
|
|
||||||
|
public class MyHealthCheckServletContextListener extends HealthCheckServlet.ContextListener {
|
||||||
|
public static final HealthCheckRegistry HEALTH_CHECK_REGISTRY = new HealthCheckRegistry();
|
||||||
|
|
||||||
|
static {
|
||||||
|
HEALTH_CHECK_REGISTRY.register("db", new DatabaseHealthCheck());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected HealthCheckRegistry getHealthCheckRegistry() {
|
||||||
|
return HEALTH_CHECK_REGISTRY;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.metrics.servlets;
|
||||||
|
|
||||||
|
import com.codahale.metrics.Counter;
|
||||||
|
import com.codahale.metrics.Histogram;
|
||||||
|
import com.codahale.metrics.MetricRegistry;
|
||||||
|
import com.codahale.metrics.servlets.MetricsServlet;
|
||||||
|
|
||||||
|
public class MyMetricsServletContextListener extends MetricsServlet.ContextListener {
|
||||||
|
private static final MetricRegistry METRIC_REGISTRY = new MetricRegistry();
|
||||||
|
|
||||||
|
static {
|
||||||
|
Counter counter = METRIC_REGISTRY.counter("m01-counter");
|
||||||
|
counter.inc();
|
||||||
|
|
||||||
|
Histogram histogram = METRIC_REGISTRY.histogram("m02-histogram");
|
||||||
|
histogram.update(5);
|
||||||
|
histogram.update(20);
|
||||||
|
histogram.update(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected MetricRegistry getMetricRegistry() {
|
||||||
|
return METRIC_REGISTRY;
|
||||||
|
}
|
||||||
|
}
|
152
metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java
Normal file
152
metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
package com.baeldung.metrics.core;
|
||||||
|
|
||||||
|
import com.codahale.metrics.*;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
public class MetricsTest {
|
||||||
|
@Test
|
||||||
|
public void whenMarkMeter_thenCorrectRates() throws InterruptedException {
|
||||||
|
Meter meter = new Meter();
|
||||||
|
long initCount = meter.getCount();
|
||||||
|
|
||||||
|
assertThat(initCount, equalTo(0L));
|
||||||
|
|
||||||
|
meter.mark();
|
||||||
|
|
||||||
|
assertThat(meter.getCount(), equalTo(1L));
|
||||||
|
|
||||||
|
meter.mark(20);
|
||||||
|
|
||||||
|
assertThat(meter.getCount(), equalTo(21L));
|
||||||
|
|
||||||
|
// not use assert for these rate values because they change every time when this test is run
|
||||||
|
double meanRate = meter.getMeanRate();
|
||||||
|
double oneMinRate = meter.getOneMinuteRate();
|
||||||
|
double fiveMinRate = meter.getFiveMinuteRate();
|
||||||
|
double fifteenMinRate = meter.getFifteenMinuteRate();
|
||||||
|
System.out.println(meanRate);
|
||||||
|
System.out.println(oneMinRate);
|
||||||
|
System.out.println(fiveMinRate);
|
||||||
|
System.out.println(fifteenMinRate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInitRatioGauge_thenCorrectRatio() {
|
||||||
|
Gauge<Double> ratioGauge = new AttendanceRatioGauge(15, 20);
|
||||||
|
|
||||||
|
assertThat(ratioGauge.getValue(), equalTo(0.75));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUseCacheGauge_thenCorrectGauge() {
|
||||||
|
Gauge<List<Long>> activeUsersGauge = new ActiveUsersGauge(15, TimeUnit.MINUTES);
|
||||||
|
List<Long> expected = new ArrayList<Long>();
|
||||||
|
expected.add(12L);
|
||||||
|
|
||||||
|
assertThat(activeUsersGauge.getValue(), equalTo(expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUseDerivativeGauge_thenCorrectGaugeFromBase() {
|
||||||
|
Gauge<List<Long>> activeUsersGauge = new ActiveUsersGauge(15, TimeUnit.MINUTES);
|
||||||
|
Gauge<Integer> activeUserCountGauge = new ActiveUserCountGauge(activeUsersGauge);
|
||||||
|
|
||||||
|
assertThat(activeUserCountGauge.getValue(), equalTo(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenIncDecCounter_thenCorrectCount() {
|
||||||
|
Counter counter = new Counter();
|
||||||
|
long initCount = counter.getCount();
|
||||||
|
|
||||||
|
assertThat(initCount, equalTo(0L));
|
||||||
|
|
||||||
|
counter.inc();
|
||||||
|
|
||||||
|
assertThat(counter.getCount(), equalTo(1L));
|
||||||
|
|
||||||
|
counter.inc(11);
|
||||||
|
|
||||||
|
assertThat(counter.getCount(), equalTo(12L));
|
||||||
|
|
||||||
|
counter.dec();
|
||||||
|
|
||||||
|
assertThat(counter.getCount(), equalTo(11L));
|
||||||
|
|
||||||
|
counter.dec(6);
|
||||||
|
|
||||||
|
assertThat(counter.getCount(), equalTo(5L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUpdateHistogram_thenCorrectDistributionData() {
|
||||||
|
Histogram histogram = new Histogram(new UniformReservoir());
|
||||||
|
histogram.update(5);
|
||||||
|
long count1 = histogram.getCount();
|
||||||
|
|
||||||
|
assertThat(count1, equalTo(1L));
|
||||||
|
|
||||||
|
Snapshot snapshot1 = histogram.getSnapshot();
|
||||||
|
assertThat(snapshot1.getValues().length, equalTo(1));
|
||||||
|
assertThat(snapshot1.getValues()[0], equalTo(5L));
|
||||||
|
assertThat(snapshot1.getMax(), equalTo(5L));
|
||||||
|
assertThat(snapshot1.getMin(), equalTo(5L));
|
||||||
|
assertThat(snapshot1.getMean(), equalTo(5.0));
|
||||||
|
assertThat(snapshot1.getMedian(), equalTo(5.0));
|
||||||
|
assertThat(snapshot1.getStdDev(), equalTo(0.0));
|
||||||
|
assertThat(snapshot1.get75thPercentile(), equalTo(5.0));
|
||||||
|
assertThat(snapshot1.get95thPercentile(), equalTo(5.0));
|
||||||
|
assertThat(snapshot1.get98thPercentile(), equalTo(5.0));
|
||||||
|
assertThat(snapshot1.get99thPercentile(), equalTo(5.0));
|
||||||
|
assertThat(snapshot1.get999thPercentile(), equalTo(5.0));
|
||||||
|
|
||||||
|
histogram.update(20);
|
||||||
|
long count2 = histogram.getCount();
|
||||||
|
|
||||||
|
assertThat(count2, equalTo(2L));
|
||||||
|
|
||||||
|
Snapshot snapshot2 = histogram.getSnapshot();
|
||||||
|
|
||||||
|
assertThat(snapshot2.getValues().length, equalTo(2));
|
||||||
|
assertThat(snapshot2.getValues()[0], equalTo(5L));
|
||||||
|
assertThat(snapshot2.getValues()[1], equalTo(20L));
|
||||||
|
assertThat(snapshot2.getMax(), equalTo(20L));
|
||||||
|
assertThat(snapshot2.getMin(), equalTo(5L));
|
||||||
|
assertThat(snapshot2.getMean(), equalTo(12.5));
|
||||||
|
assertThat(snapshot2.getMedian(), equalTo(12.5));
|
||||||
|
assertEquals(10.6, snapshot2.getStdDev(), 0.1);
|
||||||
|
assertThat(snapshot2.get75thPercentile(), equalTo(20.0));
|
||||||
|
assertThat(snapshot2.get95thPercentile(), equalTo(20.0));
|
||||||
|
assertThat(snapshot2.get98thPercentile(), equalTo(20.0));
|
||||||
|
assertThat(snapshot2.get99thPercentile(), equalTo(20.0));
|
||||||
|
assertThat(snapshot2.get999thPercentile(), equalTo(20.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUseTimer_thenCorrectTimerContexts() throws InterruptedException {
|
||||||
|
Timer timer = new Timer();
|
||||||
|
Timer.Context context1 = timer.time();
|
||||||
|
TimeUnit.SECONDS.sleep(5);
|
||||||
|
|
||||||
|
long elapsed1 = context1.stop();
|
||||||
|
|
||||||
|
assertEquals(5000000000L, elapsed1, 10000000);
|
||||||
|
assertThat(timer.getCount(), equalTo(1L));
|
||||||
|
assertEquals(0.2, timer.getMeanRate(), 0.1);
|
||||||
|
|
||||||
|
Timer.Context context2 = timer.time();
|
||||||
|
TimeUnit.SECONDS.sleep(2);
|
||||||
|
context2.close();
|
||||||
|
|
||||||
|
assertThat(timer.getCount(), equalTo(2L));
|
||||||
|
assertEquals(0.3, timer.getMeanRate(), 0.1);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.metrics.core;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.codahale.metrics.*;
|
||||||
|
|
||||||
|
public class ReporterTest {
|
||||||
|
@Test
|
||||||
|
public void whenConsoleReporter_thenOutputReport() {
|
||||||
|
MetricRegistry metricRegistry = new MetricRegistry();
|
||||||
|
|
||||||
|
Meter meter = metricRegistry.meter("meter");
|
||||||
|
meter.mark();
|
||||||
|
meter.mark(200);
|
||||||
|
Histogram histogram = metricRegistry.histogram("histogram");
|
||||||
|
histogram.update(12);
|
||||||
|
histogram.update(17);
|
||||||
|
histogram.update(20);
|
||||||
|
Counter counter = metricRegistry.counter("counter");
|
||||||
|
counter.inc();
|
||||||
|
counter.dec();
|
||||||
|
counter.inc();
|
||||||
|
counter.inc();
|
||||||
|
counter.inc();
|
||||||
|
counter.inc();
|
||||||
|
|
||||||
|
ConsoleReporter reporter = ConsoleReporter.forRegistry(metricRegistry).build();
|
||||||
|
reporter.start(5, TimeUnit.MICROSECONDS);
|
||||||
|
reporter.report();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.metrics.healthchecks;
|
||||||
|
|
||||||
|
import com.codahale.metrics.health.HealthCheck;
|
||||||
|
import com.codahale.metrics.health.HealthCheckRegistry;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class HealthCheckTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUseHealthCheck_thenHealthChecked() {
|
||||||
|
HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
|
||||||
|
|
||||||
|
healthCheckRegistry.register("db", new DatabaseHealthCheck());
|
||||||
|
healthCheckRegistry.register("uc", new UserCenterHealthCheck());
|
||||||
|
|
||||||
|
assertThat(healthCheckRegistry.getNames().size(), equalTo(2));
|
||||||
|
|
||||||
|
Map<String, HealthCheck.Result> results = healthCheckRegistry.runHealthChecks();
|
||||||
|
|
||||||
|
assertFalse(results.isEmpty());
|
||||||
|
|
||||||
|
results.forEach((k, v) -> assertTrue(v.isHealthy()));
|
||||||
|
|
||||||
|
healthCheckRegistry.unregister("uc");
|
||||||
|
|
||||||
|
assertThat(healthCheckRegistry.getNames().size(), equalTo(1));
|
||||||
|
}
|
||||||
|
}
|
10
pom.xml
10
pom.xml
@ -1,6 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>parent-modules</artifactId>
|
||||||
@ -69,12 +68,15 @@
|
|||||||
<module>jsoup</module>
|
<module>jsoup</module>
|
||||||
<module>junit5</module>
|
<module>junit5</module>
|
||||||
|
|
||||||
|
<module>kotlin</module>
|
||||||
|
|
||||||
<module>log-mdc</module>
|
<module>log-mdc</module>
|
||||||
<module>log4j</module>
|
<module>log4j</module>
|
||||||
<module>log4j2</module>
|
<module>log4j2</module>
|
||||||
<module>lombok</module>
|
<module>lombok</module>
|
||||||
|
|
||||||
<module>mapstruct</module>
|
<module>mapstruct</module>
|
||||||
|
<module>metrics</module>
|
||||||
<module>mockito</module>
|
<module>mockito</module>
|
||||||
<module>mocks</module>
|
<module>mocks</module>
|
||||||
|
|
||||||
@ -92,6 +94,7 @@
|
|||||||
<module>resteasy</module>
|
<module>resteasy</module>
|
||||||
|
|
||||||
<module>selenium-junit-testng</module>
|
<module>selenium-junit-testng</module>
|
||||||
|
<module>spark-java</module>
|
||||||
<module>spring-akka</module>
|
<module>spring-akka</module>
|
||||||
<module>spring-amqp</module>
|
<module>spring-amqp</module>
|
||||||
<module>spring-all</module>
|
<module>spring-all</module>
|
||||||
@ -118,6 +121,7 @@
|
|||||||
<module>spring-hibernate3</module>
|
<module>spring-hibernate3</module>
|
||||||
<module>spring-hibernate4</module>
|
<module>spring-hibernate4</module>
|
||||||
<module>spring-integration</module>
|
<module>spring-integration</module>
|
||||||
|
<module>spring-jersey</module>
|
||||||
<module>spring-jms</module>
|
<module>spring-jms</module>
|
||||||
<module>spring-jooq</module>
|
<module>spring-jooq</module>
|
||||||
<module>spring-jpa</module>
|
<module>spring-jpa</module>
|
||||||
@ -161,6 +165,7 @@
|
|||||||
<module>spring-security-rest</module>
|
<module>spring-security-rest</module>
|
||||||
<module>spring-security-x509</module>
|
<module>spring-security-x509</module>
|
||||||
<module>spring-session</module>
|
<module>spring-session</module>
|
||||||
|
<module>spring-sleuth</module>
|
||||||
<module>spring-social-login</module>
|
<module>spring-social-login</module>
|
||||||
<module>spring-spel</module>
|
<module>spring-spel</module>
|
||||||
<module>spring-thymeleaf</module>
|
<module>spring-thymeleaf</module>
|
||||||
@ -175,6 +180,7 @@
|
|||||||
<module>xml</module>
|
<module>xml</module>
|
||||||
<module>xmlunit2</module>
|
<module>xmlunit2</module>
|
||||||
<module>xstream</module>
|
<module>xstream</module>
|
||||||
|
<module>java-mongodb</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
</project>
|
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user