This commit is contained in:
Jonathan Cook 2020-05-10 11:21:52 +02:00
commit 7effe2a126
247 changed files with 2581 additions and 1116 deletions

View File

@ -10,9 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>

View File

@ -1,11 +1,14 @@
package com.baeldung;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;

View File

@ -1,16 +1,24 @@
package com.baeldung;
import org.apache.shiro.authc.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
public class MyCustomRealm extends JdbcRealm {

View File

@ -1,14 +1,15 @@
package com.baeldung.shiro.permissions.custom;
import com.baeldung.MyCustomRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.Ini;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,7 +1,6 @@
## Atomikos
This module contains articles about Atomikos
### Relevant Articles:
- [Guide Transactions Using Atomikos]()
- [A Guide to Atomikos](https://www.baeldung.com/java-atomikos)

View File

@ -1,3 +0,0 @@
### Relevant Articles:
- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool)

View File

@ -12,4 +12,5 @@ This module contains articles about core Groovy concepts
- [Closures in Groovy](https://www.baeldung.com/groovy-closures)
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
- [[More -->]](/core-groovy-2)
- [Convert String to Integer in Groovy](https://www.baeldung.com/groovy-convert-string-to-integer)
- [[More -->]](/core-groovy-2)

View File

@ -5,4 +5,5 @@ This module contains articles about Map data structures in Java.
### Relevant Articles:
- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap)
- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps)
- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)

View File

@ -4,5 +4,5 @@
### Relevant Articles:
- [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex)
- [Testing Multi-Threaded Code in Java] (https://www.baeldung.com/java-testing-multithreaded)
- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded)

View File

@ -0,0 +1,81 @@
package com.baeldung.lockfree;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class NonBlockingQueue<T> {
private final AtomicReference<Node<T>> head, tail;
private final AtomicInteger size;
public NonBlockingQueue() {
head = new AtomicReference<>(null);
tail = new AtomicReference<>(null);
size = new AtomicInteger();
size.set(0);
}
public void add(T element) {
if (element == null) {
throw new NullPointerException();
}
Node<T> node = new Node<>(element);
Node<T> currentTail;
do {
currentTail = tail.get();
node.setPrevious(currentTail);
} while(!tail.compareAndSet(currentTail, node));
if(node.previous != null) {
node.previous.next = node;
}
head.compareAndSet(null, node); //if we are inserting the first element
size.incrementAndGet();
}
public T get() {
if(head.get() == null) {
throw new NoSuchElementException();
}
Node<T> currentHead;
Node<T> nextNode;
do {
currentHead = head.get();
nextNode = currentHead.getNext();
} while(!head.compareAndSet(currentHead, nextNode));
size.decrementAndGet();
return currentHead.getValue();
}
public int size() {
return this.size.get();
}
private class Node<T> {
private final T value;
private volatile Node<T> next;
private volatile Node<T> previous;
public Node(T value) {
this.value = value;
this.next = null;
}
public T getValue() {
return value;
}
public Node<T> getNext() {
return next;
}
public void setPrevious(Node<T> previous) {
this.previous = previous;
}
}
}

View File

