Merge branch 'master' into master

This commit is contained in:
johnA1331 2020-05-07 11:05:00 +08:00 committed by GitHub
commit 7b80e93607
173 changed files with 1617 additions and 1008 deletions

View File

@ -18,5 +18,5 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [Guide to MapDB](https://www.baeldung.com/mapdb)
- [A Guide to Apache Mesos](https://www.baeldung.com/apache-mesos)
- [JasperReports with Spring](https://www.baeldung.com/spring-jasper)
- More articles [[<-- prev]](/libraries)
- More articles [[<-- prev]](/libraries) [[next -->]](/libraries-3)

View File

@ -16,3 +16,5 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [Introduction to Takes](https://www.baeldung.com/java-takes)
- [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway)
- [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro)
- [Quick Guide to Spring Cloud Circuit Breaker](https://www.baeldung.com/spring-cloud-circuit-breaker)
- More articles [[<-- prev]](/libraries-2) [[next -->]](/libraries-4)

21
libraries-4/README.md Normal file
View File

@ -0,0 +1,21 @@
## Libraries-4
This module contains articles about various Java libraries.
These are small libraries that are relatively easy to use and do not require any separate module of their own.
The code examples related to different libraries are each in their own module.
Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases.
### Relevant articles
- [Quick Guide to RSS with Rome](https://www.baeldung.com/rome-rss)
- [Introduction to PCollections](https://www.baeldung.com/java-pcollections)
- [Introduction to Eclipse Collections](https://www.baeldung.com/eclipse-collections)
- [DistinctBy in the Java Stream API](https://www.baeldung.com/java-streams-distinct-by)
- [Introduction to NoException](https://www.baeldung.com/no-exception)
- [Spring Yarg Integration](https://www.baeldung.com/spring-yarg)
- [Delete a Directory Recursively in Java](https://www.baeldung.com/java-delete-directory)
- [Guide to JDeferred](https://www.baeldung.com/jdeferred)
- [Introduction to MBassador](https://www.baeldung.com/mbassador)
- [Using Pairs in Java](https://www.baeldung.com/java-pairs)
- More articles [[<-- prev]](/libraries-3) [[next -->]](/libraries-5)

116
libraries-4/pom.xml Normal file
View File

@ -0,0 +1,116 @@
<?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">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries-4</artifactId>
<dependencies>
<dependency>
<groupId>org.jdeferred</groupId>
<artifactId>jdeferred-core</artifactId>
<version>${jdeferred.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse-collections.version}</version>
</dependency>
<dependency>
<groupId>com.haulmont.yarg</groupId>
<artifactId>yarg</artifactId>
<version>${yarg.version}</version>
</dependency>
<dependency>
<groupId>net.engio</groupId>
<artifactId>mbassador</artifactId>
<version>${mbassador.version}</version>
</dependency>
<dependency>
<groupId>com.machinezoo.noexception</groupId>
<artifactId>noexception</artifactId>
<version>${noexception.version}</version>
</dependency>
<dependency>
<groupId>rome</groupId>
<artifactId>rome</artifactId>
<version>${rome.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>javax.jdo</artifactId>
<version>${javax.jdo.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${javax.servlet.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>org.pcollections</groupId>
<artifactId>pcollections</artifactId>
<version>${pcollections.version}</version>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${javax.el.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
<properties>
<jdeferred.version>1.2.6</jdeferred.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
<noexception.version>1.1.0</noexception.version>
<yarg.version>2.0.12</yarg.version>
<mbassador.version>1.3.1</mbassador.version>
<rome.version>1.0</rome.version>
<spring.version>4.3.8.RELEASE</spring.version>
<javax.servlet.version>2.5</javax.servlet.version>
<javax.jdo.version>3.2.0-m7</javax.jdo.version>
<vavr.version>0.9.0</vavr.version>
<assertj.version>3.6.2</assertj.version>
<pcollections.version>2.1.2</pcollections.version>
<awaitility.version>3.0.0</awaitility.version>
<streamex.version>0.6.5</streamex.version>
<javax.el.version>3.0.0</javax.el.version>
</properties>
</project>

View File

@ -5,6 +5,7 @@ import static org.junit.Assert.assertEquals;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.map.mutable.UnifiedMap;
import org.eclipse.collections.impl.tuple.Tuples;
import org.junit.Assert;
import org.junit.Test;
public class ForEachPatternUnitTest {
@ -23,7 +24,7 @@ public class ForEachPatternUnitTest {
}
for (int i = 0; i < map.size(); i++) {
assertEquals("New Value", map.get(i + 1));
Assert.assertEquals("New Value", map.get(i + 1));
}
}
}

View File

@ -1,138 +1,138 @@
package com.baeldung.java.io;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.util.FileSystemUtils;
public class JavaDirectoryDeleteUnitTest {
private static Path TEMP_DIRECTORY;
private static final String DIRECTORY_NAME = "toBeDeleted";
private static final List<String> ALL_LINES = Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4", "This is line 5", "This is line 6");
@BeforeClass
public static void initializeTempDirectory() throws IOException {
TEMP_DIRECTORY = Files.createTempDirectory("tmpForJUnit");
}
@AfterClass
public static void cleanTempDirectory() throws IOException {
FileUtils.deleteDirectory(TEMP_DIRECTORY.toFile());
}
@Before
public void setupDirectory() throws IOException {
Path tempPathForEachTest = Files.createDirectory(TEMP_DIRECTORY.resolve(DIRECTORY_NAME));
// Create a directory structure
Files.write(tempPathForEachTest.resolve("file1.txt"), ALL_LINES.subList(0, 2));
Files.write(tempPathForEachTest.resolve("file2.txt"), ALL_LINES.subList(2, 4));
Files.createDirectories(tempPathForEachTest.resolve("Empty"));
Path aSubDir = Files.createDirectories(tempPathForEachTest.resolve("notEmpty"));
Files.write(aSubDir.resolve("file3.txt"), ALL_LINES.subList(3, 5));
Files.write(aSubDir.resolve("file4.txt"), ALL_LINES.subList(0, 3));
aSubDir = Files.createDirectories(aSubDir.resolve("anotherSubDirectory"));
Files.write(aSubDir.resolve("file5.txt"), ALL_LINES.subList(4, 5));
Files.write(aSubDir.resolve("file6.txt"), ALL_LINES.subList(0, 2));
}
@After
public void checkAndCleanupIfRequired() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
if (Files.exists(pathToBeDeleted)) {
FileUtils.deleteDirectory(pathToBeDeleted.toFile());
}
}
private boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
@Test
public void givenDirectory_whenDeletedWithRecursion_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
boolean result = deleteDirectory(pathToBeDeleted.toFile());
assertTrue("Could not delete directory", result);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithCommonsIOFileUtils_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
FileUtils.deleteDirectory(pathToBeDeleted.toFile());
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithSpringFileSystemUtils_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
boolean result = FileSystemUtils.deleteRecursively(pathToBeDeleted.toFile());
assertTrue("Could not delete directory", result);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
Files.walk(pathToBeDeleted).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithNIO2WalkFileTree_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
Files.walkFileTree(pathToBeDeleted, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
}
package com.baeldung.io;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.util.FileSystemUtils;
public class JavaDirectoryDeleteUnitTest {
private static Path TEMP_DIRECTORY;
private static final String DIRECTORY_NAME = "toBeDeleted";
private static final List<String> ALL_LINES = Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4", "This is line 5", "This is line 6");
@BeforeClass
public static void initializeTempDirectory() throws IOException {
TEMP_DIRECTORY = Files.createTempDirectory("tmpForJUnit");
}
@AfterClass
public static void cleanTempDirectory() throws IOException {
FileUtils.deleteDirectory(TEMP_DIRECTORY.toFile());
}
@Before
public void setupDirectory() throws IOException {
Path tempPathForEachTest = Files.createDirectory(TEMP_DIRECTORY.resolve(DIRECTORY_NAME));
// Create a directory structure
Files.write(tempPathForEachTest.resolve("file1.txt"), ALL_LINES.subList(0, 2));
Files.write(tempPathForEachTest.resolve("file2.txt"), ALL_LINES.subList(2, 4));
Files.createDirectories(tempPathForEachTest.resolve("Empty"));
Path aSubDir = Files.createDirectories(tempPathForEachTest.resolve("notEmpty"));
Files.write(aSubDir.resolve("file3.txt"), ALL_LINES.subList(3, 5));
Files.write(aSubDir.resolve("file4.txt"), ALL_LINES.subList(0, 3));
aSubDir = Files.createDirectories(aSubDir.resolve("anotherSubDirectory"));
Files.write(aSubDir.resolve("file5.txt"), ALL_LINES.subList(4, 5));
Files.write(aSubDir.resolve("file6.txt"), ALL_LINES.subList(0, 2));
}
@After
public void checkAndCleanupIfRequired() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
if (Files.exists(pathToBeDeleted)) {
FileUtils.deleteDirectory(pathToBeDeleted.toFile());
}
}
private boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
@Test
public void givenDirectory_whenDeletedWithRecursion_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
boolean result = deleteDirectory(pathToBeDeleted.toFile());
assertTrue("Could not delete directory", result);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithCommonsIOFileUtils_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
FileUtils.deleteDirectory(pathToBeDeleted.toFile());
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithSpringFileSystemUtils_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
boolean result = FileSystemUtils.deleteRecursively(pathToBeDeleted.toFile());
assertTrue("Could not delete directory", result);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
Files.walk(pathToBeDeleted).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithNIO2WalkFileTree_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
Files.walkFileTree(pathToBeDeleted, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
}

21
libraries-5/README.md Normal file
View File

@ -0,0 +1,21 @@
## Libraries-5
This module contains articles about various Java libraries.
These are small libraries that are relatively easy to use and do not require any separate module of their own.
The code examples related to different libraries are each in their own module.
Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases.
### Relevant articles
- [Introduction to Caffeine](https://www.baeldung.com/java-caching-caffeine)
- [Introduction to StreamEx](https://www.baeldung.com/streamex)
- [A Docker Guide for Java](https://www.baeldung.com/docker-java-api)
- [Introduction to Akka Actors in Java](https://www.baeldung.com/akka-actors-java)
- [A Guide to Byte Buddy](https://www.baeldung.com/byte-buddy)
- [Introduction to jOOL](https://www.baeldung.com/jool)
- [Consumer Driven Contracts with Pact](https://www.baeldung.com/pact-junit-consumer-driven-contracts)
- [Introduction to Atlassian Fugue](https://www.baeldung.com/java-fugue)
- [Publish and Receive Messages with Nats Java Client](https://www.baeldung.com/nats-java-client)
- [Java Concurrency Utility with JCTools](https://www.baeldung.com/java-concurrency-jc-tools)
- More articles [[<-- prev]](/libraries-4) [[next -->]](/libraries-6)

146
libraries-5/pom.xml Normal file
View File

@ -0,0 +1,146 @@
<?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">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>libraries-5</artifactId>
<modelVersion>4.0.0</modelVersion>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jool</artifactId>
<version>${jool.version}</version>
</dependency>
<dependency>
<groupId>au.com.dius</groupId>
<artifactId>pact-jvm-consumer-junit_2.11</artifactId>
<version>${pact.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.typesafe.akka/akka-actor -->
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_${scala.version}</artifactId>
<version>${typesafe-akka.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-testkit_${scala.version}</artifactId>
<version>${typesafe-akka.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>${bytebuddy.version}</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-agent</artifactId>
<version>${bytebuddy.version}</version>
</dependency>
<!--Java Docker API Client -->
<dependency>
<groupId>com.github.docker-java</groupId>
<artifactId>docker-java</artifactId>
<version>${docker.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--Java Docker API Client -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>${caffeine.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>${findbugs.version}</version>
<scope>test</scope>
</dependency>
<!-- Atlassian Fugue -->
<dependency>
<groupId>io.atlassian.fugue</groupId>
<artifactId>fugue</artifactId>
<version>${fugue.version}</version>
</dependency>
<dependency>
<groupId>io.nats</groupId>
<artifactId>jnats</artifactId>
<version>${jnats.version}</version>
</dependency>
<dependency>
<groupId>org.jctools</groupId>
<artifactId>jctools-core</artifactId>
<version>${jctools.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
<properties>
<pact.version>3.5.0</pact.version>
<jool.version>0.9.12</jool.version>
<spring.version>4.3.8.RELEASE</spring.version>
<assertj.version>3.6.2</assertj.version>
<scala.version>2.11</scala.version>
<typesafe-akka.version>2.5.11</typesafe-akka.version>
<streamex.version>0.6.5</streamex.version>
<bytebuddy.version>1.7.1</bytebuddy.version>
<docker.version>3.0.14</docker.version>
<caffeine.version>2.5.5</caffeine.version>
<findbugs.version>3.0.2</findbugs.version>
<fugue.version>4.5.1</fugue.version>
<jnats.version>1.0</jnats.version>
<jctools.version>2.1.2</jctools.version>
<jmh.version>1.19</jmh.version>
</properties>
</project>

View File

@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import org.junit.Assert;
import org.junit.Test;
import com.github.benmanes.caffeine.cache.*;
@ -65,43 +66,43 @@ public class CaffeineUnitTest {
assertEquals("Data for " + key, dataObject.getData());
});
cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size()));
cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> Assert.assertEquals(3, dataObjectMap.size()));
}
@Test
public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(1).refreshAfterWrite(10, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize());
Assert.assertEquals(0, cache.estimatedSize());
cache.get("A");
assertEquals(1, cache.estimatedSize());
Assert.assertEquals(1, cache.estimatedSize());
cache.get("B");
cache.cleanUp();
assertEquals(1, cache.estimatedSize());
Assert.assertEquals(1, cache.estimatedSize());
}
@Test
public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumWeight(10).weigher((k, v) -> 5).build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize());
Assert.assertEquals(0, cache.estimatedSize());
cache.get("A");
assertEquals(1, cache.estimatedSize());
Assert.assertEquals(1, cache.estimatedSize());
cache.get("B");
assertEquals(2, cache.estimatedSize());
Assert.assertEquals(2, cache.estimatedSize());
cache.get("C");
cache.cleanUp();
assertEquals(2, cache.estimatedSize());
Assert.assertEquals(2, cache.estimatedSize());
}
@Test
@ -138,7 +139,7 @@ public class CaffeineUnitTest {
cache.get("A");
cache.get("A");
assertEquals(1, cache.stats().hitCount());
assertEquals(1, cache.stats().missCount());
Assert.assertEquals(1, cache.stats().hitCount());
Assert.assertEquals(1, cache.stats().missCount());
}
}

View File

@ -6,6 +6,8 @@ import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.core.DockerClientBuilder;
import org.hamcrest.MatcherAssert;
import org.hamcrest.core.Is;
import org.junit.BeforeClass;
import org.junit.Test;
@ -51,7 +53,7 @@ public class ContainerLiveTest {
CreateContainerResponse container = dockerClient.createContainerCmd("mongo:3.6").withCmd("--bind_ip_all").withName("mongo").withHostName("baeldung").withEnv("MONGO_LATEST_VERSION=3.6").withPortBindings(PortBinding.parse("9999:27017")).exec();
// then
assertThat(container.getId(), is(not(null)));
MatcherAssert.assertThat(container.getId(), is(not(null)));
}
@Test
@ -104,7 +106,7 @@ public class ContainerLiveTest {
// then
InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(container.getId()).exec();
assertThat(containerResponse.getId(), is(container.getId()));
MatcherAssert.assertThat(containerResponse.getId(), Is.is(container.getId()));
}
@Test

View File

@ -8,6 +8,8 @@ import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.BuildImageResultCallback;
import com.github.dockerjava.core.command.PullImageResultCallback;
import com.github.dockerjava.core.command.PushImageResultCallback;
import org.hamcrest.MatcherAssert;
import org.hamcrest.core.Is;
import org.junit.BeforeClass;
import org.junit.Test;
@ -81,7 +83,7 @@ public class ImageLiveTest {
InspectImageResponse imageResponse = dockerClient.inspectImageCmd(image.getId()).exec();
// then
assertThat(imageResponse.getId(), is(image.getId()));
MatcherAssert.assertThat(imageResponse.getId(), Is.is(image.getId()));
}
@Test

View File

@ -5,6 +5,7 @@ import com.github.dockerjava.api.command.CreateNetworkResponse;
import com.github.dockerjava.api.model.Network;
import com.github.dockerjava.api.model.Network.Ipam;
import com.github.dockerjava.core.DockerClientBuilder;
import org.hamcrest.MatcherAssert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
@ -64,7 +65,7 @@ public class NetworkLiveTest {
Network network = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
// then
assertThat(network.getName(), is(networkName));
MatcherAssert.assertThat(network.getName(), is(networkName));
}
@Test

View File

@ -5,6 +5,7 @@ import com.github.dockerjava.api.command.CreateVolumeResponse;
import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.command.ListVolumesResponse;
import com.github.dockerjava.core.DockerClientBuilder;
import org.hamcrest.MatcherAssert;
import org.junit.BeforeClass;
import org.junit.Test;
@ -57,7 +58,7 @@ public class VolumeLiveTest {
CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec();
// then
assertThat(unnamedVolume.getName(), is(not(null)));
MatcherAssert.assertThat(unnamedVolume.getName(), is(not(null)));
}
@Test
@ -67,7 +68,7 @@ public class VolumeLiveTest {
CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("myNamedVolume").exec();
// then
assertThat(namedVolume.getName(), is(not(null)));
MatcherAssert.assertThat(namedVolume.getName(), is(not(null)));
}
@Test

View File

@ -1,4 +1,4 @@
package com.baeldung.atlassian.fugue;
package com.baeldung.fugue;
import io.atlassian.fugue.*;
import org.junit.Assert;

View File

@ -1,5 +1,6 @@
package com.baeldung.jctools;
import org.assertj.core.api.Assertions;
import org.jctools.queues.SpscArrayQueue;
import org.jctools.queues.SpscChunkedArrayQueue;
import org.junit.Test;
@ -44,16 +45,16 @@ public class JCToolsUnitTest {
@Test
public void whenQueueIsFull_thenNoMoreElementsCanBeAdded() throws InterruptedException {
SpscChunkedArrayQueue<Integer> queue = new SpscChunkedArrayQueue<>(8, 16);
assertThat(queue.capacity()).isEqualTo(16);
Assertions.assertThat(queue.capacity()).isEqualTo(16);
CountDownLatch startConsuming = new CountDownLatch(1);
CountDownLatch awakeProducer = new CountDownLatch(1);
AtomicReference<Throwable> error = new AtomicReference<>();
Thread producer = new Thread(() -> {
IntStream.range(0, queue.capacity()).forEach(i -> {
assertThat(queue.offer(i)).isTrue();
Assertions.assertThat(queue.offer(i)).isTrue();
});
assertThat(queue.offer(queue.capacity())).isFalse();
Assertions.assertThat(queue.offer(queue.capacity())).isFalse();
startConsuming.countDown();
try {
awakeProducer.await();
@ -61,7 +62,7 @@ public class JCToolsUnitTest {
throw new RuntimeException(e);
}
assertThat(queue.offer(queue.capacity())).isTrue();
Assertions.assertThat(queue.offer(queue.capacity())).isTrue();
});
producer.setUncaughtExceptionHandler((t, e) -> {
error.set(e);

View File

@ -1,4 +1,4 @@
package com.baeldung.stream;
package com.baeldung.streamex;
import one.util.streamex.StreamEx;
import org.junit.Test;

17
libraries-6/README.md Normal file
View File

@ -0,0 +1,17 @@
## Libraries-6
This module contains articles about various Java libraries.
These are small libraries that are relatively easy to use and do not require any separate module of their own.
The code examples related to different libraries are each in their own module.
Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases.
### Relevant articles
- [Introduction to JavaPoet](https://www.baeldung.com/java-poet)
- [Guide to Resilience4j](https://www.baeldung.com/resilience4j)
- [Implementing a FTP-Client in Java](https://www.baeldung.com/java-ftp-client)
- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library)
- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library)
- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once)
- More articles [[<-- prev]](/libraries-5)

111
libraries-6/pom.xml Normal file
View File

@ -0,0 +1,111 @@
<?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">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries-6</artifactId>
<dependencies>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-java8</artifactId>
<version>${functionaljava.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
<version>${kafka.version}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>${kafka.version}</version>
<classifier>test</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-circuitbreaker</artifactId>
<version>${resilience4j.version}</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-bulkhead</artifactId>
<version>${resilience4j.version}</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-retry</artifactId>
<version>${resilience4j.version}</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-timelimiter</artifactId>
<version>${resilience4j.version}</version>
</dependency>
<dependency>
<groupId>com.squareup</groupId>
<artifactId>javapoet</artifactId>
<version>${javapoet.version}</version>
</dependency>
<dependency>
<groupId>org.mockftpserver</groupId>
<artifactId>MockFtpServer</artifactId>
<version>${mockftpserver.version}</version>
<scope>test</scope>
</dependency>
<!-- Reflections -->
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>${reflections.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>${commons-net.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commonsio.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<kafka.version>2.0.0</kafka.version>
<javapoet.version>1.10.0</javapoet.version>
<reflections.version>0.9.11</reflections.version>
<mockftpserver.version>2.7.1</mockftpserver.version>
<functionaljava.version>4.8.1</functionaljava.version>
<resilience4j.version>0.12.1</resilience4j.version>
<protonpack.version>1.15</protonpack.version>
<commons-net.version>3.6</commons-net.version>
<assertj.version>3.6.2</assertj.version>
<commonsio.version>2.6</commonsio.version>
</properties>
</project>

View File

@ -1,43 +1,43 @@
package com.baeldung.fj;
import fj.F;
import fj.F1Functions;
import fj.Unit;
import fj.data.IO;
import fj.data.IOFunctions;
public class FunctionalJavaIOMain {
public static IO<Unit> printLetters(final String s) {
return () -> {
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
return Unit.unit();
};
}
public static void main(String[] args) {
F<String, IO<Unit>> printLetters = i -> printLetters(i);
IO<Unit> lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?");
IO<Unit> input = IOFunctions.stdoutPrint("First Name: ");
IO<Unit> userInput = IOFunctions.append(lowerCase, input);
IO<String> readInput = IOFunctions.stdinReadLine();
F<String, String> toUpperCase = i -> i.toUpperCase();
F<String, IO<Unit>> transformInput = F1Functions.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput, transformInput);
IO<Unit> program = IOFunctions.bind(userInput, nothing -> readAndPrintResult);
IOFunctions.toSafe(program).run();
}
}
package com.baeldung.fj;
import fj.F;
import fj.F1Functions;
import fj.Unit;
import fj.data.IO;
import fj.data.IOFunctions;
public class FunctionalJavaIOMain {
public static IO<Unit> printLetters(final String s) {
return () -> {
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
return Unit.unit();
};
}
public static void main(String[] args) {
F<String, IO<Unit>> printLetters = i -> printLetters(i);
IO<Unit> lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?");
IO<Unit> input = IOFunctions.stdoutPrint("First Name: ");
IO<Unit> userInput = IOFunctions.append(lowerCase, input);
IO<String> readInput = IOFunctions.stdinReadLine();
F<String, String> toUpperCase = i -> i.toUpperCase();
F<String, IO<Unit>> transformInput = F1Functions.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput, transformInput);
IO<Unit> program = IOFunctions.bind(userInput, nothing -> readAndPrintResult);
IOFunctions.toSafe(program).run();
}
}

View File

@ -1,48 +1,48 @@
package com.baeldung.fj;
import fj.F;
import fj.Show;
import fj.data.Array;
import fj.data.List;
import fj.data.Option;
import fj.function.Characters;
import fj.function.Integers;
public class FunctionalJavaMain {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static void main(String[] args) {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
Show.listShow(Show.booleanShow).println(evenList);
fList = fList.map(i -> i + 1);
Show.listShow(Show.intShow).println(fList);
Array<Integer> a = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
Array<Integer> b = a.filter(Integers.even);
Show.arrayShow(Show.intShow).println(b);
Array<String> array = Array.array("Welcome", "To", "baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
System.out.println(isExist);
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0);
System.out.println(sum);
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
Option<Integer> result1 = n1.bind(f1);
Option<Integer> result2 = n2.bind(f1);
Show.optionShow(Show.intShow).println(result1);
Show.optionShow(Show.intShow).println(result2);
}
}
package com.baeldung.fj;
import fj.F;
import fj.Show;
import fj.data.Array;
import fj.data.List;
import fj.data.Option;
import fj.function.Characters;
import fj.function.Integers;
public class FunctionalJavaMain {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static void main(String[] args) {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
Show.listShow(Show.booleanShow).println(evenList);
fList = fList.map(i -> i + 1);
Show.listShow(Show.intShow).println(fList);
Array<Integer> a = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
Array<Integer> b = a.filter(Integers.even);
Show.arrayShow(Show.intShow).println(b);
Array<String> array = Array.array("Welcome", "To", "baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
System.out.println(isExist);
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0);
System.out.println(sum);
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
Option<Integer> result1 = n1.bind(f1);
Option<Integer> result2 = n2.bind(f1);
Show.optionShow(Show.intShow).println(result1);
Show.optionShow(Show.intShow).println(result2);
}
}

View File

@ -1,71 +1,71 @@
package com.baeldung.reflections;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Set;
import java.util.regex.Pattern;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.MethodParameterScanner;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.scanners.Scanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
public class ReflectionsApp {
public Set<Class<? extends Scanner>> getReflectionsSubTypes() {
Reflections reflections = new Reflections("org.reflections");
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
return scannersSet;
}
public Set<Class<?>> getJDKFunctinalInterfaces() {
Reflections reflections = new Reflections("java.util.function");
Set<Class<?>> typesSet = reflections.getTypesAnnotatedWith(FunctionalInterface.class);
return typesSet;
}
public Set<Method> getDateDeprecatedMethods() {
Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
Set<Method> deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class);
return deprecatedMethodsSet;
}
@SuppressWarnings("rawtypes")
public Set<Constructor> getDateDeprecatedConstructors() {
Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
Set<Constructor> constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class);
return constructorsSet;
}
public Set<Method> getMethodsWithDateParam() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
Set<Method> methodsSet = reflections.getMethodsMatchParams(Date.class);
return methodsSet;
}
public Set<Method> getMethodsWithVoidReturn() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
Set<Method> methodsSet = reflections.getMethodsReturn(void.class);
return methodsSet;
}
public Set<String> getPomXmlPaths() {
Reflections reflections = new Reflections(new ResourcesScanner());
Set<String> resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml"));
return resourcesSet;
}
public Set<Class<? extends Scanner>> getReflectionsSubTypesUsingBuilder() {
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections"))
.setScanners(new SubTypesScanner()));
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
return scannersSet;
}
}
package com.baeldung.reflections;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Set;
import java.util.regex.Pattern;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.MethodParameterScanner;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.scanners.Scanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
public class ReflectionsApp {
public Set<Class<? extends Scanner>> getReflectionsSubTypes() {
Reflections reflections = new Reflections("org.reflections");
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
return scannersSet;
}
public Set<Class<?>> getJDKFunctinalInterfaces() {
Reflections reflections = new Reflections("java.util.function");
Set<Class<?>> typesSet = reflections.getTypesAnnotatedWith(FunctionalInterface.class);
return typesSet;
}
public Set<Method> getDateDeprecatedMethods() {
Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
Set<Method> deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class);
return deprecatedMethodsSet;
}
@SuppressWarnings("rawtypes")
public Set<Constructor> getDateDeprecatedConstructors() {
Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
Set<Constructor> constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class);
return constructorsSet;
}
public Set<Method> getMethodsWithDateParam() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
Set<Method> methodsSet = reflections.getMethodsMatchParams(Date.class);
return methodsSet;
}
public Set<Method> getMethodsWithVoidReturn() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
Set<Method> methodsSet = reflections.getMethodsReturn(void.class);
return methodsSet;
}
public Set<String> getPomXmlPaths() {
Reflections reflections = new Reflections(new ResourcesScanner());
Set<String> resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml"));
return resourcesSet;
}
public Set<Class<? extends Scanner>> getReflectionsSubTypesUsingBuilder() {
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections"))
.setScanners(new SubTypesScanner()));
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
return scannersSet;
}
}

View File

@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Assert;
import org.junit.Test;
import fj.F;
@ -96,9 +97,9 @@ public class FunctionalJavaUnitTest {
Option<Integer> result2 = n2.bind(function);
Option<Integer> result3 = n3.bind(function);
assertEquals(Option.none(), result1);
assertEquals(Option.some(102), result2);
assertEquals(Option.none(), result3);
Assert.assertEquals(Option.none(), result1);
Assert.assertEquals(Option.some(102), result2);
Assert.assertEquals(Option.none(), result3);
}
@Test

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