@ -11,4 +11,5 @@ This module contains articles about networking in Java
- [Sending Emails with Java](https://www.baeldung.com/java-email)
- [Authentication with HttpUrlConnection](https://www.baeldung.com/java-http-url-connection)
- [Download a File from an URL in Java](https://www.baeldung.com/java-download-file)
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
- [[<-- Prev]](/core-java-modules/core-java-networking)

View File

@ -26,7 +26,6 @@ public class RegexUnitTest {
while (matcher.find())
matches++;
assertEquals(matches, 2);
}
@Test
@ -452,7 +451,6 @@ public class RegexUnitTest {
Matcher matcher = pattern.matcher("dogs are friendly");
assertTrue(matcher.lookingAt());
assertFalse(matcher.matches());
}
@Test
@ -460,7 +458,6 @@ public class RegexUnitTest {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("dog");
assertTrue(matcher.matches());
}
@Test
@ -469,7 +466,6 @@ public class RegexUnitTest {
Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
String newStr = matcher.replaceFirst("cat");
assertEquals("cats are domestic animals, dogs are friendly", newStr);
}
@Test
@ -478,7 +474,6 @@ public class RegexUnitTest {
Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
String newStr = matcher.replaceAll("cat");
assertEquals("cats are domestic animals, cats are friendly", newStr);
}
public synchronized static int runTest(String regex, String text) {

View File

@ -0,0 +1,129 @@
package com.baeldung.regex.phonenumbers;
import static org.junit.Assert.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class PhoneNumbersRegexUnitTest {
@Test
public void whenMatchesTenDigitsNumber_thenCorrect() {
Pattern pattern = Pattern.compile("^\\d{10}$");
Matcher matcher = pattern.matcher("2055550125");
assertTrue(matcher.matches());
}
@Test
public void whenMOreThanTenDigits_thenNotCorrect() {
Pattern pattern = Pattern.compile("^\\d{10}$");
Matcher matcher = pattern.matcher("20555501251");
assertFalse(matcher.matches());
}
@Test
public void whenMatchesTenDigitsNumberWhitespacesDotHyphen_thenCorrect() {
Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$");
Matcher matcher = pattern.matcher("202 555 0125");
assertTrue(matcher.matches());
}
@Test
public void whenIncludesBracket_thenNotCorrect() {
Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$");
Matcher matcher = pattern.matcher("202]555 0125");
assertFalse(matcher.matches());
}
@Test
public void whenNotStartsWithBatchesOfThreeDigits_thenNotCorrect() {
Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$");
Matcher matcher = pattern.matcher("2021 555 0125");
assertFalse(matcher.matches());
}
@Test
public void whenLastPartWithNoFourDigits_thenNotCorrect() {
Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$");
Matcher matcher = pattern.matcher("202 555 012");
assertFalse(matcher.matches());
}
@Test
public void whenMatchesTenDigitsNumberParenthesis_thenCorrect() {
Pattern pattern = Pattern.compile("^((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
Matcher matcher = pattern.matcher("(202) 555-0125");
assertTrue(matcher.matches());
}
@Test
public void whenJustOpeningParenthesis_thenNotCorrect() {
Pattern pattern = Pattern.compile("^((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
Matcher matcher = pattern.matcher("(202 555-0125");
assertFalse(matcher.matches());
}
@Test
public void whenJustClosingParenthesis_thenNotCorrect() {
Pattern pattern = Pattern.compile("^((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
Matcher matcher = pattern.matcher("202) 555-0125");
assertFalse(matcher.matches());
}
@Test
public void whenMatchesTenDigitsNumberPrefix_thenCorrect() {
Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
Matcher matcher = pattern.matcher("+111 (202) 555-0125");
assertTrue(matcher.matches());
}
@Test
public void whenIncorrectPrefix_thenNotCorrect() {
Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
Matcher matcher = pattern.matcher("-111 (202) 555-0125");
assertFalse(matcher.matches());
}
@Test
public void whenTooLongPrefix_thenNotCorrect() {
Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
Matcher matcher = pattern.matcher("+1111 (202) 555-0125");
assertFalse(matcher.matches());
}
@Test
public void whenMatchesPhoneNumber_thenCorrect() {
String patterns
= "^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"
+ "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$"
+ "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$";
String[] validPhoneNumbers
= {"2055550125","202 555 0125", "(202) 555-0125", "+111 (202) 555-0125", "636 856 789", "+111 636 856 789", "636 85 67 89", "+111 636 85 67 89"};
Pattern pattern = Pattern.compile(patterns);
for(String phoneNumber : validPhoneNumbers) {
Matcher matcher = pattern.matcher(phoneNumber);
assertTrue(matcher.matches());
}
}
@Test
public void whenNotMatchesPhoneNumber_thenNotCorrect() {
String patterns
= "^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"
+ "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$"
+ "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$";
String[] invalidPhoneNumbers
= {"20555501251","202]555 0125", "2021 555 012", "(202 555-0125", "202) 555-0125", "-111 (202) 555-0125", "+1111 (202) 555-0125", "636 85 789", "636 85 67 893"};
Pattern pattern = Pattern.compile(patterns);
for(String phoneNumber : invalidPhoneNumbers) {
Matcher matcher = pattern.matcher(phoneNumber);
assertFalse(matcher.matches());
}
}
}

View File

@ -10,4 +10,5 @@ This module contains articles about the Stream API in Java.
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
- [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams)
- [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals)
- [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close)
- More articles: [[<-- prev>]](/../core-java-streams-2)

View File

@ -0,0 +1,22 @@
package com.baeldung.late
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class LateInitUnitTest {
private lateinit var answer: String
@Test(expected = UninitializedPropertyAccessException::class)
fun givenLateInit_WhenNotInitialized_ShouldThrowAnException() {
answer.length
}
@Test
fun givenLateInit_TheIsInitialized_ReturnsTheInitializationStatus() {
assertFalse { this::answer.isInitialized }
answer = "42"
assertTrue { this::answer.isInitialized }
}
}

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys)

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

@ -17,3 +17,4 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [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);

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